]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/sqlite3/sqlite3.c
Merge ^/head r285341 through r285792.
[FreeBSD/FreeBSD.git] / contrib / sqlite3 / sqlite3.c
1 /******************************************************************************
2 ** This file is an amalgamation of many separate C source files from SQLite
3 ** version 3.8.9.  By combining all the individual C code files into this 
4 ** single large file, the entire code can be compiled as a single translation
5 ** unit.  This allows many compilers to do optimizations that would not be
6 ** possible if the files were compiled separately.  Performance improvements
7 ** of 5% or more are commonly seen when SQLite is compiled as a single
8 ** translation unit.
9 **
10 ** This file is all you need to compile SQLite.  To use SQLite in other
11 ** programs, you need this file and the "sqlite3.h" header file that defines
12 ** the programming interface to the SQLite library.  (If you do not have 
13 ** the "sqlite3.h" header file at hand, you will find a copy embedded within
14 ** the text of this file.  Search for "Begin file sqlite3.h" to find the start
15 ** of the embedded sqlite3.h header file.) Additional code files may be needed
16 ** if you want a wrapper to interface SQLite with your choice of programming
17 ** language. The code for the "sqlite3" command-line shell is also in a
18 ** separate file. This file contains only code for the core SQLite library.
19 */
20 #define SQLITE_CORE 1
21 #define SQLITE_AMALGAMATION 1
22 #ifndef SQLITE_PRIVATE
23 # define SQLITE_PRIVATE static
24 #endif
25 /************** Begin file sqliteInt.h ***************************************/
26 /*
27 ** 2001 September 15
28 **
29 ** The author disclaims copyright to this source code.  In place of
30 ** a legal notice, here is a blessing:
31 **
32 **    May you do good and not evil.
33 **    May you find forgiveness for yourself and forgive others.
34 **    May you share freely, never taking more than you give.
35 **
36 *************************************************************************
37 ** Internal interface definitions for SQLite.
38 **
39 */
40 #ifndef _SQLITEINT_H_
41 #define _SQLITEINT_H_
42
43 /*
44 ** Include the header file used to customize the compiler options for MSVC.
45 ** This should be done first so that it can successfully prevent spurious
46 ** compiler warnings due to subsequent content in this file and other files
47 ** that are included by this file.
48 */
49 /************** Include msvc.h in the middle of sqliteInt.h ******************/
50 /************** Begin file msvc.h ********************************************/
51 /*
52 ** 2015 January 12
53 **
54 ** The author disclaims copyright to this source code.  In place of
55 ** a legal notice, here is a blessing:
56 **
57 **    May you do good and not evil.
58 **    May you find forgiveness for yourself and forgive others.
59 **    May you share freely, never taking more than you give.
60 **
61 ******************************************************************************
62 **
63 ** This file contains code that is specific to MSVC.
64 */
65 #ifndef _MSVC_H_
66 #define _MSVC_H_
67
68 #if defined(_MSC_VER)
69 #pragma warning(disable : 4054)
70 #pragma warning(disable : 4055)
71 #pragma warning(disable : 4100)
72 #pragma warning(disable : 4127)
73 #pragma warning(disable : 4152)
74 #pragma warning(disable : 4189)
75 #pragma warning(disable : 4206)
76 #pragma warning(disable : 4210)
77 #pragma warning(disable : 4232)
78 #pragma warning(disable : 4244)
79 #pragma warning(disable : 4305)
80 #pragma warning(disable : 4306)
81 #pragma warning(disable : 4702)
82 #pragma warning(disable : 4706)
83 #endif /* defined(_MSC_VER) */
84
85 #endif /* _MSVC_H_ */
86
87 /************** End of msvc.h ************************************************/
88 /************** Continuing where we left off in sqliteInt.h ******************/
89
90 /*
91 ** Special setup for VxWorks
92 */
93 /************** Include vxworks.h in the middle of sqliteInt.h ***************/
94 /************** Begin file vxworks.h *****************************************/
95 /*
96 ** 2015-03-02
97 **
98 ** The author disclaims copyright to this source code.  In place of
99 ** a legal notice, here is a blessing:
100 **
101 **    May you do good and not evil.
102 **    May you find forgiveness for yourself and forgive others.
103 **    May you share freely, never taking more than you give.
104 **
105 ******************************************************************************
106 **
107 ** This file contains code that is specific to Wind River's VxWorks
108 */
109 #if defined(__RTP__) || defined(_WRS_KERNEL)
110 /* This is VxWorks.  Set up things specially for that OS
111 */
112 #include <vxWorks.h>
113 #include <pthread.h>  /* amalgamator: dontcache */
114 #define OS_VXWORKS 1
115 #define SQLITE_OS_OTHER 0
116 #define SQLITE_HOMEGROWN_RECURSIVE_MUTEX 1
117 #define SQLITE_OMIT_LOAD_EXTENSION 1
118 #define SQLITE_ENABLE_LOCKING_STYLE 0
119 #define HAVE_UTIME 1
120 #else
121 /* This is not VxWorks. */
122 #define OS_VXWORKS 0
123 #endif /* defined(_WRS_KERNEL) */
124
125 /************** End of vxworks.h *********************************************/
126 /************** Continuing where we left off in sqliteInt.h ******************/
127
128 /*
129 ** These #defines should enable >2GB file support on POSIX if the
130 ** underlying operating system supports it.  If the OS lacks
131 ** large file support, or if the OS is windows, these should be no-ops.
132 **
133 ** Ticket #2739:  The _LARGEFILE_SOURCE macro must appear before any
134 ** system #includes.  Hence, this block of code must be the very first
135 ** code in all source files.
136 **
137 ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
138 ** on the compiler command line.  This is necessary if you are compiling
139 ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
140 ** on an older machine (ex: Red Hat 6.0).  If you compile on Red Hat 7.2
141 ** without this option, LFS is enable.  But LFS does not exist in the kernel
142 ** in Red Hat 6.0, so the code won't work.  Hence, for maximum binary
143 ** portability you should omit LFS.
144 **
145 ** The previous paragraph was written in 2005.  (This paragraph is written
146 ** on 2008-11-28.) These days, all Linux kernels support large files, so
147 ** you should probably leave LFS enabled.  But some embedded platforms might
148 ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
149 **
150 ** Similar is true for Mac OS X.  LFS is only supported on Mac OS X 9 and later.
151 */
152 #ifndef SQLITE_DISABLE_LFS
153 # define _LARGE_FILE       1
154 # ifndef _FILE_OFFSET_BITS
155 #   define _FILE_OFFSET_BITS 64
156 # endif
157 # define _LARGEFILE_SOURCE 1
158 #endif
159
160 /* Needed for various definitions... */
161 #if defined(__GNUC__) && !defined(_GNU_SOURCE)
162 # define _GNU_SOURCE
163 #endif
164
165 #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
166 # define _BSD_SOURCE
167 #endif
168
169 /*
170 ** For MinGW, check to see if we can include the header file containing its
171 ** version information, among other things.  Normally, this internal MinGW
172 ** header file would [only] be included automatically by other MinGW header
173 ** files; however, the contained version information is now required by this
174 ** header file to work around binary compatibility issues (see below) and
175 ** this is the only known way to reliably obtain it.  This entire #if block
176 ** would be completely unnecessary if there was any other way of detecting
177 ** MinGW via their preprocessor (e.g. if they customized their GCC to define
178 ** some MinGW-specific macros).  When compiling for MinGW, either the
179 ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
180 ** defined; otherwise, detection of conditions specific to MinGW will be
181 ** disabled.
182 */
183 #if defined(_HAVE_MINGW_H)
184 # include "mingw.h"
185 #elif defined(_HAVE__MINGW_H)
186 # include "_mingw.h"
187 #endif
188
189 /*
190 ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
191 ** define is required to maintain binary compatibility with the MSVC runtime
192 ** library in use (e.g. for Windows XP).
193 */
194 #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
195     defined(_WIN32) && !defined(_WIN64) && \
196     defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
197     defined(__MSVCRT__)
198 # define _USE_32BIT_TIME_T
199 #endif
200
201 /* The public SQLite interface.  The _FILE_OFFSET_BITS macro must appear
202 ** first in QNX.  Also, the _USE_32BIT_TIME_T macro must appear first for
203 ** MinGW.
204 */
205 /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
206 /************** Begin file sqlite3.h *****************************************/
207 /*
208 ** 2001 September 15
209 **
210 ** The author disclaims copyright to this source code.  In place of
211 ** a legal notice, here is a blessing:
212 **
213 **    May you do good and not evil.
214 **    May you find forgiveness for yourself and forgive others.
215 **    May you share freely, never taking more than you give.
216 **
217 *************************************************************************
218 ** This header file defines the interface that the SQLite library
219 ** presents to client programs.  If a C-function, structure, datatype,
220 ** or constant definition does not appear in this file, then it is
221 ** not a published API of SQLite, is subject to change without
222 ** notice, and should not be referenced by programs that use SQLite.
223 **
224 ** Some of the definitions that are in this file are marked as
225 ** "experimental".  Experimental interfaces are normally new
226 ** features recently added to SQLite.  We do not anticipate changes
227 ** to experimental interfaces but reserve the right to make minor changes
228 ** if experience from use "in the wild" suggest such changes are prudent.
229 **
230 ** The official C-language API documentation for SQLite is derived
231 ** from comments in this file.  This file is the authoritative source
232 ** on how SQLite interfaces are suppose to operate.
233 **
234 ** The name of this file under configuration management is "sqlite.h.in".
235 ** The makefile makes some minor changes to this file (such as inserting
236 ** the version number) and changes its name to "sqlite3.h" as
237 ** part of the build process.
238 */
239 #ifndef _SQLITE3_H_
240 #define _SQLITE3_H_
241 #include <stdarg.h>     /* Needed for the definition of va_list */
242
243 /*
244 ** Make sure we can call this stuff from C++.
245 */
246 #if 0
247 extern "C" {
248 #endif
249
250
251 /*
252 ** Provide the ability to override linkage features of the interface.
253 */
254 #ifndef SQLITE_EXTERN
255 # define SQLITE_EXTERN extern
256 #endif
257 #ifndef SQLITE_API
258 # define SQLITE_API
259 #endif
260 #ifndef SQLITE_CDECL
261 # define SQLITE_CDECL
262 #endif
263 #ifndef SQLITE_STDCALL
264 # define SQLITE_STDCALL
265 #endif
266
267 /*
268 ** These no-op macros are used in front of interfaces to mark those
269 ** interfaces as either deprecated or experimental.  New applications
270 ** should not use deprecated interfaces - they are supported for backwards
271 ** compatibility only.  Application writers should be aware that
272 ** experimental interfaces are subject to change in point releases.
273 **
274 ** These macros used to resolve to various kinds of compiler magic that
275 ** would generate warning messages when they were used.  But that
276 ** compiler magic ended up generating such a flurry of bug reports
277 ** that we have taken it all out and gone back to using simple
278 ** noop macros.
279 */
280 #define SQLITE_DEPRECATED
281 #define SQLITE_EXPERIMENTAL
282
283 /*
284 ** Ensure these symbols were not defined by some previous header file.
285 */
286 #ifdef SQLITE_VERSION
287 # undef SQLITE_VERSION
288 #endif
289 #ifdef SQLITE_VERSION_NUMBER
290 # undef SQLITE_VERSION_NUMBER
291 #endif
292
293 /*
294 ** CAPI3REF: Compile-Time Library Version Numbers
295 **
296 ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
297 ** evaluates to a string literal that is the SQLite version in the
298 ** format "X.Y.Z" where X is the major version number (always 3 for
299 ** SQLite3) and Y is the minor version number and Z is the release number.)^
300 ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
301 ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
302 ** numbers used in [SQLITE_VERSION].)^
303 ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
304 ** be larger than the release from which it is derived.  Either Y will
305 ** be held constant and Z will be incremented or else Y will be incremented
306 ** and Z will be reset to zero.
307 **
308 ** Since version 3.6.18, SQLite source code has been stored in the
309 ** <a href="http://www.fossil-scm.org/">Fossil configuration management
310 ** system</a>.  ^The SQLITE_SOURCE_ID macro evaluates to
311 ** a string which identifies a particular check-in of SQLite
312 ** within its configuration management system.  ^The SQLITE_SOURCE_ID
313 ** string contains the date and time of the check-in (UTC) and an SHA1
314 ** hash of the entire source tree.
315 **
316 ** See also: [sqlite3_libversion()],
317 ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
318 ** [sqlite_version()] and [sqlite_source_id()].
319 */
320 #define SQLITE_VERSION        "3.8.9"
321 #define SQLITE_VERSION_NUMBER 3008009
322 #define SQLITE_SOURCE_ID      "2015-04-08 12:16:33 8a8ffc862e96f57aa698f93de10dee28e69f6e09"
323
324 /*
325 ** CAPI3REF: Run-Time Library Version Numbers
326 ** KEYWORDS: sqlite3_version, sqlite3_sourceid
327 **
328 ** These interfaces provide the same information as the [SQLITE_VERSION],
329 ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
330 ** but are associated with the library instead of the header file.  ^(Cautious
331 ** programmers might include assert() statements in their application to
332 ** verify that values returned by these interfaces match the macros in
333 ** the header, and thus insure that the application is
334 ** compiled with matching library and header files.
335 **
336 ** <blockquote><pre>
337 ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
338 ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
339 ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
340 ** </pre></blockquote>)^
341 **
342 ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
343 ** macro.  ^The sqlite3_libversion() function returns a pointer to the
344 ** to the sqlite3_version[] string constant.  The sqlite3_libversion()
345 ** function is provided for use in DLLs since DLL users usually do not have
346 ** direct access to string constants within the DLL.  ^The
347 ** sqlite3_libversion_number() function returns an integer equal to
348 ** [SQLITE_VERSION_NUMBER].  ^The sqlite3_sourceid() function returns 
349 ** a pointer to a string constant whose value is the same as the 
350 ** [SQLITE_SOURCE_ID] C preprocessor macro.
351 **
352 ** See also: [sqlite_version()] and [sqlite_source_id()].
353 */
354 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
355 SQLITE_API const char *SQLITE_STDCALL sqlite3_libversion(void);
356 SQLITE_API const char *SQLITE_STDCALL sqlite3_sourceid(void);
357 SQLITE_API int SQLITE_STDCALL sqlite3_libversion_number(void);
358
359 /*
360 ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
361 **
362 ** ^The sqlite3_compileoption_used() function returns 0 or 1 
363 ** indicating whether the specified option was defined at 
364 ** compile time.  ^The SQLITE_ prefix may be omitted from the 
365 ** option name passed to sqlite3_compileoption_used().  
366 **
367 ** ^The sqlite3_compileoption_get() function allows iterating
368 ** over the list of options that were defined at compile time by
369 ** returning the N-th compile time option string.  ^If N is out of range,
370 ** sqlite3_compileoption_get() returns a NULL pointer.  ^The SQLITE_ 
371 ** prefix is omitted from any strings returned by 
372 ** sqlite3_compileoption_get().
373 **
374 ** ^Support for the diagnostic functions sqlite3_compileoption_used()
375 ** and sqlite3_compileoption_get() may be omitted by specifying the 
376 ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
377 **
378 ** See also: SQL functions [sqlite_compileoption_used()] and
379 ** [sqlite_compileoption_get()] and the [compile_options pragma].
380 */
381 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
382 SQLITE_API int SQLITE_STDCALL sqlite3_compileoption_used(const char *zOptName);
383 SQLITE_API const char *SQLITE_STDCALL sqlite3_compileoption_get(int N);
384 #endif
385
386 /*
387 ** CAPI3REF: Test To See If The Library Is Threadsafe
388 **
389 ** ^The sqlite3_threadsafe() function returns zero if and only if
390 ** SQLite was compiled with mutexing code omitted due to the
391 ** [SQLITE_THREADSAFE] compile-time option being set to 0.
392 **
393 ** SQLite can be compiled with or without mutexes.  When
394 ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
395 ** are enabled and SQLite is threadsafe.  When the
396 ** [SQLITE_THREADSAFE] macro is 0, 
397 ** the mutexes are omitted.  Without the mutexes, it is not safe
398 ** to use SQLite concurrently from more than one thread.
399 **
400 ** Enabling mutexes incurs a measurable performance penalty.
401 ** So if speed is of utmost importance, it makes sense to disable
402 ** the mutexes.  But for maximum safety, mutexes should be enabled.
403 ** ^The default behavior is for mutexes to be enabled.
404 **
405 ** This interface can be used by an application to make sure that the
406 ** version of SQLite that it is linking against was compiled with
407 ** the desired setting of the [SQLITE_THREADSAFE] macro.
408 **
409 ** This interface only reports on the compile-time mutex setting
410 ** of the [SQLITE_THREADSAFE] flag.  If SQLite is compiled with
411 ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
412 ** can be fully or partially disabled using a call to [sqlite3_config()]
413 ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
414 ** or [SQLITE_CONFIG_SERIALIZED].  ^(The return value of the
415 ** sqlite3_threadsafe() function shows only the compile-time setting of
416 ** thread safety, not any run-time changes to that setting made by
417 ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
418 ** is unchanged by calls to sqlite3_config().)^
419 **
420 ** See the [threading mode] documentation for additional information.
421 */
422 SQLITE_API int SQLITE_STDCALL sqlite3_threadsafe(void);
423
424 /*
425 ** CAPI3REF: Database Connection Handle
426 ** KEYWORDS: {database connection} {database connections}
427 **
428 ** Each open SQLite database is represented by a pointer to an instance of
429 ** the opaque structure named "sqlite3".  It is useful to think of an sqlite3
430 ** pointer as an object.  The [sqlite3_open()], [sqlite3_open16()], and
431 ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
432 ** and [sqlite3_close_v2()] are its destructors.  There are many other
433 ** interfaces (such as
434 ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
435 ** [sqlite3_busy_timeout()] to name but three) that are methods on an
436 ** sqlite3 object.
437 */
438 typedef struct sqlite3 sqlite3;
439
440 /*
441 ** CAPI3REF: 64-Bit Integer Types
442 ** KEYWORDS: sqlite_int64 sqlite_uint64
443 **
444 ** Because there is no cross-platform way to specify 64-bit integer types
445 ** SQLite includes typedefs for 64-bit signed and unsigned integers.
446 **
447 ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
448 ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
449 ** compatibility only.
450 **
451 ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
452 ** between -9223372036854775808 and +9223372036854775807 inclusive.  ^The
453 ** sqlite3_uint64 and sqlite_uint64 types can store integer values 
454 ** between 0 and +18446744073709551615 inclusive.
455 */
456 #ifdef SQLITE_INT64_TYPE
457   typedef SQLITE_INT64_TYPE sqlite_int64;
458   typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
459 #elif defined(_MSC_VER) || defined(__BORLANDC__)
460   typedef __int64 sqlite_int64;
461   typedef unsigned __int64 sqlite_uint64;
462 #else
463   typedef long long int sqlite_int64;
464   typedef unsigned long long int sqlite_uint64;
465 #endif
466 typedef sqlite_int64 sqlite3_int64;
467 typedef sqlite_uint64 sqlite3_uint64;
468
469 /*
470 ** If compiling for a processor that lacks floating point support,
471 ** substitute integer for floating-point.
472 */
473 #ifdef SQLITE_OMIT_FLOATING_POINT
474 # define double sqlite3_int64
475 #endif
476
477 /*
478 ** CAPI3REF: Closing A Database Connection
479 **
480 ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
481 ** for the [sqlite3] object.
482 ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
483 ** the [sqlite3] object is successfully destroyed and all associated
484 ** resources are deallocated.
485 **
486 ** ^If the database connection is associated with unfinalized prepared
487 ** statements or unfinished sqlite3_backup objects then sqlite3_close()
488 ** will leave the database connection open and return [SQLITE_BUSY].
489 ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
490 ** and/or unfinished sqlite3_backups, then the database connection becomes
491 ** an unusable "zombie" which will automatically be deallocated when the
492 ** last prepared statement is finalized or the last sqlite3_backup is
493 ** finished.  The sqlite3_close_v2() interface is intended for use with
494 ** host languages that are garbage collected, and where the order in which
495 ** destructors are called is arbitrary.
496 **
497 ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
498 ** [sqlite3_blob_close | close] all [BLOB handles], and 
499 ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
500 ** with the [sqlite3] object prior to attempting to close the object.  ^If
501 ** sqlite3_close_v2() is called on a [database connection] that still has
502 ** outstanding [prepared statements], [BLOB handles], and/or
503 ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
504 ** of resources is deferred until all [prepared statements], [BLOB handles],
505 ** and [sqlite3_backup] objects are also destroyed.
506 **
507 ** ^If an [sqlite3] object is destroyed while a transaction is open,
508 ** the transaction is automatically rolled back.
509 **
510 ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
511 ** must be either a NULL
512 ** pointer or an [sqlite3] object pointer obtained
513 ** from [sqlite3_open()], [sqlite3_open16()], or
514 ** [sqlite3_open_v2()], and not previously closed.
515 ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
516 ** argument is a harmless no-op.
517 */
518 SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3*);
519 SQLITE_API int SQLITE_STDCALL sqlite3_close_v2(sqlite3*);
520
521 /*
522 ** The type for a callback function.
523 ** This is legacy and deprecated.  It is included for historical
524 ** compatibility and is not documented.
525 */
526 typedef int (*sqlite3_callback)(void*,int,char**, char**);
527
528 /*
529 ** CAPI3REF: One-Step Query Execution Interface
530 **
531 ** The sqlite3_exec() interface is a convenience wrapper around
532 ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
533 ** that allows an application to run multiple statements of SQL
534 ** without having to use a lot of C code. 
535 **
536 ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
537 ** semicolon-separate SQL statements passed into its 2nd argument,
538 ** in the context of the [database connection] passed in as its 1st
539 ** argument.  ^If the callback function of the 3rd argument to
540 ** sqlite3_exec() is not NULL, then it is invoked for each result row
541 ** coming out of the evaluated SQL statements.  ^The 4th argument to
542 ** sqlite3_exec() is relayed through to the 1st argument of each
543 ** callback invocation.  ^If the callback pointer to sqlite3_exec()
544 ** is NULL, then no callback is ever invoked and result rows are
545 ** ignored.
546 **
547 ** ^If an error occurs while evaluating the SQL statements passed into
548 ** sqlite3_exec(), then execution of the current statement stops and
549 ** subsequent statements are skipped.  ^If the 5th parameter to sqlite3_exec()
550 ** is not NULL then any error message is written into memory obtained
551 ** from [sqlite3_malloc()] and passed back through the 5th parameter.
552 ** To avoid memory leaks, the application should invoke [sqlite3_free()]
553 ** on error message strings returned through the 5th parameter of
554 ** of sqlite3_exec() after the error message string is no longer needed.
555 ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
556 ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
557 ** NULL before returning.
558 **
559 ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
560 ** routine returns SQLITE_ABORT without invoking the callback again and
561 ** without running any subsequent SQL statements.
562 **
563 ** ^The 2nd argument to the sqlite3_exec() callback function is the
564 ** number of columns in the result.  ^The 3rd argument to the sqlite3_exec()
565 ** callback is an array of pointers to strings obtained as if from
566 ** [sqlite3_column_text()], one for each column.  ^If an element of a
567 ** result row is NULL then the corresponding string pointer for the
568 ** sqlite3_exec() callback is a NULL pointer.  ^The 4th argument to the
569 ** sqlite3_exec() callback is an array of pointers to strings where each
570 ** entry represents the name of corresponding result column as obtained
571 ** from [sqlite3_column_name()].
572 **
573 ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
574 ** to an empty string, or a pointer that contains only whitespace and/or 
575 ** SQL comments, then no SQL statements are evaluated and the database
576 ** is not changed.
577 **
578 ** Restrictions:
579 **
580 ** <ul>
581 ** <li> The application must insure that the 1st parameter to sqlite3_exec()
582 **      is a valid and open [database connection].
583 ** <li> The application must not close the [database connection] specified by
584 **      the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
585 ** <li> The application must not modify the SQL statement text passed into
586 **      the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
587 ** </ul>
588 */
589 SQLITE_API int SQLITE_STDCALL sqlite3_exec(
590   sqlite3*,                                  /* An open database */
591   const char *sql,                           /* SQL to be evaluated */
592   int (*callback)(void*,int,char**,char**),  /* Callback function */
593   void *,                                    /* 1st argument to callback */
594   char **errmsg                              /* Error msg written here */
595 );
596
597 /*
598 ** CAPI3REF: Result Codes
599 ** KEYWORDS: {result code definitions}
600 **
601 ** Many SQLite functions return an integer result code from the set shown
602 ** here in order to indicate success or failure.
603 **
604 ** New error codes may be added in future versions of SQLite.
605 **
606 ** See also: [extended result code definitions]
607 */
608 #define SQLITE_OK           0   /* Successful result */
609 /* beginning-of-error-codes */
610 #define SQLITE_ERROR        1   /* SQL error or missing database */
611 #define SQLITE_INTERNAL     2   /* Internal logic error in SQLite */
612 #define SQLITE_PERM         3   /* Access permission denied */
613 #define SQLITE_ABORT        4   /* Callback routine requested an abort */
614 #define SQLITE_BUSY         5   /* The database file is locked */
615 #define SQLITE_LOCKED       6   /* A table in the database is locked */
616 #define SQLITE_NOMEM        7   /* A malloc() failed */
617 #define SQLITE_READONLY     8   /* Attempt to write a readonly database */
618 #define SQLITE_INTERRUPT    9   /* Operation terminated by sqlite3_interrupt()*/
619 #define SQLITE_IOERR       10   /* Some kind of disk I/O error occurred */
620 #define SQLITE_CORRUPT     11   /* The database disk image is malformed */
621 #define SQLITE_NOTFOUND    12   /* Unknown opcode in sqlite3_file_control() */
622 #define SQLITE_FULL        13   /* Insertion failed because database is full */
623 #define SQLITE_CANTOPEN    14   /* Unable to open the database file */
624 #define SQLITE_PROTOCOL    15   /* Database lock protocol error */
625 #define SQLITE_EMPTY       16   /* Database is empty */
626 #define SQLITE_SCHEMA      17   /* The database schema changed */
627 #define SQLITE_TOOBIG      18   /* String or BLOB exceeds size limit */
628 #define SQLITE_CONSTRAINT  19   /* Abort due to constraint violation */
629 #define SQLITE_MISMATCH    20   /* Data type mismatch */
630 #define SQLITE_MISUSE      21   /* Library used incorrectly */
631 #define SQLITE_NOLFS       22   /* Uses OS features not supported on host */
632 #define SQLITE_AUTH        23   /* Authorization denied */
633 #define SQLITE_FORMAT      24   /* Auxiliary database format error */
634 #define SQLITE_RANGE       25   /* 2nd parameter to sqlite3_bind out of range */
635 #define SQLITE_NOTADB      26   /* File opened that is not a database file */
636 #define SQLITE_NOTICE      27   /* Notifications from sqlite3_log() */
637 #define SQLITE_WARNING     28   /* Warnings from sqlite3_log() */
638 #define SQLITE_ROW         100  /* sqlite3_step() has another row ready */
639 #define SQLITE_DONE        101  /* sqlite3_step() has finished executing */
640 /* end-of-error-codes */
641
642 /*
643 ** CAPI3REF: Extended Result Codes
644 ** KEYWORDS: {extended result code definitions}
645 **
646 ** In its default configuration, SQLite API routines return one of 30 integer
647 ** [result codes].  However, experience has shown that many of
648 ** these result codes are too coarse-grained.  They do not provide as
649 ** much information about problems as programmers might like.  In an effort to
650 ** address this, newer versions of SQLite (version 3.3.8 and later) include
651 ** support for additional result codes that provide more detailed information
652 ** about errors. These [extended result codes] are enabled or disabled
653 ** on a per database connection basis using the
654 ** [sqlite3_extended_result_codes()] API.  Or, the extended code for
655 ** the most recent error can be obtained using
656 ** [sqlite3_extended_errcode()].
657 */
658 #define SQLITE_IOERR_READ              (SQLITE_IOERR | (1<<8))
659 #define SQLITE_IOERR_SHORT_READ        (SQLITE_IOERR | (2<<8))
660 #define SQLITE_IOERR_WRITE             (SQLITE_IOERR | (3<<8))
661 #define SQLITE_IOERR_FSYNC             (SQLITE_IOERR | (4<<8))
662 #define SQLITE_IOERR_DIR_FSYNC         (SQLITE_IOERR | (5<<8))
663 #define SQLITE_IOERR_TRUNCATE          (SQLITE_IOERR | (6<<8))
664 #define SQLITE_IOERR_FSTAT             (SQLITE_IOERR | (7<<8))
665 #define SQLITE_IOERR_UNLOCK            (SQLITE_IOERR | (8<<8))
666 #define SQLITE_IOERR_RDLOCK            (SQLITE_IOERR | (9<<8))
667 #define SQLITE_IOERR_DELETE            (SQLITE_IOERR | (10<<8))
668 #define SQLITE_IOERR_BLOCKED           (SQLITE_IOERR | (11<<8))
669 #define SQLITE_IOERR_NOMEM             (SQLITE_IOERR | (12<<8))
670 #define SQLITE_IOERR_ACCESS            (SQLITE_IOERR | (13<<8))
671 #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
672 #define SQLITE_IOERR_LOCK              (SQLITE_IOERR | (15<<8))
673 #define SQLITE_IOERR_CLOSE             (SQLITE_IOERR | (16<<8))
674 #define SQLITE_IOERR_DIR_CLOSE         (SQLITE_IOERR | (17<<8))
675 #define SQLITE_IOERR_SHMOPEN           (SQLITE_IOERR | (18<<8))
676 #define SQLITE_IOERR_SHMSIZE           (SQLITE_IOERR | (19<<8))
677 #define SQLITE_IOERR_SHMLOCK           (SQLITE_IOERR | (20<<8))
678 #define SQLITE_IOERR_SHMMAP            (SQLITE_IOERR | (21<<8))
679 #define SQLITE_IOERR_SEEK              (SQLITE_IOERR | (22<<8))
680 #define SQLITE_IOERR_DELETE_NOENT      (SQLITE_IOERR | (23<<8))
681 #define SQLITE_IOERR_MMAP              (SQLITE_IOERR | (24<<8))
682 #define SQLITE_IOERR_GETTEMPPATH       (SQLITE_IOERR | (25<<8))
683 #define SQLITE_IOERR_CONVPATH          (SQLITE_IOERR | (26<<8))
684 #define SQLITE_LOCKED_SHAREDCACHE      (SQLITE_LOCKED |  (1<<8))
685 #define SQLITE_BUSY_RECOVERY           (SQLITE_BUSY   |  (1<<8))
686 #define SQLITE_BUSY_SNAPSHOT           (SQLITE_BUSY   |  (2<<8))
687 #define SQLITE_CANTOPEN_NOTEMPDIR      (SQLITE_CANTOPEN | (1<<8))
688 #define SQLITE_CANTOPEN_ISDIR          (SQLITE_CANTOPEN | (2<<8))
689 #define SQLITE_CANTOPEN_FULLPATH       (SQLITE_CANTOPEN | (3<<8))
690 #define SQLITE_CANTOPEN_CONVPATH       (SQLITE_CANTOPEN | (4<<8))
691 #define SQLITE_CORRUPT_VTAB            (SQLITE_CORRUPT | (1<<8))
692 #define SQLITE_READONLY_RECOVERY       (SQLITE_READONLY | (1<<8))
693 #define SQLITE_READONLY_CANTLOCK       (SQLITE_READONLY | (2<<8))
694 #define SQLITE_READONLY_ROLLBACK       (SQLITE_READONLY | (3<<8))
695 #define SQLITE_READONLY_DBMOVED        (SQLITE_READONLY | (4<<8))
696 #define SQLITE_ABORT_ROLLBACK          (SQLITE_ABORT | (2<<8))
697 #define SQLITE_CONSTRAINT_CHECK        (SQLITE_CONSTRAINT | (1<<8))
698 #define SQLITE_CONSTRAINT_COMMITHOOK   (SQLITE_CONSTRAINT | (2<<8))
699 #define SQLITE_CONSTRAINT_FOREIGNKEY   (SQLITE_CONSTRAINT | (3<<8))
700 #define SQLITE_CONSTRAINT_FUNCTION     (SQLITE_CONSTRAINT | (4<<8))
701 #define SQLITE_CONSTRAINT_NOTNULL      (SQLITE_CONSTRAINT | (5<<8))
702 #define SQLITE_CONSTRAINT_PRIMARYKEY   (SQLITE_CONSTRAINT | (6<<8))
703 #define SQLITE_CONSTRAINT_TRIGGER      (SQLITE_CONSTRAINT | (7<<8))
704 #define SQLITE_CONSTRAINT_UNIQUE       (SQLITE_CONSTRAINT | (8<<8))
705 #define SQLITE_CONSTRAINT_VTAB         (SQLITE_CONSTRAINT | (9<<8))
706 #define SQLITE_CONSTRAINT_ROWID        (SQLITE_CONSTRAINT |(10<<8))
707 #define SQLITE_NOTICE_RECOVER_WAL      (SQLITE_NOTICE | (1<<8))
708 #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
709 #define SQLITE_WARNING_AUTOINDEX       (SQLITE_WARNING | (1<<8))
710 #define SQLITE_AUTH_USER               (SQLITE_AUTH | (1<<8))
711
712 /*
713 ** CAPI3REF: Flags For File Open Operations
714 **
715 ** These bit values are intended for use in the
716 ** 3rd parameter to the [sqlite3_open_v2()] interface and
717 ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
718 */
719 #define SQLITE_OPEN_READONLY         0x00000001  /* Ok for sqlite3_open_v2() */
720 #define SQLITE_OPEN_READWRITE        0x00000002  /* Ok for sqlite3_open_v2() */
721 #define SQLITE_OPEN_CREATE           0x00000004  /* Ok for sqlite3_open_v2() */
722 #define SQLITE_OPEN_DELETEONCLOSE    0x00000008  /* VFS only */
723 #define SQLITE_OPEN_EXCLUSIVE        0x00000010  /* VFS only */
724 #define SQLITE_OPEN_AUTOPROXY        0x00000020  /* VFS only */
725 #define SQLITE_OPEN_URI              0x00000040  /* Ok for sqlite3_open_v2() */
726 #define SQLITE_OPEN_MEMORY           0x00000080  /* Ok for sqlite3_open_v2() */
727 #define SQLITE_OPEN_MAIN_DB          0x00000100  /* VFS only */
728 #define SQLITE_OPEN_TEMP_DB          0x00000200  /* VFS only */
729 #define SQLITE_OPEN_TRANSIENT_DB     0x00000400  /* VFS only */
730 #define SQLITE_OPEN_MAIN_JOURNAL     0x00000800  /* VFS only */
731 #define SQLITE_OPEN_TEMP_JOURNAL     0x00001000  /* VFS only */
732 #define SQLITE_OPEN_SUBJOURNAL       0x00002000  /* VFS only */
733 #define SQLITE_OPEN_MASTER_JOURNAL   0x00004000  /* VFS only */
734 #define SQLITE_OPEN_NOMUTEX          0x00008000  /* Ok for sqlite3_open_v2() */
735 #define SQLITE_OPEN_FULLMUTEX        0x00010000  /* Ok for sqlite3_open_v2() */
736 #define SQLITE_OPEN_SHAREDCACHE      0x00020000  /* Ok for sqlite3_open_v2() */
737 #define SQLITE_OPEN_PRIVATECACHE     0x00040000  /* Ok for sqlite3_open_v2() */
738 #define SQLITE_OPEN_WAL              0x00080000  /* VFS only */
739
740 /* Reserved:                         0x00F00000 */
741
742 /*
743 ** CAPI3REF: Device Characteristics
744 **
745 ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
746 ** object returns an integer which is a vector of these
747 ** bit values expressing I/O characteristics of the mass storage
748 ** device that holds the file that the [sqlite3_io_methods]
749 ** refers to.
750 **
751 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
752 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
753 ** mean that writes of blocks that are nnn bytes in size and
754 ** are aligned to an address which is an integer multiple of
755 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
756 ** that when data is appended to a file, the data is appended
757 ** first then the size of the file is extended, never the other
758 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
759 ** information is written to disk in the same order as calls
760 ** to xWrite().  The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
761 ** after reboot following a crash or power loss, the only bytes in a
762 ** file that were written at the application level might have changed
763 ** and that adjacent bytes, even bytes within the same sector are
764 ** guaranteed to be unchanged.  The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
765 ** flag indicate that a file cannot be deleted when open.  The
766 ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
767 ** read-only media and cannot be changed even by processes with
768 ** elevated privileges.
769 */
770 #define SQLITE_IOCAP_ATOMIC                 0x00000001
771 #define SQLITE_IOCAP_ATOMIC512              0x00000002
772 #define SQLITE_IOCAP_ATOMIC1K               0x00000004
773 #define SQLITE_IOCAP_ATOMIC2K               0x00000008
774 #define SQLITE_IOCAP_ATOMIC4K               0x00000010
775 #define SQLITE_IOCAP_ATOMIC8K               0x00000020
776 #define SQLITE_IOCAP_ATOMIC16K              0x00000040
777 #define SQLITE_IOCAP_ATOMIC32K              0x00000080
778 #define SQLITE_IOCAP_ATOMIC64K              0x00000100
779 #define SQLITE_IOCAP_SAFE_APPEND            0x00000200
780 #define SQLITE_IOCAP_SEQUENTIAL             0x00000400
781 #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN  0x00000800
782 #define SQLITE_IOCAP_POWERSAFE_OVERWRITE    0x00001000
783 #define SQLITE_IOCAP_IMMUTABLE              0x00002000
784
785 /*
786 ** CAPI3REF: File Locking Levels
787 **
788 ** SQLite uses one of these integer values as the second
789 ** argument to calls it makes to the xLock() and xUnlock() methods
790 ** of an [sqlite3_io_methods] object.
791 */
792 #define SQLITE_LOCK_NONE          0
793 #define SQLITE_LOCK_SHARED        1
794 #define SQLITE_LOCK_RESERVED      2
795 #define SQLITE_LOCK_PENDING       3
796 #define SQLITE_LOCK_EXCLUSIVE     4
797
798 /*
799 ** CAPI3REF: Synchronization Type Flags
800 **
801 ** When SQLite invokes the xSync() method of an
802 ** [sqlite3_io_methods] object it uses a combination of
803 ** these integer values as the second argument.
804 **
805 ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
806 ** sync operation only needs to flush data to mass storage.  Inode
807 ** information need not be flushed. If the lower four bits of the flag
808 ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
809 ** If the lower four bits equal SQLITE_SYNC_FULL, that means
810 ** to use Mac OS X style fullsync instead of fsync().
811 **
812 ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
813 ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
814 ** settings.  The [synchronous pragma] determines when calls to the
815 ** xSync VFS method occur and applies uniformly across all platforms.
816 ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
817 ** energetic or rigorous or forceful the sync operations are and
818 ** only make a difference on Mac OSX for the default SQLite code.
819 ** (Third-party VFS implementations might also make the distinction
820 ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
821 ** operating systems natively supported by SQLite, only Mac OSX
822 ** cares about the difference.)
823 */
824 #define SQLITE_SYNC_NORMAL        0x00002
825 #define SQLITE_SYNC_FULL          0x00003
826 #define SQLITE_SYNC_DATAONLY      0x00010
827
828 /*
829 ** CAPI3REF: OS Interface Open File Handle
830 **
831 ** An [sqlite3_file] object represents an open file in the 
832 ** [sqlite3_vfs | OS interface layer].  Individual OS interface
833 ** implementations will
834 ** want to subclass this object by appending additional fields
835 ** for their own use.  The pMethods entry is a pointer to an
836 ** [sqlite3_io_methods] object that defines methods for performing
837 ** I/O operations on the open file.
838 */
839 typedef struct sqlite3_file sqlite3_file;
840 struct sqlite3_file {
841   const struct sqlite3_io_methods *pMethods;  /* Methods for an open file */
842 };
843
844 /*
845 ** CAPI3REF: OS Interface File Virtual Methods Object
846 **
847 ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
848 ** [sqlite3_file] object (or, more commonly, a subclass of the
849 ** [sqlite3_file] object) with a pointer to an instance of this object.
850 ** This object defines the methods used to perform various operations
851 ** against the open file represented by the [sqlite3_file] object.
852 **
853 ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element 
854 ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
855 ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed.  The
856 ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
857 ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
858 ** to NULL.
859 **
860 ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
861 ** [SQLITE_SYNC_FULL].  The first choice is the normal fsync().
862 ** The second choice is a Mac OS X style fullsync.  The [SQLITE_SYNC_DATAONLY]
863 ** flag may be ORed in to indicate that only the data of the file
864 ** and not its inode needs to be synced.
865 **
866 ** The integer values to xLock() and xUnlock() are one of
867 ** <ul>
868 ** <li> [SQLITE_LOCK_NONE],
869 ** <li> [SQLITE_LOCK_SHARED],
870 ** <li> [SQLITE_LOCK_RESERVED],
871 ** <li> [SQLITE_LOCK_PENDING], or
872 ** <li> [SQLITE_LOCK_EXCLUSIVE].
873 ** </ul>
874 ** xLock() increases the lock. xUnlock() decreases the lock.
875 ** The xCheckReservedLock() method checks whether any database connection,
876 ** either in this process or in some other process, is holding a RESERVED,
877 ** PENDING, or EXCLUSIVE lock on the file.  It returns true
878 ** if such a lock exists and false otherwise.
879 **
880 ** The xFileControl() method is a generic interface that allows custom
881 ** VFS implementations to directly control an open file using the
882 ** [sqlite3_file_control()] interface.  The second "op" argument is an
883 ** integer opcode.  The third argument is a generic pointer intended to
884 ** point to a structure that may contain arguments or space in which to
885 ** write return values.  Potential uses for xFileControl() might be
886 ** functions to enable blocking locks with timeouts, to change the
887 ** locking strategy (for example to use dot-file locks), to inquire
888 ** about the status of a lock, or to break stale locks.  The SQLite
889 ** core reserves all opcodes less than 100 for its own use.
890 ** A [file control opcodes | list of opcodes] less than 100 is available.
891 ** Applications that define a custom xFileControl method should use opcodes
892 ** greater than 100 to avoid conflicts.  VFS implementations should
893 ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
894 ** recognize.
895 **
896 ** The xSectorSize() method returns the sector size of the
897 ** device that underlies the file.  The sector size is the
898 ** minimum write that can be performed without disturbing
899 ** other bytes in the file.  The xDeviceCharacteristics()
900 ** method returns a bit vector describing behaviors of the
901 ** underlying device:
902 **
903 ** <ul>
904 ** <li> [SQLITE_IOCAP_ATOMIC]
905 ** <li> [SQLITE_IOCAP_ATOMIC512]
906 ** <li> [SQLITE_IOCAP_ATOMIC1K]
907 ** <li> [SQLITE_IOCAP_ATOMIC2K]
908 ** <li> [SQLITE_IOCAP_ATOMIC4K]
909 ** <li> [SQLITE_IOCAP_ATOMIC8K]
910 ** <li> [SQLITE_IOCAP_ATOMIC16K]
911 ** <li> [SQLITE_IOCAP_ATOMIC32K]
912 ** <li> [SQLITE_IOCAP_ATOMIC64K]
913 ** <li> [SQLITE_IOCAP_SAFE_APPEND]
914 ** <li> [SQLITE_IOCAP_SEQUENTIAL]
915 ** </ul>
916 **
917 ** The SQLITE_IOCAP_ATOMIC property means that all writes of
918 ** any size are atomic.  The SQLITE_IOCAP_ATOMICnnn values
919 ** mean that writes of blocks that are nnn bytes in size and
920 ** are aligned to an address which is an integer multiple of
921 ** nnn are atomic.  The SQLITE_IOCAP_SAFE_APPEND value means
922 ** that when data is appended to a file, the data is appended
923 ** first then the size of the file is extended, never the other
924 ** way around.  The SQLITE_IOCAP_SEQUENTIAL property means that
925 ** information is written to disk in the same order as calls
926 ** to xWrite().
927 **
928 ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
929 ** in the unread portions of the buffer with zeros.  A VFS that
930 ** fails to zero-fill short reads might seem to work.  However,
931 ** failure to zero-fill short reads will eventually lead to
932 ** database corruption.
933 */
934 typedef struct sqlite3_io_methods sqlite3_io_methods;
935 struct sqlite3_io_methods {
936   int iVersion;
937   int (*xClose)(sqlite3_file*);
938   int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
939   int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
940   int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
941   int (*xSync)(sqlite3_file*, int flags);
942   int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
943   int (*xLock)(sqlite3_file*, int);
944   int (*xUnlock)(sqlite3_file*, int);
945   int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
946   int (*xFileControl)(sqlite3_file*, int op, void *pArg);
947   int (*xSectorSize)(sqlite3_file*);
948   int (*xDeviceCharacteristics)(sqlite3_file*);
949   /* Methods above are valid for version 1 */
950   int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
951   int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
952   void (*xShmBarrier)(sqlite3_file*);
953   int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
954   /* Methods above are valid for version 2 */
955   int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
956   int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
957   /* Methods above are valid for version 3 */
958   /* Additional methods may be added in future releases */
959 };
960
961 /*
962 ** CAPI3REF: Standard File Control Opcodes
963 ** KEYWORDS: {file control opcodes} {file control opcode}
964 **
965 ** These integer constants are opcodes for the xFileControl method
966 ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
967 ** interface.
968 **
969 ** <ul>
970 ** <li>[[SQLITE_FCNTL_LOCKSTATE]]
971 ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging.  This
972 ** opcode causes the xFileControl method to write the current state of
973 ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
974 ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
975 ** into an integer that the pArg argument points to. This capability
976 ** is used during testing and is only available when the SQLITE_TEST
977 ** compile-time option is used.
978 **
979 ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
980 ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
981 ** layer a hint of how large the database file will grow to be during the
982 ** current transaction.  This hint is not guaranteed to be accurate but it
983 ** is often close.  The underlying VFS might choose to preallocate database
984 ** file space based on this hint in order to help writes to the database
985 ** file run faster.
986 **
987 ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
988 ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
989 ** extends and truncates the database file in chunks of a size specified
990 ** by the user. The fourth argument to [sqlite3_file_control()] should 
991 ** point to an integer (type int) containing the new chunk-size to use
992 ** for the nominated database. Allocating database file space in large
993 ** chunks (say 1MB at a time), may reduce file-system fragmentation and
994 ** improve performance on some systems.
995 **
996 ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
997 ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
998 ** to the [sqlite3_file] object associated with a particular database
999 ** connection.  See the [sqlite3_file_control()] documentation for
1000 ** additional information.
1001 **
1002 ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
1003 ** No longer in use.
1004 **
1005 ** <li>[[SQLITE_FCNTL_SYNC]]
1006 ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
1007 ** sent to the VFS immediately before the xSync method is invoked on a
1008 ** database file descriptor. Or, if the xSync method is not invoked 
1009 ** because the user has configured SQLite with 
1010 ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place 
1011 ** of the xSync method. In most cases, the pointer argument passed with
1012 ** this file-control is NULL. However, if the database file is being synced
1013 ** as part of a multi-database commit, the argument points to a nul-terminated
1014 ** string containing the transactions master-journal file name. VFSes that 
1015 ** do not need this signal should silently ignore this opcode. Applications 
1016 ** should not call [sqlite3_file_control()] with this opcode as doing so may 
1017 ** disrupt the operation of the specialized VFSes that do require it.  
1018 **
1019 ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
1020 ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
1021 ** and sent to the VFS after a transaction has been committed immediately
1022 ** but before the database is unlocked. VFSes that do not need this signal
1023 ** should silently ignore this opcode. Applications should not call
1024 ** [sqlite3_file_control()] with this opcode as doing so may disrupt the 
1025 ** operation of the specialized VFSes that do require it.  
1026 **
1027 ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
1028 ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
1029 ** retry counts and intervals for certain disk I/O operations for the
1030 ** windows [VFS] in order to provide robustness in the presence of
1031 ** anti-virus programs.  By default, the windows VFS will retry file read,
1032 ** file write, and file delete operations up to 10 times, with a delay
1033 ** of 25 milliseconds before the first retry and with the delay increasing
1034 ** by an additional 25 milliseconds with each subsequent retry.  This
1035 ** opcode allows these two values (10 retries and 25 milliseconds of delay)
1036 ** to be adjusted.  The values are changed for all database connections
1037 ** within the same process.  The argument is a pointer to an array of two
1038 ** integers where the first integer i the new retry count and the second
1039 ** integer is the delay.  If either integer is negative, then the setting
1040 ** is not changed but instead the prior value of that setting is written
1041 ** into the array entry, allowing the current retry settings to be
1042 ** interrogated.  The zDbName parameter is ignored.
1043 **
1044 ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
1045 ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
1046 ** persistent [WAL | Write Ahead Log] setting.  By default, the auxiliary
1047 ** write ahead log and shared memory files used for transaction control
1048 ** are automatically deleted when the latest connection to the database
1049 ** closes.  Setting persistent WAL mode causes those files to persist after
1050 ** close.  Persisting the files is useful when other processes that do not
1051 ** have write permission on the directory containing the database file want
1052 ** to read the database file, as the WAL and shared memory files must exist
1053 ** in order for the database to be readable.  The fourth parameter to
1054 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1055 ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
1056 ** WAL mode.  If the integer is -1, then it is overwritten with the current
1057 ** WAL persistence setting.
1058 **
1059 ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
1060 ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
1061 ** persistent "powersafe-overwrite" or "PSOW" setting.  The PSOW setting
1062 ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
1063 ** xDeviceCharacteristics methods. The fourth parameter to
1064 ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
1065 ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
1066 ** mode.  If the integer is -1, then it is overwritten with the current
1067 ** zero-damage mode setting.
1068 **
1069 ** <li>[[SQLITE_FCNTL_OVERWRITE]]
1070 ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
1071 ** a write transaction to indicate that, unless it is rolled back for some
1072 ** reason, the entire database file will be overwritten by the current 
1073 ** transaction. This is used by VACUUM operations.
1074 **
1075 ** <li>[[SQLITE_FCNTL_VFSNAME]]
1076 ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
1077 ** all [VFSes] in the VFS stack.  The names are of all VFS shims and the
1078 ** final bottom-level VFS are written into memory obtained from 
1079 ** [sqlite3_malloc()] and the result is stored in the char* variable
1080 ** that the fourth parameter of [sqlite3_file_control()] points to.
1081 ** The caller is responsible for freeing the memory when done.  As with
1082 ** all file-control actions, there is no guarantee that this will actually
1083 ** do anything.  Callers should initialize the char* variable to a NULL
1084 ** pointer in case this file-control is not implemented.  This file-control
1085 ** is intended for diagnostic use only.
1086 **
1087 ** <li>[[SQLITE_FCNTL_PRAGMA]]
1088 ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA] 
1089 ** file control is sent to the open [sqlite3_file] object corresponding
1090 ** to the database file to which the pragma statement refers. ^The argument
1091 ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
1092 ** pointers to strings (char**) in which the second element of the array
1093 ** is the name of the pragma and the third element is the argument to the
1094 ** pragma or NULL if the pragma has no argument.  ^The handler for an
1095 ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
1096 ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
1097 ** or the equivalent and that string will become the result of the pragma or
1098 ** the error message if the pragma fails. ^If the
1099 ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal 
1100 ** [PRAGMA] processing continues.  ^If the [SQLITE_FCNTL_PRAGMA]
1101 ** file control returns [SQLITE_OK], then the parser assumes that the
1102 ** VFS has handled the PRAGMA itself and the parser generates a no-op
1103 ** prepared statement if result string is NULL, or that returns a copy
1104 ** of the result string if the string is non-NULL.
1105 ** ^If the [SQLITE_FCNTL_PRAGMA] file control returns
1106 ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
1107 ** that the VFS encountered an error while handling the [PRAGMA] and the
1108 ** compilation of the PRAGMA fails with an error.  ^The [SQLITE_FCNTL_PRAGMA]
1109 ** file control occurs at the beginning of pragma statement analysis and so
1110 ** it is able to override built-in [PRAGMA] statements.
1111 **
1112 ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
1113 ** ^The [SQLITE_FCNTL_BUSYHANDLER]
1114 ** file-control may be invoked by SQLite on the database file handle
1115 ** shortly after it is opened in order to provide a custom VFS with access
1116 ** to the connections busy-handler callback. The argument is of type (void **)
1117 ** - an array of two (void *) values. The first (void *) actually points
1118 ** to a function of type (int (*)(void *)). In order to invoke the connections
1119 ** busy-handler, this function should be invoked with the second (void *) in
1120 ** the array as the only argument. If it returns non-zero, then the operation
1121 ** should be retried. If it returns zero, the custom VFS should abandon the
1122 ** current operation.
1123 **
1124 ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
1125 ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
1126 ** to have SQLite generate a
1127 ** temporary filename using the same algorithm that is followed to generate
1128 ** temporary filenames for TEMP tables and other internal uses.  The
1129 ** argument should be a char** which will be filled with the filename
1130 ** written into memory obtained from [sqlite3_malloc()].  The caller should
1131 ** invoke [sqlite3_free()] on the result to avoid a memory leak.
1132 **
1133 ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
1134 ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
1135 ** maximum number of bytes that will be used for memory-mapped I/O.
1136 ** The argument is a pointer to a value of type sqlite3_int64 that
1137 ** is an advisory maximum number of bytes in the file to memory map.  The
1138 ** pointer is overwritten with the old value.  The limit is not changed if
1139 ** the value originally pointed to is negative, and so the current limit 
1140 ** can be queried by passing in a pointer to a negative number.  This
1141 ** file-control is used internally to implement [PRAGMA mmap_size].
1142 **
1143 ** <li>[[SQLITE_FCNTL_TRACE]]
1144 ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
1145 ** to the VFS about what the higher layers of the SQLite stack are doing.
1146 ** This file control is used by some VFS activity tracing [shims].
1147 ** The argument is a zero-terminated string.  Higher layers in the
1148 ** SQLite stack may generate instances of this file control if
1149 ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
1150 **
1151 ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
1152 ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
1153 ** pointer to an integer and it writes a boolean into that integer depending
1154 ** on whether or not the file has been renamed, moved, or deleted since it
1155 ** was first opened.
1156 **
1157 ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
1158 ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging.  This
1159 ** opcode causes the xFileControl method to swap the file handle with the one
1160 ** pointed to by the pArg argument.  This capability is used during testing
1161 ** and only needs to be supported when SQLITE_TEST is defined.
1162 **
1163 ** <li>[[SQLITE_FCNTL_WAL_BLOCK]]
1164 ** The [SQLITE_FCNTL_WAL_BLOCK] is a signal to the VFS layer that it might
1165 ** be advantageous to block on the next WAL lock if the lock is not immediately
1166 ** available.  The WAL subsystem issues this signal during rare
1167 ** circumstances in order to fix a problem with priority inversion.
1168 ** Applications should <em>not</em> use this file-control.
1169 **
1170 ** </ul>
1171 */
1172 #define SQLITE_FCNTL_LOCKSTATE               1
1173 #define SQLITE_FCNTL_GET_LOCKPROXYFILE       2
1174 #define SQLITE_FCNTL_SET_LOCKPROXYFILE       3
1175 #define SQLITE_FCNTL_LAST_ERRNO              4
1176 #define SQLITE_FCNTL_SIZE_HINT               5
1177 #define SQLITE_FCNTL_CHUNK_SIZE              6
1178 #define SQLITE_FCNTL_FILE_POINTER            7
1179 #define SQLITE_FCNTL_SYNC_OMITTED            8
1180 #define SQLITE_FCNTL_WIN32_AV_RETRY          9
1181 #define SQLITE_FCNTL_PERSIST_WAL            10
1182 #define SQLITE_FCNTL_OVERWRITE              11
1183 #define SQLITE_FCNTL_VFSNAME                12
1184 #define SQLITE_FCNTL_POWERSAFE_OVERWRITE    13
1185 #define SQLITE_FCNTL_PRAGMA                 14
1186 #define SQLITE_FCNTL_BUSYHANDLER            15
1187 #define SQLITE_FCNTL_TEMPFILENAME           16
1188 #define SQLITE_FCNTL_MMAP_SIZE              18
1189 #define SQLITE_FCNTL_TRACE                  19
1190 #define SQLITE_FCNTL_HAS_MOVED              20
1191 #define SQLITE_FCNTL_SYNC                   21
1192 #define SQLITE_FCNTL_COMMIT_PHASETWO        22
1193 #define SQLITE_FCNTL_WIN32_SET_HANDLE       23
1194 #define SQLITE_FCNTL_WAL_BLOCK              24
1195
1196 /* deprecated names */
1197 #define SQLITE_GET_LOCKPROXYFILE      SQLITE_FCNTL_GET_LOCKPROXYFILE
1198 #define SQLITE_SET_LOCKPROXYFILE      SQLITE_FCNTL_SET_LOCKPROXYFILE
1199 #define SQLITE_LAST_ERRNO             SQLITE_FCNTL_LAST_ERRNO
1200
1201
1202 /*
1203 ** CAPI3REF: Mutex Handle
1204 **
1205 ** The mutex module within SQLite defines [sqlite3_mutex] to be an
1206 ** abstract type for a mutex object.  The SQLite core never looks
1207 ** at the internal representation of an [sqlite3_mutex].  It only
1208 ** deals with pointers to the [sqlite3_mutex] object.
1209 **
1210 ** Mutexes are created using [sqlite3_mutex_alloc()].
1211 */
1212 typedef struct sqlite3_mutex sqlite3_mutex;
1213
1214 /*
1215 ** CAPI3REF: OS Interface Object
1216 **
1217 ** An instance of the sqlite3_vfs object defines the interface between
1218 ** the SQLite core and the underlying operating system.  The "vfs"
1219 ** in the name of the object stands for "virtual file system".  See
1220 ** the [VFS | VFS documentation] for further information.
1221 **
1222 ** The value of the iVersion field is initially 1 but may be larger in
1223 ** future versions of SQLite.  Additional fields may be appended to this
1224 ** object when the iVersion value is increased.  Note that the structure
1225 ** of the sqlite3_vfs object changes in the transaction between
1226 ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
1227 ** modified.
1228 **
1229 ** The szOsFile field is the size of the subclassed [sqlite3_file]
1230 ** structure used by this VFS.  mxPathname is the maximum length of
1231 ** a pathname in this VFS.
1232 **
1233 ** Registered sqlite3_vfs objects are kept on a linked list formed by
1234 ** the pNext pointer.  The [sqlite3_vfs_register()]
1235 ** and [sqlite3_vfs_unregister()] interfaces manage this list
1236 ** in a thread-safe way.  The [sqlite3_vfs_find()] interface
1237 ** searches the list.  Neither the application code nor the VFS
1238 ** implementation should use the pNext pointer.
1239 **
1240 ** The pNext field is the only field in the sqlite3_vfs
1241 ** structure that SQLite will ever modify.  SQLite will only access
1242 ** or modify this field while holding a particular static mutex.
1243 ** The application should never modify anything within the sqlite3_vfs
1244 ** object once the object has been registered.
1245 **
1246 ** The zName field holds the name of the VFS module.  The name must
1247 ** be unique across all VFS modules.
1248 **
1249 ** [[sqlite3_vfs.xOpen]]
1250 ** ^SQLite guarantees that the zFilename parameter to xOpen
1251 ** is either a NULL pointer or string obtained
1252 ** from xFullPathname() with an optional suffix added.
1253 ** ^If a suffix is added to the zFilename parameter, it will
1254 ** consist of a single "-" character followed by no more than
1255 ** 11 alphanumeric and/or "-" characters.
1256 ** ^SQLite further guarantees that
1257 ** the string will be valid and unchanged until xClose() is
1258 ** called. Because of the previous sentence,
1259 ** the [sqlite3_file] can safely store a pointer to the
1260 ** filename if it needs to remember the filename for some reason.
1261 ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
1262 ** must invent its own temporary name for the file.  ^Whenever the 
1263 ** xFilename parameter is NULL it will also be the case that the
1264 ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
1265 **
1266 ** The flags argument to xOpen() includes all bits set in
1267 ** the flags argument to [sqlite3_open_v2()].  Or if [sqlite3_open()]
1268 ** or [sqlite3_open16()] is used, then flags includes at least
1269 ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]. 
1270 ** If xOpen() opens a file read-only then it sets *pOutFlags to
1271 ** include [SQLITE_OPEN_READONLY].  Other bits in *pOutFlags may be set.
1272 **
1273 ** ^(SQLite will also add one of the following flags to the xOpen()
1274 ** call, depending on the object being opened:
1275 **
1276 ** <ul>
1277 ** <li>  [SQLITE_OPEN_MAIN_DB]
1278 ** <li>  [SQLITE_OPEN_MAIN_JOURNAL]
1279 ** <li>  [SQLITE_OPEN_TEMP_DB]
1280 ** <li>  [SQLITE_OPEN_TEMP_JOURNAL]
1281 ** <li>  [SQLITE_OPEN_TRANSIENT_DB]
1282 ** <li>  [SQLITE_OPEN_SUBJOURNAL]
1283 ** <li>  [SQLITE_OPEN_MASTER_JOURNAL]
1284 ** <li>  [SQLITE_OPEN_WAL]
1285 ** </ul>)^
1286 **
1287 ** The file I/O implementation can use the object type flags to
1288 ** change the way it deals with files.  For example, an application
1289 ** that does not care about crash recovery or rollback might make
1290 ** the open of a journal file a no-op.  Writes to this journal would
1291 ** also be no-ops, and any attempt to read the journal would return
1292 ** SQLITE_IOERR.  Or the implementation might recognize that a database
1293 ** file will be doing page-aligned sector reads and writes in a random
1294 ** order and set up its I/O subsystem accordingly.
1295 **
1296 ** SQLite might also add one of the following flags to the xOpen method:
1297 **
1298 ** <ul>
1299 ** <li> [SQLITE_OPEN_DELETEONCLOSE]
1300 ** <li> [SQLITE_OPEN_EXCLUSIVE]
1301 ** </ul>
1302 **
1303 ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
1304 ** deleted when it is closed.  ^The [SQLITE_OPEN_DELETEONCLOSE]
1305 ** will be set for TEMP databases and their journals, transient
1306 ** databases, and subjournals.
1307 **
1308 ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
1309 ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
1310 ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
1311 ** API.  The SQLITE_OPEN_EXCLUSIVE flag, when paired with the 
1312 ** SQLITE_OPEN_CREATE, is used to indicate that file should always
1313 ** be created, and that it is an error if it already exists.
1314 ** It is <i>not</i> used to indicate the file should be opened 
1315 ** for exclusive access.
1316 **
1317 ** ^At least szOsFile bytes of memory are allocated by SQLite
1318 ** to hold the  [sqlite3_file] structure passed as the third
1319 ** argument to xOpen.  The xOpen method does not have to
1320 ** allocate the structure; it should just fill it in.  Note that
1321 ** the xOpen method must set the sqlite3_file.pMethods to either
1322 ** a valid [sqlite3_io_methods] object or to NULL.  xOpen must do
1323 ** this even if the open fails.  SQLite expects that the sqlite3_file.pMethods
1324 ** element will be valid after xOpen returns regardless of the success
1325 ** or failure of the xOpen call.
1326 **
1327 ** [[sqlite3_vfs.xAccess]]
1328 ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
1329 ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
1330 ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
1331 ** to test whether a file is at least readable.   The file can be a
1332 ** directory.
1333 **
1334 ** ^SQLite will always allocate at least mxPathname+1 bytes for the
1335 ** output buffer xFullPathname.  The exact size of the output buffer
1336 ** is also passed as a parameter to both  methods. If the output buffer
1337 ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
1338 ** handled as a fatal error by SQLite, vfs implementations should endeavor
1339 ** to prevent this by setting mxPathname to a sufficiently large value.
1340 **
1341 ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
1342 ** interfaces are not strictly a part of the filesystem, but they are
1343 ** included in the VFS structure for completeness.
1344 ** The xRandomness() function attempts to return nBytes bytes
1345 ** of good-quality randomness into zOut.  The return value is
1346 ** the actual number of bytes of randomness obtained.
1347 ** The xSleep() method causes the calling thread to sleep for at
1348 ** least the number of microseconds given.  ^The xCurrentTime()
1349 ** method returns a Julian Day Number for the current date and time as
1350 ** a floating point value.
1351 ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
1352 ** Day Number multiplied by 86400000 (the number of milliseconds in 
1353 ** a 24-hour day).  
1354 ** ^SQLite will use the xCurrentTimeInt64() method to get the current
1355 ** date and time if that method is available (if iVersion is 2 or 
1356 ** greater and the function pointer is not NULL) and will fall back
1357 ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
1358 **
1359 ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
1360 ** are not used by the SQLite core.  These optional interfaces are provided
1361 ** by some VFSes to facilitate testing of the VFS code. By overriding 
1362 ** system calls with functions under its control, a test program can
1363 ** simulate faults and error conditions that would otherwise be difficult
1364 ** or impossible to induce.  The set of system calls that can be overridden
1365 ** varies from one VFS to another, and from one version of the same VFS to the
1366 ** next.  Applications that use these interfaces must be prepared for any
1367 ** or all of these interfaces to be NULL or for their behavior to change
1368 ** from one release to the next.  Applications must not attempt to access
1369 ** any of these methods if the iVersion of the VFS is less than 3.
1370 */
1371 typedef struct sqlite3_vfs sqlite3_vfs;
1372 typedef void (*sqlite3_syscall_ptr)(void);
1373 struct sqlite3_vfs {
1374   int iVersion;            /* Structure version number (currently 3) */
1375   int szOsFile;            /* Size of subclassed sqlite3_file */
1376   int mxPathname;          /* Maximum file pathname length */
1377   sqlite3_vfs *pNext;      /* Next registered VFS */
1378   const char *zName;       /* Name of this virtual file system */
1379   void *pAppData;          /* Pointer to application-specific data */
1380   int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
1381                int flags, int *pOutFlags);
1382   int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
1383   int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
1384   int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
1385   void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
1386   void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
1387   void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
1388   void (*xDlClose)(sqlite3_vfs*, void*);
1389   int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
1390   int (*xSleep)(sqlite3_vfs*, int microseconds);
1391   int (*xCurrentTime)(sqlite3_vfs*, double*);
1392   int (*xGetLastError)(sqlite3_vfs*, int, char *);
1393   /*
1394   ** The methods above are in version 1 of the sqlite_vfs object
1395   ** definition.  Those that follow are added in version 2 or later
1396   */
1397   int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
1398   /*
1399   ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
1400   ** Those below are for version 3 and greater.
1401   */
1402   int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
1403   sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
1404   const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
1405   /*
1406   ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
1407   ** New fields may be appended in figure versions.  The iVersion
1408   ** value will increment whenever this happens. 
1409   */
1410 };
1411
1412 /*
1413 ** CAPI3REF: Flags for the xAccess VFS method
1414 **
1415 ** These integer constants can be used as the third parameter to
1416 ** the xAccess method of an [sqlite3_vfs] object.  They determine
1417 ** what kind of permissions the xAccess method is looking for.
1418 ** With SQLITE_ACCESS_EXISTS, the xAccess method
1419 ** simply checks whether the file exists.
1420 ** With SQLITE_ACCESS_READWRITE, the xAccess method
1421 ** checks whether the named directory is both readable and writable
1422 ** (in other words, if files can be added, removed, and renamed within
1423 ** the directory).
1424 ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
1425 ** [temp_store_directory pragma], though this could change in a future
1426 ** release of SQLite.
1427 ** With SQLITE_ACCESS_READ, the xAccess method
1428 ** checks whether the file is readable.  The SQLITE_ACCESS_READ constant is
1429 ** currently unused, though it might be used in a future release of
1430 ** SQLite.
1431 */
1432 #define SQLITE_ACCESS_EXISTS    0
1433 #define SQLITE_ACCESS_READWRITE 1   /* Used by PRAGMA temp_store_directory */
1434 #define SQLITE_ACCESS_READ      2   /* Unused */
1435
1436 /*
1437 ** CAPI3REF: Flags for the xShmLock VFS method
1438 **
1439 ** These integer constants define the various locking operations
1440 ** allowed by the xShmLock method of [sqlite3_io_methods].  The
1441 ** following are the only legal combinations of flags to the
1442 ** xShmLock method:
1443 **
1444 ** <ul>
1445 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
1446 ** <li>  SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
1447 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
1448 ** <li>  SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
1449 ** </ul>
1450 **
1451 ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
1452 ** was given on the corresponding lock.  
1453 **
1454 ** The xShmLock method can transition between unlocked and SHARED or
1455 ** between unlocked and EXCLUSIVE.  It cannot transition between SHARED
1456 ** and EXCLUSIVE.
1457 */
1458 #define SQLITE_SHM_UNLOCK       1
1459 #define SQLITE_SHM_LOCK         2
1460 #define SQLITE_SHM_SHARED       4
1461 #define SQLITE_SHM_EXCLUSIVE    8
1462
1463 /*
1464 ** CAPI3REF: Maximum xShmLock index
1465 **
1466 ** The xShmLock method on [sqlite3_io_methods] may use values
1467 ** between 0 and this upper bound as its "offset" argument.
1468 ** The SQLite core will never attempt to acquire or release a
1469 ** lock outside of this range
1470 */
1471 #define SQLITE_SHM_NLOCK        8
1472
1473
1474 /*
1475 ** CAPI3REF: Initialize The SQLite Library
1476 **
1477 ** ^The sqlite3_initialize() routine initializes the
1478 ** SQLite library.  ^The sqlite3_shutdown() routine
1479 ** deallocates any resources that were allocated by sqlite3_initialize().
1480 ** These routines are designed to aid in process initialization and
1481 ** shutdown on embedded systems.  Workstation applications using
1482 ** SQLite normally do not need to invoke either of these routines.
1483 **
1484 ** A call to sqlite3_initialize() is an "effective" call if it is
1485 ** the first time sqlite3_initialize() is invoked during the lifetime of
1486 ** the process, or if it is the first time sqlite3_initialize() is invoked
1487 ** following a call to sqlite3_shutdown().  ^(Only an effective call
1488 ** of sqlite3_initialize() does any initialization.  All other calls
1489 ** are harmless no-ops.)^
1490 **
1491 ** A call to sqlite3_shutdown() is an "effective" call if it is the first
1492 ** call to sqlite3_shutdown() since the last sqlite3_initialize().  ^(Only
1493 ** an effective call to sqlite3_shutdown() does any deinitialization.
1494 ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
1495 **
1496 ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
1497 ** is not.  The sqlite3_shutdown() interface must only be called from a
1498 ** single thread.  All open [database connections] must be closed and all
1499 ** other SQLite resources must be deallocated prior to invoking
1500 ** sqlite3_shutdown().
1501 **
1502 ** Among other things, ^sqlite3_initialize() will invoke
1503 ** sqlite3_os_init().  Similarly, ^sqlite3_shutdown()
1504 ** will invoke sqlite3_os_end().
1505 **
1506 ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
1507 ** ^If for some reason, sqlite3_initialize() is unable to initialize
1508 ** the library (perhaps it is unable to allocate a needed resource such
1509 ** as a mutex) it returns an [error code] other than [SQLITE_OK].
1510 **
1511 ** ^The sqlite3_initialize() routine is called internally by many other
1512 ** SQLite interfaces so that an application usually does not need to
1513 ** invoke sqlite3_initialize() directly.  For example, [sqlite3_open()]
1514 ** calls sqlite3_initialize() so the SQLite library will be automatically
1515 ** initialized when [sqlite3_open()] is called if it has not be initialized
1516 ** already.  ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
1517 ** compile-time option, then the automatic calls to sqlite3_initialize()
1518 ** are omitted and the application must call sqlite3_initialize() directly
1519 ** prior to using any other SQLite interface.  For maximum portability,
1520 ** it is recommended that applications always invoke sqlite3_initialize()
1521 ** directly prior to using any other SQLite interface.  Future releases
1522 ** of SQLite may require this.  In other words, the behavior exhibited
1523 ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
1524 ** default behavior in some future release of SQLite.
1525 **
1526 ** The sqlite3_os_init() routine does operating-system specific
1527 ** initialization of the SQLite library.  The sqlite3_os_end()
1528 ** routine undoes the effect of sqlite3_os_init().  Typical tasks
1529 ** performed by these routines include allocation or deallocation
1530 ** of static resources, initialization of global variables,
1531 ** setting up a default [sqlite3_vfs] module, or setting up
1532 ** a default configuration using [sqlite3_config()].
1533 **
1534 ** The application should never invoke either sqlite3_os_init()
1535 ** or sqlite3_os_end() directly.  The application should only invoke
1536 ** sqlite3_initialize() and sqlite3_shutdown().  The sqlite3_os_init()
1537 ** interface is called automatically by sqlite3_initialize() and
1538 ** sqlite3_os_end() is called by sqlite3_shutdown().  Appropriate
1539 ** implementations for sqlite3_os_init() and sqlite3_os_end()
1540 ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
1541 ** When [custom builds | built for other platforms]
1542 ** (using the [SQLITE_OS_OTHER=1] compile-time
1543 ** option) the application must supply a suitable implementation for
1544 ** sqlite3_os_init() and sqlite3_os_end().  An application-supplied
1545 ** implementation of sqlite3_os_init() or sqlite3_os_end()
1546 ** must return [SQLITE_OK] on success and some other [error code] upon
1547 ** failure.
1548 */
1549 SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void);
1550 SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void);
1551 SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void);
1552 SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void);
1553
1554 /*
1555 ** CAPI3REF: Configuring The SQLite Library
1556 **
1557 ** The sqlite3_config() interface is used to make global configuration
1558 ** changes to SQLite in order to tune SQLite to the specific needs of
1559 ** the application.  The default configuration is recommended for most
1560 ** applications and so this routine is usually not necessary.  It is
1561 ** provided to support rare applications with unusual needs.
1562 **
1563 ** The sqlite3_config() interface is not threadsafe.  The application
1564 ** must insure that no other SQLite interfaces are invoked by other
1565 ** threads while sqlite3_config() is running.  Furthermore, sqlite3_config()
1566 ** may only be invoked prior to library initialization using
1567 ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
1568 ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
1569 ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
1570 ** Note, however, that ^sqlite3_config() can be called as part of the
1571 ** implementation of an application-defined [sqlite3_os_init()].
1572 **
1573 ** The first argument to sqlite3_config() is an integer
1574 ** [configuration option] that determines
1575 ** what property of SQLite is to be configured.  Subsequent arguments
1576 ** vary depending on the [configuration option]
1577 ** in the first argument.
1578 **
1579 ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
1580 ** ^If the option is unknown or SQLite is unable to set the option
1581 ** then this routine returns a non-zero [error code].
1582 */
1583 SQLITE_API int SQLITE_CDECL sqlite3_config(int, ...);
1584
1585 /*
1586 ** CAPI3REF: Configure database connections
1587 **
1588 ** The sqlite3_db_config() interface is used to make configuration
1589 ** changes to a [database connection].  The interface is similar to
1590 ** [sqlite3_config()] except that the changes apply to a single
1591 ** [database connection] (specified in the first argument).
1592 **
1593 ** The second argument to sqlite3_db_config(D,V,...)  is the
1594 ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code 
1595 ** that indicates what aspect of the [database connection] is being configured.
1596 ** Subsequent arguments vary depending on the configuration verb.
1597 **
1598 ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
1599 ** the call is considered successful.
1600 */
1601 SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3*, int op, ...);
1602
1603 /*
1604 ** CAPI3REF: Memory Allocation Routines
1605 **
1606 ** An instance of this object defines the interface between SQLite
1607 ** and low-level memory allocation routines.
1608 **
1609 ** This object is used in only one place in the SQLite interface.
1610 ** A pointer to an instance of this object is the argument to
1611 ** [sqlite3_config()] when the configuration option is
1612 ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].  
1613 ** By creating an instance of this object
1614 ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
1615 ** during configuration, an application can specify an alternative
1616 ** memory allocation subsystem for SQLite to use for all of its
1617 ** dynamic memory needs.
1618 **
1619 ** Note that SQLite comes with several [built-in memory allocators]
1620 ** that are perfectly adequate for the overwhelming majority of applications
1621 ** and that this object is only useful to a tiny minority of applications
1622 ** with specialized memory allocation requirements.  This object is
1623 ** also used during testing of SQLite in order to specify an alternative
1624 ** memory allocator that simulates memory out-of-memory conditions in
1625 ** order to verify that SQLite recovers gracefully from such
1626 ** conditions.
1627 **
1628 ** The xMalloc, xRealloc, and xFree methods must work like the
1629 ** malloc(), realloc() and free() functions from the standard C library.
1630 ** ^SQLite guarantees that the second argument to
1631 ** xRealloc is always a value returned by a prior call to xRoundup.
1632 **
1633 ** xSize should return the allocated size of a memory allocation
1634 ** previously obtained from xMalloc or xRealloc.  The allocated size
1635 ** is always at least as big as the requested size but may be larger.
1636 **
1637 ** The xRoundup method returns what would be the allocated size of
1638 ** a memory allocation given a particular requested size.  Most memory
1639 ** allocators round up memory allocations at least to the next multiple
1640 ** of 8.  Some allocators round up to a larger multiple or to a power of 2.
1641 ** Every memory allocation request coming in through [sqlite3_malloc()]
1642 ** or [sqlite3_realloc()] first calls xRoundup.  If xRoundup returns 0, 
1643 ** that causes the corresponding memory allocation to fail.
1644 **
1645 ** The xInit method initializes the memory allocator.  For example,
1646 ** it might allocate any require mutexes or initialize internal data
1647 ** structures.  The xShutdown method is invoked (indirectly) by
1648 ** [sqlite3_shutdown()] and should deallocate any resources acquired
1649 ** by xInit.  The pAppData pointer is used as the only parameter to
1650 ** xInit and xShutdown.
1651 **
1652 ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
1653 ** the xInit method, so the xInit method need not be threadsafe.  The
1654 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
1655 ** not need to be threadsafe either.  For all other methods, SQLite
1656 ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
1657 ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
1658 ** it is by default) and so the methods are automatically serialized.
1659 ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
1660 ** methods must be threadsafe or else make their own arrangements for
1661 ** serialization.
1662 **
1663 ** SQLite will never invoke xInit() more than once without an intervening
1664 ** call to xShutdown().
1665 */
1666 typedef struct sqlite3_mem_methods sqlite3_mem_methods;
1667 struct sqlite3_mem_methods {
1668   void *(*xMalloc)(int);         /* Memory allocation function */
1669   void (*xFree)(void*);          /* Free a prior allocation */
1670   void *(*xRealloc)(void*,int);  /* Resize an allocation */
1671   int (*xSize)(void*);           /* Return the size of an allocation */
1672   int (*xRoundup)(int);          /* Round up request size to allocation size */
1673   int (*xInit)(void*);           /* Initialize the memory allocator */
1674   void (*xShutdown)(void*);      /* Deinitialize the memory allocator */
1675   void *pAppData;                /* Argument to xInit() and xShutdown() */
1676 };
1677
1678 /*
1679 ** CAPI3REF: Configuration Options
1680 ** KEYWORDS: {configuration option}
1681 **
1682 ** These constants are the available integer configuration options that
1683 ** can be passed as the first argument to the [sqlite3_config()] interface.
1684 **
1685 ** New configuration options may be added in future releases of SQLite.
1686 ** Existing configuration options might be discontinued.  Applications
1687 ** should check the return code from [sqlite3_config()] to make sure that
1688 ** the call worked.  The [sqlite3_config()] interface will return a
1689 ** non-zero [error code] if a discontinued or unsupported configuration option
1690 ** is invoked.
1691 **
1692 ** <dl>
1693 ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
1694 ** <dd>There are no arguments to this option.  ^This option sets the
1695 ** [threading mode] to Single-thread.  In other words, it disables
1696 ** all mutexing and puts SQLite into a mode where it can only be used
1697 ** by a single thread.   ^If SQLite is compiled with
1698 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1699 ** it is not possible to change the [threading mode] from its default
1700 ** value of Single-thread and so [sqlite3_config()] will return 
1701 ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
1702 ** configuration option.</dd>
1703 **
1704 ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
1705 ** <dd>There are no arguments to this option.  ^This option sets the
1706 ** [threading mode] to Multi-thread.  In other words, it disables
1707 ** mutexing on [database connection] and [prepared statement] objects.
1708 ** The application is responsible for serializing access to
1709 ** [database connections] and [prepared statements].  But other mutexes
1710 ** are enabled so that SQLite will be safe to use in a multi-threaded
1711 ** environment as long as no two threads attempt to use the same
1712 ** [database connection] at the same time.  ^If SQLite is compiled with
1713 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1714 ** it is not possible to set the Multi-thread [threading mode] and
1715 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1716 ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
1717 **
1718 ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
1719 ** <dd>There are no arguments to this option.  ^This option sets the
1720 ** [threading mode] to Serialized. In other words, this option enables
1721 ** all mutexes including the recursive
1722 ** mutexes on [database connection] and [prepared statement] objects.
1723 ** In this mode (which is the default when SQLite is compiled with
1724 ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
1725 ** to [database connections] and [prepared statements] so that the
1726 ** application is free to use the same [database connection] or the
1727 ** same [prepared statement] in different threads at the same time.
1728 ** ^If SQLite is compiled with
1729 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1730 ** it is not possible to set the Serialized [threading mode] and
1731 ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
1732 ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
1733 **
1734 ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
1735 ** <dd> ^(The SQLITE_CONFIG_MALLOC option takes a single argument which is 
1736 ** a pointer to an instance of the [sqlite3_mem_methods] structure.
1737 ** The argument specifies
1738 ** alternative low-level memory allocation routines to be used in place of
1739 ** the memory allocation routines built into SQLite.)^ ^SQLite makes
1740 ** its own private copy of the content of the [sqlite3_mem_methods] structure
1741 ** before the [sqlite3_config()] call returns.</dd>
1742 **
1743 ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
1744 ** <dd> ^(The SQLITE_CONFIG_GETMALLOC option takes a single argument which
1745 ** is a pointer to an instance of the [sqlite3_mem_methods] structure.
1746 ** The [sqlite3_mem_methods]
1747 ** structure is filled with the currently defined memory allocation routines.)^
1748 ** This option can be used to overload the default memory allocation
1749 ** routines with a wrapper that simulations memory allocation failure or
1750 ** tracks memory usage, for example. </dd>
1751 **
1752 ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
1753 ** <dd> ^The SQLITE_CONFIG_MEMSTATUS option takes single argument of type int,
1754 ** interpreted as a boolean, which enables or disables the collection of
1755 ** memory allocation statistics. ^(When memory allocation statistics are
1756 ** disabled, the following SQLite interfaces become non-operational:
1757 **   <ul>
1758 **   <li> [sqlite3_memory_used()]
1759 **   <li> [sqlite3_memory_highwater()]
1760 **   <li> [sqlite3_soft_heap_limit64()]
1761 **   <li> [sqlite3_status64()]
1762 **   </ul>)^
1763 ** ^Memory allocation statistics are enabled by default unless SQLite is
1764 ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
1765 ** allocation statistics are disabled by default.
1766 ** </dd>
1767 **
1768 ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
1769 ** <dd> ^The SQLITE_CONFIG_SCRATCH option specifies a static memory buffer
1770 ** that SQLite can use for scratch memory.  ^(There are three arguments
1771 ** to SQLITE_CONFIG_SCRATCH:  A pointer an 8-byte
1772 ** aligned memory buffer from which the scratch allocations will be
1773 ** drawn, the size of each scratch allocation (sz),
1774 ** and the maximum number of scratch allocations (N).)^
1775 ** The first argument must be a pointer to an 8-byte aligned buffer
1776 ** of at least sz*N bytes of memory.
1777 ** ^SQLite will not use more than one scratch buffers per thread.
1778 ** ^SQLite will never request a scratch buffer that is more than 6
1779 ** times the database page size.
1780 ** ^If SQLite needs needs additional
1781 ** scratch memory beyond what is provided by this configuration option, then 
1782 ** [sqlite3_malloc()] will be used to obtain the memory needed.<p>
1783 ** ^When the application provides any amount of scratch memory using
1784 ** SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary large
1785 ** [sqlite3_malloc|heap allocations].
1786 ** This can help [Robson proof|prevent memory allocation failures] due to heap
1787 ** fragmentation in low-memory embedded systems.
1788 ** </dd>
1789 **
1790 ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
1791 ** <dd> ^The SQLITE_CONFIG_PAGECACHE option specifies a static memory buffer
1792 ** that SQLite can use for the database page cache with the default page
1793 ** cache implementation.  
1794 ** This configuration should not be used if an application-define page
1795 ** cache implementation is loaded using the [SQLITE_CONFIG_PCACHE2]
1796 ** configuration option.
1797 ** ^There are three arguments to SQLITE_CONFIG_PAGECACHE: A pointer to
1798 ** 8-byte aligned
1799 ** memory, the size of each page buffer (sz), and the number of pages (N).
1800 ** The sz argument should be the size of the largest database page
1801 ** (a power of two between 512 and 65536) plus some extra bytes for each
1802 ** page header.  ^The number of extra bytes needed by the page header
1803 ** can be determined using the [SQLITE_CONFIG_PCACHE_HDRSZ] option 
1804 ** to [sqlite3_config()].
1805 ** ^It is harmless, apart from the wasted memory,
1806 ** for the sz parameter to be larger than necessary.  The first
1807 ** argument should pointer to an 8-byte aligned block of memory that
1808 ** is at least sz*N bytes of memory, otherwise subsequent behavior is
1809 ** undefined.
1810 ** ^SQLite will use the memory provided by the first argument to satisfy its
1811 ** memory needs for the first N pages that it adds to cache.  ^If additional
1812 ** page cache memory is needed beyond what is provided by this option, then
1813 ** SQLite goes to [sqlite3_malloc()] for the additional storage space.</dd>
1814 **
1815 ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
1816 ** <dd> ^The SQLITE_CONFIG_HEAP option specifies a static memory buffer 
1817 ** that SQLite will use for all of its dynamic memory allocation needs
1818 ** beyond those provided for by [SQLITE_CONFIG_SCRATCH] and
1819 ** [SQLITE_CONFIG_PAGECACHE].
1820 ** ^The SQLITE_CONFIG_HEAP option is only available if SQLite is compiled
1821 ** with either [SQLITE_ENABLE_MEMSYS3] or [SQLITE_ENABLE_MEMSYS5] and returns
1822 ** [SQLITE_ERROR] if invoked otherwise.
1823 ** ^There are three arguments to SQLITE_CONFIG_HEAP:
1824 ** An 8-byte aligned pointer to the memory,
1825 ** the number of bytes in the memory buffer, and the minimum allocation size.
1826 ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
1827 ** to using its default memory allocator (the system malloc() implementation),
1828 ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC].  ^If the
1829 ** memory pointer is not NULL then the alternative memory
1830 ** allocator is engaged to handle all of SQLites memory allocation needs.
1831 ** The first pointer (the memory pointer) must be aligned to an 8-byte
1832 ** boundary or subsequent behavior of SQLite will be undefined.
1833 ** The minimum allocation size is capped at 2**12. Reasonable values
1834 ** for the minimum allocation size are 2**5 through 2**8.</dd>
1835 **
1836 ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
1837 ** <dd> ^(The SQLITE_CONFIG_MUTEX option takes a single argument which is a
1838 ** pointer to an instance of the [sqlite3_mutex_methods] structure.
1839 ** The argument specifies alternative low-level mutex routines to be used
1840 ** in place the mutex routines built into SQLite.)^  ^SQLite makes a copy of
1841 ** the content of the [sqlite3_mutex_methods] structure before the call to
1842 ** [sqlite3_config()] returns. ^If SQLite is compiled with
1843 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1844 ** the entire mutexing subsystem is omitted from the build and hence calls to
1845 ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
1846 ** return [SQLITE_ERROR].</dd>
1847 **
1848 ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
1849 ** <dd> ^(The SQLITE_CONFIG_GETMUTEX option takes a single argument which
1850 ** is a pointer to an instance of the [sqlite3_mutex_methods] structure.  The
1851 ** [sqlite3_mutex_methods]
1852 ** structure is filled with the currently defined mutex routines.)^
1853 ** This option can be used to overload the default mutex allocation
1854 ** routines with a wrapper used to track mutex usage for performance
1855 ** profiling or testing, for example.   ^If SQLite is compiled with
1856 ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
1857 ** the entire mutexing subsystem is omitted from the build and hence calls to
1858 ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
1859 ** return [SQLITE_ERROR].</dd>
1860 **
1861 ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
1862 ** <dd> ^(The SQLITE_CONFIG_LOOKASIDE option takes two arguments that determine
1863 ** the default size of lookaside memory on each [database connection].
1864 ** The first argument is the
1865 ** size of each lookaside buffer slot and the second is the number of
1866 ** slots allocated to each database connection.)^  ^(SQLITE_CONFIG_LOOKASIDE
1867 ** sets the <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
1868 ** option to [sqlite3_db_config()] can be used to change the lookaside
1869 ** configuration on individual connections.)^ </dd>
1870 **
1871 ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
1872 ** <dd> ^(The SQLITE_CONFIG_PCACHE2 option takes a single argument which is 
1873 ** a pointer to an [sqlite3_pcache_methods2] object.  This object specifies
1874 ** the interface to a custom page cache implementation.)^
1875 ** ^SQLite makes a copy of the [sqlite3_pcache_methods2] object.</dd>
1876 **
1877 ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
1878 ** <dd> ^(The SQLITE_CONFIG_GETPCACHE2 option takes a single argument which
1879 ** is a pointer to an [sqlite3_pcache_methods2] object.  SQLite copies of
1880 ** the current page cache implementation into that object.)^ </dd>
1881 **
1882 ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
1883 ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
1884 ** global [error log].
1885 ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
1886 ** function with a call signature of void(*)(void*,int,const char*), 
1887 ** and a pointer to void. ^If the function pointer is not NULL, it is
1888 ** invoked by [sqlite3_log()] to process each logging event.  ^If the
1889 ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
1890 ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
1891 ** passed through as the first parameter to the application-defined logger
1892 ** function whenever that function is invoked.  ^The second parameter to
1893 ** the logger function is a copy of the first parameter to the corresponding
1894 ** [sqlite3_log()] call and is intended to be a [result code] or an
1895 ** [extended result code].  ^The third parameter passed to the logger is
1896 ** log message after formatting via [sqlite3_snprintf()].
1897 ** The SQLite logging interface is not reentrant; the logger function
1898 ** supplied by the application must not invoke any SQLite interface.
1899 ** In a multi-threaded application, the application-defined logger
1900 ** function must be threadsafe. </dd>
1901 **
1902 ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
1903 ** <dd>^(The SQLITE_CONFIG_URI option takes a single argument of type int.
1904 ** If non-zero, then URI handling is globally enabled. If the parameter is zero,
1905 ** then URI handling is globally disabled.)^ ^If URI handling is globally
1906 ** enabled, all filenames passed to [sqlite3_open()], [sqlite3_open_v2()],
1907 ** [sqlite3_open16()] or
1908 ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
1909 ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
1910 ** connection is opened. ^If it is globally disabled, filenames are
1911 ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
1912 ** database connection is opened. ^(By default, URI handling is globally
1913 ** disabled. The default value may be changed by compiling with the
1914 ** [SQLITE_USE_URI] symbol defined.)^
1915 **
1916 ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
1917 ** <dd>^The SQLITE_CONFIG_COVERING_INDEX_SCAN option takes a single integer
1918 ** argument which is interpreted as a boolean in order to enable or disable
1919 ** the use of covering indices for full table scans in the query optimizer.
1920 ** ^The default setting is determined
1921 ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
1922 ** if that compile-time option is omitted.
1923 ** The ability to disable the use of covering indices for full table scans
1924 ** is because some incorrectly coded legacy applications might malfunction
1925 ** when the optimization is enabled.  Providing the ability to
1926 ** disable the optimization allows the older, buggy application code to work
1927 ** without change even with newer versions of SQLite.
1928 **
1929 ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
1930 ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
1931 ** <dd> These options are obsolete and should not be used by new code.
1932 ** They are retained for backwards compatibility but are now no-ops.
1933 ** </dd>
1934 **
1935 ** [[SQLITE_CONFIG_SQLLOG]]
1936 ** <dt>SQLITE_CONFIG_SQLLOG
1937 ** <dd>This option is only available if sqlite is compiled with the
1938 ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
1939 ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
1940 ** The second should be of type (void*). The callback is invoked by the library
1941 ** in three separate circumstances, identified by the value passed as the
1942 ** fourth parameter. If the fourth parameter is 0, then the database connection
1943 ** passed as the second argument has just been opened. The third argument
1944 ** points to a buffer containing the name of the main database file. If the
1945 ** fourth parameter is 1, then the SQL statement that the third parameter
1946 ** points to has just been executed. Or, if the fourth parameter is 2, then
1947 ** the connection being passed as the second parameter is being closed. The
1948 ** third parameter is passed NULL In this case.  An example of using this
1949 ** configuration option can be seen in the "test_sqllog.c" source file in
1950 ** the canonical SQLite source tree.</dd>
1951 **
1952 ** [[SQLITE_CONFIG_MMAP_SIZE]]
1953 ** <dt>SQLITE_CONFIG_MMAP_SIZE
1954 ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
1955 ** that are the default mmap size limit (the default setting for
1956 ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
1957 ** ^The default setting can be overridden by each database connection using
1958 ** either the [PRAGMA mmap_size] command, or by using the
1959 ** [SQLITE_FCNTL_MMAP_SIZE] file control.  ^(The maximum allowed mmap size
1960 ** will be silently truncated if necessary so that it does not exceed the
1961 ** compile-time maximum mmap size set by the
1962 ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
1963 ** ^If either argument to this option is negative, then that argument is
1964 ** changed to its compile-time default.
1965 **
1966 ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
1967 ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
1968 ** <dd>^The SQLITE_CONFIG_WIN32_HEAPSIZE option is only available if SQLite is
1969 ** compiled for Windows with the [SQLITE_WIN32_MALLOC] pre-processor macro
1970 ** defined. ^SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
1971 ** that specifies the maximum size of the created heap.
1972 **
1973 ** [[SQLITE_CONFIG_PCACHE_HDRSZ]]
1974 ** <dt>SQLITE_CONFIG_PCACHE_HDRSZ
1975 ** <dd>^The SQLITE_CONFIG_PCACHE_HDRSZ option takes a single parameter which
1976 ** is a pointer to an integer and writes into that integer the number of extra
1977 ** bytes per page required for each page in [SQLITE_CONFIG_PAGECACHE].
1978 ** The amount of extra space required can change depending on the compiler,
1979 ** target platform, and SQLite version.
1980 **
1981 ** [[SQLITE_CONFIG_PMASZ]]
1982 ** <dt>SQLITE_CONFIG_PMASZ
1983 ** <dd>^The SQLITE_CONFIG_PMASZ option takes a single parameter which
1984 ** is an unsigned integer and sets the "Minimum PMA Size" for the multithreaded
1985 ** sorter to that integer.  The default minimum PMA Size is set by the
1986 ** [SQLITE_SORTER_PMASZ] compile-time option.  New threads are launched
1987 ** to help with sort operations when multithreaded sorting
1988 ** is enabled (using the [PRAGMA threads] command) and the amount of content
1989 ** to be sorted exceeds the page size times the minimum of the
1990 ** [PRAGMA cache_size] setting and this value.
1991 ** </dl>
1992 */
1993 #define SQLITE_CONFIG_SINGLETHREAD  1  /* nil */
1994 #define SQLITE_CONFIG_MULTITHREAD   2  /* nil */
1995 #define SQLITE_CONFIG_SERIALIZED    3  /* nil */
1996 #define SQLITE_CONFIG_MALLOC        4  /* sqlite3_mem_methods* */
1997 #define SQLITE_CONFIG_GETMALLOC     5  /* sqlite3_mem_methods* */
1998 #define SQLITE_CONFIG_SCRATCH       6  /* void*, int sz, int N */
1999 #define SQLITE_CONFIG_PAGECACHE     7  /* void*, int sz, int N */
2000 #define SQLITE_CONFIG_HEAP          8  /* void*, int nByte, int min */
2001 #define SQLITE_CONFIG_MEMSTATUS     9  /* boolean */
2002 #define SQLITE_CONFIG_MUTEX        10  /* sqlite3_mutex_methods* */
2003 #define SQLITE_CONFIG_GETMUTEX     11  /* sqlite3_mutex_methods* */
2004 /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */ 
2005 #define SQLITE_CONFIG_LOOKASIDE    13  /* int int */
2006 #define SQLITE_CONFIG_PCACHE       14  /* no-op */
2007 #define SQLITE_CONFIG_GETPCACHE    15  /* no-op */
2008 #define SQLITE_CONFIG_LOG          16  /* xFunc, void* */
2009 #define SQLITE_CONFIG_URI          17  /* int */
2010 #define SQLITE_CONFIG_PCACHE2      18  /* sqlite3_pcache_methods2* */
2011 #define SQLITE_CONFIG_GETPCACHE2   19  /* sqlite3_pcache_methods2* */
2012 #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20  /* int */
2013 #define SQLITE_CONFIG_SQLLOG       21  /* xSqllog, void* */
2014 #define SQLITE_CONFIG_MMAP_SIZE    22  /* sqlite3_int64, sqlite3_int64 */
2015 #define SQLITE_CONFIG_WIN32_HEAPSIZE      23  /* int nByte */
2016 #define SQLITE_CONFIG_PCACHE_HDRSZ        24  /* int *psz */
2017 #define SQLITE_CONFIG_PMASZ               25  /* unsigned int szPma */
2018
2019 /*
2020 ** CAPI3REF: Database Connection Configuration Options
2021 **
2022 ** These constants are the available integer configuration options that
2023 ** can be passed as the second argument to the [sqlite3_db_config()] interface.
2024 **
2025 ** New configuration options may be added in future releases of SQLite.
2026 ** Existing configuration options might be discontinued.  Applications
2027 ** should check the return code from [sqlite3_db_config()] to make sure that
2028 ** the call worked.  ^The [sqlite3_db_config()] interface will return a
2029 ** non-zero [error code] if a discontinued or unsupported configuration option
2030 ** is invoked.
2031 **
2032 ** <dl>
2033 ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
2034 ** <dd> ^This option takes three additional arguments that determine the 
2035 ** [lookaside memory allocator] configuration for the [database connection].
2036 ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
2037 ** pointer to a memory buffer to use for lookaside memory.
2038 ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
2039 ** may be NULL in which case SQLite will allocate the
2040 ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
2041 ** size of each lookaside buffer slot.  ^The third argument is the number of
2042 ** slots.  The size of the buffer in the first argument must be greater than
2043 ** or equal to the product of the second and third arguments.  The buffer
2044 ** must be aligned to an 8-byte boundary.  ^If the second argument to
2045 ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
2046 ** rounded down to the next smaller multiple of 8.  ^(The lookaside memory
2047 ** configuration for a database connection can only be changed when that
2048 ** connection is not currently using lookaside memory, or in other words
2049 ** when the "current value" returned by
2050 ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
2051 ** Any attempt to change the lookaside memory configuration when lookaside
2052 ** memory is in use leaves the configuration unchanged and returns 
2053 ** [SQLITE_BUSY].)^</dd>
2054 **
2055 ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
2056 ** <dd> ^This option is used to enable or disable the enforcement of
2057 ** [foreign key constraints].  There should be two additional arguments.
2058 ** The first argument is an integer which is 0 to disable FK enforcement,
2059 ** positive to enable FK enforcement or negative to leave FK enforcement
2060 ** unchanged.  The second parameter is a pointer to an integer into which
2061 ** is written 0 or 1 to indicate whether FK enforcement is off or on
2062 ** following this call.  The second parameter may be a NULL pointer, in
2063 ** which case the FK enforcement setting is not reported back. </dd>
2064 **
2065 ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
2066 ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
2067 ** There should be two additional arguments.
2068 ** The first argument is an integer which is 0 to disable triggers,
2069 ** positive to enable triggers or negative to leave the setting unchanged.
2070 ** The second parameter is a pointer to an integer into which
2071 ** is written 0 or 1 to indicate whether triggers are disabled or enabled
2072 ** following this call.  The second parameter may be a NULL pointer, in
2073 ** which case the trigger setting is not reported back. </dd>
2074 **
2075 ** </dl>
2076 */
2077 #define SQLITE_DBCONFIG_LOOKASIDE       1001  /* void* int int */
2078 #define SQLITE_DBCONFIG_ENABLE_FKEY     1002  /* int int* */
2079 #define SQLITE_DBCONFIG_ENABLE_TRIGGER  1003  /* int int* */
2080
2081
2082 /*
2083 ** CAPI3REF: Enable Or Disable Extended Result Codes
2084 **
2085 ** ^The sqlite3_extended_result_codes() routine enables or disables the
2086 ** [extended result codes] feature of SQLite. ^The extended result
2087 ** codes are disabled by default for historical compatibility.
2088 */
2089 SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3*, int onoff);
2090
2091 /*
2092 ** CAPI3REF: Last Insert Rowid
2093 **
2094 ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
2095 ** has a unique 64-bit signed
2096 ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
2097 ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
2098 ** names are not also used by explicitly declared columns. ^If
2099 ** the table has a column of type [INTEGER PRIMARY KEY] then that column
2100 ** is another alias for the rowid.
2101 **
2102 ** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the 
2103 ** most recent successful [INSERT] into a rowid table or [virtual table]
2104 ** on database connection D.
2105 ** ^Inserts into [WITHOUT ROWID] tables are not recorded.
2106 ** ^If no successful [INSERT]s into rowid tables
2107 ** have ever occurred on the database connection D, 
2108 ** then sqlite3_last_insert_rowid(D) returns zero.
2109 **
2110 ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
2111 ** method, then this routine will return the [rowid] of the inserted
2112 ** row as long as the trigger or virtual table method is running.
2113 ** But once the trigger or virtual table method ends, the value returned 
2114 ** by this routine reverts to what it was before the trigger or virtual
2115 ** table method began.)^
2116 **
2117 ** ^An [INSERT] that fails due to a constraint violation is not a
2118 ** successful [INSERT] and does not change the value returned by this
2119 ** routine.  ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
2120 ** and INSERT OR ABORT make no changes to the return value of this
2121 ** routine when their insertion fails.  ^(When INSERT OR REPLACE
2122 ** encounters a constraint violation, it does not fail.  The
2123 ** INSERT continues to completion after deleting rows that caused
2124 ** the constraint problem so INSERT OR REPLACE will always change
2125 ** the return value of this interface.)^
2126 **
2127 ** ^For the purposes of this routine, an [INSERT] is considered to
2128 ** be successful even if it is subsequently rolled back.
2129 **
2130 ** This function is accessible to SQL statements via the
2131 ** [last_insert_rowid() SQL function].
2132 **
2133 ** If a separate thread performs a new [INSERT] on the same
2134 ** database connection while the [sqlite3_last_insert_rowid()]
2135 ** function is running and thus changes the last insert [rowid],
2136 ** then the value returned by [sqlite3_last_insert_rowid()] is
2137 ** unpredictable and might not equal either the old or the new
2138 ** last insert [rowid].
2139 */
2140 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3*);
2141
2142 /*
2143 ** CAPI3REF: Count The Number Of Rows Modified
2144 **
2145 ** ^This function returns the number of rows modified, inserted or
2146 ** deleted by the most recently completed INSERT, UPDATE or DELETE
2147 ** statement on the database connection specified by the only parameter.
2148 ** ^Executing any other type of SQL statement does not modify the value
2149 ** returned by this function.
2150 **
2151 ** ^Only changes made directly by the INSERT, UPDATE or DELETE statement are
2152 ** considered - auxiliary changes caused by [CREATE TRIGGER | triggers], 
2153 ** [foreign key actions] or [REPLACE] constraint resolution are not counted.
2154 ** 
2155 ** Changes to a view that are intercepted by 
2156 ** [INSTEAD OF trigger | INSTEAD OF triggers] are not counted. ^The value 
2157 ** returned by sqlite3_changes() immediately after an INSERT, UPDATE or 
2158 ** DELETE statement run on a view is always zero. Only changes made to real 
2159 ** tables are counted.
2160 **
2161 ** Things are more complicated if the sqlite3_changes() function is
2162 ** executed while a trigger program is running. This may happen if the
2163 ** program uses the [changes() SQL function], or if some other callback
2164 ** function invokes sqlite3_changes() directly. Essentially:
2165 ** 
2166 ** <ul>
2167 **   <li> ^(Before entering a trigger program the value returned by
2168 **        sqlite3_changes() function is saved. After the trigger program 
2169 **        has finished, the original value is restored.)^
2170 ** 
2171 **   <li> ^(Within a trigger program each INSERT, UPDATE and DELETE 
2172 **        statement sets the value returned by sqlite3_changes() 
2173 **        upon completion as normal. Of course, this value will not include 
2174 **        any changes performed by sub-triggers, as the sqlite3_changes() 
2175 **        value will be saved and restored after each sub-trigger has run.)^
2176 ** </ul>
2177 ** 
2178 ** ^This means that if the changes() SQL function (or similar) is used
2179 ** by the first INSERT, UPDATE or DELETE statement within a trigger, it 
2180 ** returns the value as set when the calling statement began executing.
2181 ** ^If it is used by the second or subsequent such statement within a trigger 
2182 ** program, the value returned reflects the number of rows modified by the 
2183 ** previous INSERT, UPDATE or DELETE statement within the same trigger.
2184 **
2185 ** See also the [sqlite3_total_changes()] interface, the
2186 ** [count_changes pragma], and the [changes() SQL function].
2187 **
2188 ** If a separate thread makes changes on the same database connection
2189 ** while [sqlite3_changes()] is running then the value returned
2190 ** is unpredictable and not meaningful.
2191 */
2192 SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3*);
2193
2194 /*
2195 ** CAPI3REF: Total Number Of Rows Modified
2196 **
2197 ** ^This function returns the total number of rows inserted, modified or
2198 ** deleted by all [INSERT], [UPDATE] or [DELETE] statements completed
2199 ** since the database connection was opened, including those executed as
2200 ** part of trigger programs. ^Executing any other type of SQL statement
2201 ** does not affect the value returned by sqlite3_total_changes().
2202 ** 
2203 ** ^Changes made as part of [foreign key actions] are included in the
2204 ** count, but those made as part of REPLACE constraint resolution are
2205 ** not. ^Changes to a view that are intercepted by INSTEAD OF triggers 
2206 ** are not counted.
2207 ** 
2208 ** See also the [sqlite3_changes()] interface, the
2209 ** [count_changes pragma], and the [total_changes() SQL function].
2210 **
2211 ** If a separate thread makes changes on the same database connection
2212 ** while [sqlite3_total_changes()] is running then the value
2213 ** returned is unpredictable and not meaningful.
2214 */
2215 SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3*);
2216
2217 /*
2218 ** CAPI3REF: Interrupt A Long-Running Query
2219 **
2220 ** ^This function causes any pending database operation to abort and
2221 ** return at its earliest opportunity. This routine is typically
2222 ** called in response to a user action such as pressing "Cancel"
2223 ** or Ctrl-C where the user wants a long query operation to halt
2224 ** immediately.
2225 **
2226 ** ^It is safe to call this routine from a thread different from the
2227 ** thread that is currently running the database operation.  But it
2228 ** is not safe to call this routine with a [database connection] that
2229 ** is closed or might close before sqlite3_interrupt() returns.
2230 **
2231 ** ^If an SQL operation is very nearly finished at the time when
2232 ** sqlite3_interrupt() is called, then it might not have an opportunity
2233 ** to be interrupted and might continue to completion.
2234 **
2235 ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
2236 ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
2237 ** that is inside an explicit transaction, then the entire transaction
2238 ** will be rolled back automatically.
2239 **
2240 ** ^The sqlite3_interrupt(D) call is in effect until all currently running
2241 ** SQL statements on [database connection] D complete.  ^Any new SQL statements
2242 ** that are started after the sqlite3_interrupt() call and before the 
2243 ** running statements reaches zero are interrupted as if they had been
2244 ** running prior to the sqlite3_interrupt() call.  ^New SQL statements
2245 ** that are started after the running statement count reaches zero are
2246 ** not effected by the sqlite3_interrupt().
2247 ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
2248 ** SQL statements is a no-op and has no effect on SQL statements
2249 ** that are started after the sqlite3_interrupt() call returns.
2250 **
2251 ** If the database connection closes while [sqlite3_interrupt()]
2252 ** is running then bad things will likely happen.
2253 */
2254 SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3*);
2255
2256 /*
2257 ** CAPI3REF: Determine If An SQL Statement Is Complete
2258 **
2259 ** These routines are useful during command-line input to determine if the
2260 ** currently entered text seems to form a complete SQL statement or
2261 ** if additional input is needed before sending the text into
2262 ** SQLite for parsing.  ^These routines return 1 if the input string
2263 ** appears to be a complete SQL statement.  ^A statement is judged to be
2264 ** complete if it ends with a semicolon token and is not a prefix of a
2265 ** well-formed CREATE TRIGGER statement.  ^Semicolons that are embedded within
2266 ** string literals or quoted identifier names or comments are not
2267 ** independent tokens (they are part of the token in which they are
2268 ** embedded) and thus do not count as a statement terminator.  ^Whitespace
2269 ** and comments that follow the final semicolon are ignored.
2270 **
2271 ** ^These routines return 0 if the statement is incomplete.  ^If a
2272 ** memory allocation fails, then SQLITE_NOMEM is returned.
2273 **
2274 ** ^These routines do not parse the SQL statements thus
2275 ** will not detect syntactically incorrect SQL.
2276 **
2277 ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior 
2278 ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
2279 ** automatically by sqlite3_complete16().  If that initialization fails,
2280 ** then the return value from sqlite3_complete16() will be non-zero
2281 ** regardless of whether or not the input SQL is complete.)^
2282 **
2283 ** The input to [sqlite3_complete()] must be a zero-terminated
2284 ** UTF-8 string.
2285 **
2286 ** The input to [sqlite3_complete16()] must be a zero-terminated
2287 ** UTF-16 string in native byte order.
2288 */
2289 SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *sql);
2290 SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *sql);
2291
2292 /*
2293 ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
2294 ** KEYWORDS: {busy-handler callback} {busy handler}
2295 **
2296 ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
2297 ** that might be invoked with argument P whenever
2298 ** an attempt is made to access a database table associated with
2299 ** [database connection] D when another thread
2300 ** or process has the table locked.
2301 ** The sqlite3_busy_handler() interface is used to implement
2302 ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
2303 **
2304 ** ^If the busy callback is NULL, then [SQLITE_BUSY]
2305 ** is returned immediately upon encountering the lock.  ^If the busy callback
2306 ** is not NULL, then the callback might be invoked with two arguments.
2307 **
2308 ** ^The first argument to the busy handler is a copy of the void* pointer which
2309 ** is the third argument to sqlite3_busy_handler().  ^The second argument to
2310 ** the busy handler callback is the number of times that the busy handler has
2311 ** been invoked previously for the same locking event.  ^If the
2312 ** busy callback returns 0, then no additional attempts are made to
2313 ** access the database and [SQLITE_BUSY] is returned
2314 ** to the application.
2315 ** ^If the callback returns non-zero, then another attempt
2316 ** is made to access the database and the cycle repeats.
2317 **
2318 ** The presence of a busy handler does not guarantee that it will be invoked
2319 ** when there is lock contention. ^If SQLite determines that invoking the busy
2320 ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
2321 ** to the application instead of invoking the 
2322 ** busy handler.
2323 ** Consider a scenario where one process is holding a read lock that
2324 ** it is trying to promote to a reserved lock and
2325 ** a second process is holding a reserved lock that it is trying
2326 ** to promote to an exclusive lock.  The first process cannot proceed
2327 ** because it is blocked by the second and the second process cannot
2328 ** proceed because it is blocked by the first.  If both processes
2329 ** invoke the busy handlers, neither will make any progress.  Therefore,
2330 ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
2331 ** will induce the first process to release its read lock and allow
2332 ** the second process to proceed.
2333 **
2334 ** ^The default busy callback is NULL.
2335 **
2336 ** ^(There can only be a single busy handler defined for each
2337 ** [database connection].  Setting a new busy handler clears any
2338 ** previously set handler.)^  ^Note that calling [sqlite3_busy_timeout()]
2339 ** or evaluating [PRAGMA busy_timeout=N] will change the
2340 ** busy handler and thus clear any previously set busy handler.
2341 **
2342 ** The busy callback should not take any actions which modify the
2343 ** database connection that invoked the busy handler.  In other words,
2344 ** the busy handler is not reentrant.  Any such actions
2345 ** result in undefined behavior.
2346 ** 
2347 ** A busy handler must not close the database connection
2348 ** or [prepared statement] that invoked the busy handler.
2349 */
2350 SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
2351
2352 /*
2353 ** CAPI3REF: Set A Busy Timeout
2354 **
2355 ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
2356 ** for a specified amount of time when a table is locked.  ^The handler
2357 ** will sleep multiple times until at least "ms" milliseconds of sleeping
2358 ** have accumulated.  ^After at least "ms" milliseconds of sleeping,
2359 ** the handler returns 0 which causes [sqlite3_step()] to return
2360 ** [SQLITE_BUSY].
2361 **
2362 ** ^Calling this routine with an argument less than or equal to zero
2363 ** turns off all busy handlers.
2364 **
2365 ** ^(There can only be a single busy handler for a particular
2366 ** [database connection] at any given moment.  If another busy handler
2367 ** was defined  (using [sqlite3_busy_handler()]) prior to calling
2368 ** this routine, that other busy handler is cleared.)^
2369 **
2370 ** See also:  [PRAGMA busy_timeout]
2371 */
2372 SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3*, int ms);
2373
2374 /*
2375 ** CAPI3REF: Convenience Routines For Running Queries
2376 **
2377 ** This is a legacy interface that is preserved for backwards compatibility.
2378 ** Use of this interface is not recommended.
2379 **
2380 ** Definition: A <b>result table</b> is memory data structure created by the
2381 ** [sqlite3_get_table()] interface.  A result table records the
2382 ** complete query results from one or more queries.
2383 **
2384 ** The table conceptually has a number of rows and columns.  But
2385 ** these numbers are not part of the result table itself.  These
2386 ** numbers are obtained separately.  Let N be the number of rows
2387 ** and M be the number of columns.
2388 **
2389 ** A result table is an array of pointers to zero-terminated UTF-8 strings.
2390 ** There are (N+1)*M elements in the array.  The first M pointers point
2391 ** to zero-terminated strings that  contain the names of the columns.
2392 ** The remaining entries all point to query results.  NULL values result
2393 ** in NULL pointers.  All other values are in their UTF-8 zero-terminated
2394 ** string representation as returned by [sqlite3_column_text()].
2395 **
2396 ** A result table might consist of one or more memory allocations.
2397 ** It is not safe to pass a result table directly to [sqlite3_free()].
2398 ** A result table should be deallocated using [sqlite3_free_table()].
2399 **
2400 ** ^(As an example of the result table format, suppose a query result
2401 ** is as follows:
2402 **
2403 ** <blockquote><pre>
2404 **        Name        | Age
2405 **        -----------------------
2406 **        Alice       | 43
2407 **        Bob         | 28
2408 **        Cindy       | 21
2409 ** </pre></blockquote>
2410 **
2411 ** There are two column (M==2) and three rows (N==3).  Thus the
2412 ** result table has 8 entries.  Suppose the result table is stored
2413 ** in an array names azResult.  Then azResult holds this content:
2414 **
2415 ** <blockquote><pre>
2416 **        azResult&#91;0] = "Name";
2417 **        azResult&#91;1] = "Age";
2418 **        azResult&#91;2] = "Alice";
2419 **        azResult&#91;3] = "43";
2420 **        azResult&#91;4] = "Bob";
2421 **        azResult&#91;5] = "28";
2422 **        azResult&#91;6] = "Cindy";
2423 **        azResult&#91;7] = "21";
2424 ** </pre></blockquote>)^
2425 **
2426 ** ^The sqlite3_get_table() function evaluates one or more
2427 ** semicolon-separated SQL statements in the zero-terminated UTF-8
2428 ** string of its 2nd parameter and returns a result table to the
2429 ** pointer given in its 3rd parameter.
2430 **
2431 ** After the application has finished with the result from sqlite3_get_table(),
2432 ** it must pass the result table pointer to sqlite3_free_table() in order to
2433 ** release the memory that was malloced.  Because of the way the
2434 ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
2435 ** function must not try to call [sqlite3_free()] directly.  Only
2436 ** [sqlite3_free_table()] is able to release the memory properly and safely.
2437 **
2438 ** The sqlite3_get_table() interface is implemented as a wrapper around
2439 ** [sqlite3_exec()].  The sqlite3_get_table() routine does not have access
2440 ** to any internal data structures of SQLite.  It uses only the public
2441 ** interface defined here.  As a consequence, errors that occur in the
2442 ** wrapper layer outside of the internal [sqlite3_exec()] call are not
2443 ** reflected in subsequent calls to [sqlite3_errcode()] or
2444 ** [sqlite3_errmsg()].
2445 */
2446 SQLITE_API int SQLITE_STDCALL sqlite3_get_table(
2447   sqlite3 *db,          /* An open database */
2448   const char *zSql,     /* SQL to be evaluated */
2449   char ***pazResult,    /* Results of the query */
2450   int *pnRow,           /* Number of result rows written here */
2451   int *pnColumn,        /* Number of result columns written here */
2452   char **pzErrmsg       /* Error msg written here */
2453 );
2454 SQLITE_API void SQLITE_STDCALL sqlite3_free_table(char **result);
2455
2456 /*
2457 ** CAPI3REF: Formatted String Printing Functions
2458 **
2459 ** These routines are work-alikes of the "printf()" family of functions
2460 ** from the standard C library.
2461 ** These routines understand most of the common K&R formatting options,
2462 ** plus some additional non-standard formats, detailed below.
2463 ** Note that some of the more obscure formatting options from recent
2464 ** C-library standards are omitted from this implementation.
2465 **
2466 ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
2467 ** results into memory obtained from [sqlite3_malloc()].
2468 ** The strings returned by these two routines should be
2469 ** released by [sqlite3_free()].  ^Both routines return a
2470 ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
2471 ** memory to hold the resulting string.
2472 **
2473 ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
2474 ** the standard C library.  The result is written into the
2475 ** buffer supplied as the second parameter whose size is given by
2476 ** the first parameter. Note that the order of the
2477 ** first two parameters is reversed from snprintf().)^  This is an
2478 ** historical accident that cannot be fixed without breaking
2479 ** backwards compatibility.  ^(Note also that sqlite3_snprintf()
2480 ** returns a pointer to its buffer instead of the number of
2481 ** characters actually written into the buffer.)^  We admit that
2482 ** the number of characters written would be a more useful return
2483 ** value but we cannot change the implementation of sqlite3_snprintf()
2484 ** now without breaking compatibility.
2485 **
2486 ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
2487 ** guarantees that the buffer is always zero-terminated.  ^The first
2488 ** parameter "n" is the total size of the buffer, including space for
2489 ** the zero terminator.  So the longest string that can be completely
2490 ** written will be n-1 characters.
2491 **
2492 ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
2493 **
2494 ** These routines all implement some additional formatting
2495 ** options that are useful for constructing SQL statements.
2496 ** All of the usual printf() formatting options apply.  In addition, there
2497 ** is are "%q", "%Q", "%w" and "%z" options.
2498 **
2499 ** ^(The %q option works like %s in that it substitutes a nul-terminated
2500 ** string from the argument list.  But %q also doubles every '\'' character.
2501 ** %q is designed for use inside a string literal.)^  By doubling each '\''
2502 ** character it escapes that character and allows it to be inserted into
2503 ** the string.
2504 **
2505 ** For example, assume the string variable zText contains text as follows:
2506 **
2507 ** <blockquote><pre>
2508 **  char *zText = "It's a happy day!";
2509 ** </pre></blockquote>
2510 **
2511 ** One can use this text in an SQL statement as follows:
2512 **
2513 ** <blockquote><pre>
2514 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
2515 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2516 **  sqlite3_free(zSQL);
2517 ** </pre></blockquote>
2518 **
2519 ** Because the %q format string is used, the '\'' character in zText
2520 ** is escaped and the SQL generated is as follows:
2521 **
2522 ** <blockquote><pre>
2523 **  INSERT INTO table1 VALUES('It''s a happy day!')
2524 ** </pre></blockquote>
2525 **
2526 ** This is correct.  Had we used %s instead of %q, the generated SQL
2527 ** would have looked like this:
2528 **
2529 ** <blockquote><pre>
2530 **  INSERT INTO table1 VALUES('It's a happy day!');
2531 ** </pre></blockquote>
2532 **
2533 ** This second example is an SQL syntax error.  As a general rule you should
2534 ** always use %q instead of %s when inserting text into a string literal.
2535 **
2536 ** ^(The %Q option works like %q except it also adds single quotes around
2537 ** the outside of the total string.  Additionally, if the parameter in the
2538 ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
2539 ** single quotes).)^  So, for example, one could say:
2540 **
2541 ** <blockquote><pre>
2542 **  char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
2543 **  sqlite3_exec(db, zSQL, 0, 0, 0);
2544 **  sqlite3_free(zSQL);
2545 ** </pre></blockquote>
2546 **
2547 ** The code above will render a correct SQL statement in the zSQL
2548 ** variable even if the zText variable is a NULL pointer.
2549 **
2550 ** ^(The "%w" formatting option is like "%q" except that it expects to
2551 ** be contained within double-quotes instead of single quotes, and it
2552 ** escapes the double-quote character instead of the single-quote
2553 ** character.)^  The "%w" formatting option is intended for safely inserting
2554 ** table and column names into a constructed SQL statement.
2555 **
2556 ** ^(The "%z" formatting option works like "%s" but with the
2557 ** addition that after the string has been read and copied into
2558 ** the result, [sqlite3_free()] is called on the input string.)^
2559 */
2560 SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char*,...);
2561 SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char*, va_list);
2562 SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int,char*,const char*, ...);
2563 SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int,char*,const char*, va_list);
2564
2565 /*
2566 ** CAPI3REF: Memory Allocation Subsystem
2567 **
2568 ** The SQLite core uses these three routines for all of its own
2569 ** internal memory allocation needs. "Core" in the previous sentence
2570 ** does not include operating-system specific VFS implementation.  The
2571 ** Windows VFS uses native malloc() and free() for some operations.
2572 **
2573 ** ^The sqlite3_malloc() routine returns a pointer to a block
2574 ** of memory at least N bytes in length, where N is the parameter.
2575 ** ^If sqlite3_malloc() is unable to obtain sufficient free
2576 ** memory, it returns a NULL pointer.  ^If the parameter N to
2577 ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
2578 ** a NULL pointer.
2579 **
2580 ** ^The sqlite3_malloc64(N) routine works just like
2581 ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
2582 ** of a signed 32-bit integer.
2583 **
2584 ** ^Calling sqlite3_free() with a pointer previously returned
2585 ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
2586 ** that it might be reused.  ^The sqlite3_free() routine is
2587 ** a no-op if is called with a NULL pointer.  Passing a NULL pointer
2588 ** to sqlite3_free() is harmless.  After being freed, memory
2589 ** should neither be read nor written.  Even reading previously freed
2590 ** memory might result in a segmentation fault or other severe error.
2591 ** Memory corruption, a segmentation fault, or other severe error
2592 ** might result if sqlite3_free() is called with a non-NULL pointer that
2593 ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
2594 **
2595 ** ^The sqlite3_realloc(X,N) interface attempts to resize a
2596 ** prior memory allocation X to be at least N bytes.
2597 ** ^If the X parameter to sqlite3_realloc(X,N)
2598 ** is a NULL pointer then its behavior is identical to calling
2599 ** sqlite3_malloc(N).
2600 ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
2601 ** negative then the behavior is exactly the same as calling
2602 ** sqlite3_free(X).
2603 ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
2604 ** of at least N bytes in size or NULL if insufficient memory is available.
2605 ** ^If M is the size of the prior allocation, then min(N,M) bytes
2606 ** of the prior allocation are copied into the beginning of buffer returned
2607 ** by sqlite3_realloc(X,N) and the prior allocation is freed.
2608 ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
2609 ** prior allocation is not freed.
2610 **
2611 ** ^The sqlite3_realloc64(X,N) interfaces works the same as
2612 ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
2613 ** of a 32-bit signed integer.
2614 **
2615 ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
2616 ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
2617 ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
2618 ** ^The value returned by sqlite3_msize(X) might be larger than the number
2619 ** of bytes requested when X was allocated.  ^If X is a NULL pointer then
2620 ** sqlite3_msize(X) returns zero.  If X points to something that is not
2621 ** the beginning of memory allocation, or if it points to a formerly
2622 ** valid memory allocation that has now been freed, then the behavior
2623 ** of sqlite3_msize(X) is undefined and possibly harmful.
2624 **
2625 ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
2626 ** sqlite3_malloc64(), and sqlite3_realloc64()
2627 ** is always aligned to at least an 8 byte boundary, or to a
2628 ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
2629 ** option is used.
2630 **
2631 ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
2632 ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
2633 ** implementation of these routines to be omitted.  That capability
2634 ** is no longer provided.  Only built-in memory allocators can be used.
2635 **
2636 ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
2637 ** the system malloc() and free() directly when converting
2638 ** filenames between the UTF-8 encoding used by SQLite
2639 ** and whatever filename encoding is used by the particular Windows
2640 ** installation.  Memory allocation errors were detected, but
2641 ** they were reported back as [SQLITE_CANTOPEN] or
2642 ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
2643 **
2644 ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
2645 ** must be either NULL or else pointers obtained from a prior
2646 ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
2647 ** not yet been released.
2648 **
2649 ** The application must not read or write any part of
2650 ** a block of memory after it has been released using
2651 ** [sqlite3_free()] or [sqlite3_realloc()].
2652 */
2653 SQLITE_API void *SQLITE_STDCALL sqlite3_malloc(int);
2654 SQLITE_API void *SQLITE_STDCALL sqlite3_malloc64(sqlite3_uint64);
2655 SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void*, int);
2656 SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void*, sqlite3_uint64);
2657 SQLITE_API void SQLITE_STDCALL sqlite3_free(void*);
2658 SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void*);
2659
2660 /*
2661 ** CAPI3REF: Memory Allocator Statistics
2662 **
2663 ** SQLite provides these two interfaces for reporting on the status
2664 ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
2665 ** routines, which form the built-in memory allocation subsystem.
2666 **
2667 ** ^The [sqlite3_memory_used()] routine returns the number of bytes
2668 ** of memory currently outstanding (malloced but not freed).
2669 ** ^The [sqlite3_memory_highwater()] routine returns the maximum
2670 ** value of [sqlite3_memory_used()] since the high-water mark
2671 ** was last reset.  ^The values returned by [sqlite3_memory_used()] and
2672 ** [sqlite3_memory_highwater()] include any overhead
2673 ** added by SQLite in its implementation of [sqlite3_malloc()],
2674 ** but not overhead added by the any underlying system library
2675 ** routines that [sqlite3_malloc()] may call.
2676 **
2677 ** ^The memory high-water mark is reset to the current value of
2678 ** [sqlite3_memory_used()] if and only if the parameter to
2679 ** [sqlite3_memory_highwater()] is true.  ^The value returned
2680 ** by [sqlite3_memory_highwater(1)] is the high-water mark
2681 ** prior to the reset.
2682 */
2683 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_used(void);
2684 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_highwater(int resetFlag);
2685
2686 /*
2687 ** CAPI3REF: Pseudo-Random Number Generator
2688 **
2689 ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
2690 ** select random [ROWID | ROWIDs] when inserting new records into a table that
2691 ** already uses the largest possible [ROWID].  The PRNG is also used for
2692 ** the build-in random() and randomblob() SQL functions.  This interface allows
2693 ** applications to access the same PRNG for other purposes.
2694 **
2695 ** ^A call to this routine stores N bytes of randomness into buffer P.
2696 ** ^The P parameter can be a NULL pointer.
2697 **
2698 ** ^If this routine has not been previously called or if the previous
2699 ** call had N less than one or a NULL pointer for P, then the PRNG is
2700 ** seeded using randomness obtained from the xRandomness method of
2701 ** the default [sqlite3_vfs] object.
2702 ** ^If the previous call to this routine had an N of 1 or more and a
2703 ** non-NULL P then the pseudo-randomness is generated
2704 ** internally and without recourse to the [sqlite3_vfs] xRandomness
2705 ** method.
2706 */
2707 SQLITE_API void SQLITE_STDCALL sqlite3_randomness(int N, void *P);
2708
2709 /*
2710 ** CAPI3REF: Compile-Time Authorization Callbacks
2711 **
2712 ** ^This routine registers an authorizer callback with a particular
2713 ** [database connection], supplied in the first argument.
2714 ** ^The authorizer callback is invoked as SQL statements are being compiled
2715 ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
2716 ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()].  ^At various
2717 ** points during the compilation process, as logic is being created
2718 ** to perform various actions, the authorizer callback is invoked to
2719 ** see if those actions are allowed.  ^The authorizer callback should
2720 ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
2721 ** specific action but allow the SQL statement to continue to be
2722 ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
2723 ** rejected with an error.  ^If the authorizer callback returns
2724 ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
2725 ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
2726 ** the authorizer will fail with an error message.
2727 **
2728 ** When the callback returns [SQLITE_OK], that means the operation
2729 ** requested is ok.  ^When the callback returns [SQLITE_DENY], the
2730 ** [sqlite3_prepare_v2()] or equivalent call that triggered the
2731 ** authorizer will fail with an error message explaining that
2732 ** access is denied. 
2733 **
2734 ** ^The first parameter to the authorizer callback is a copy of the third
2735 ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
2736 ** to the callback is an integer [SQLITE_COPY | action code] that specifies
2737 ** the particular action to be authorized. ^The third through sixth parameters
2738 ** to the callback are zero-terminated strings that contain additional
2739 ** details about the action to be authorized.
2740 **
2741 ** ^If the action code is [SQLITE_READ]
2742 ** and the callback returns [SQLITE_IGNORE] then the
2743 ** [prepared statement] statement is constructed to substitute
2744 ** a NULL value in place of the table column that would have
2745 ** been read if [SQLITE_OK] had been returned.  The [SQLITE_IGNORE]
2746 ** return can be used to deny an untrusted user access to individual
2747 ** columns of a table.
2748 ** ^If the action code is [SQLITE_DELETE] and the callback returns
2749 ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
2750 ** [truncate optimization] is disabled and all rows are deleted individually.
2751 **
2752 ** An authorizer is used when [sqlite3_prepare | preparing]
2753 ** SQL statements from an untrusted source, to ensure that the SQL statements
2754 ** do not try to access data they are not allowed to see, or that they do not
2755 ** try to execute malicious statements that damage the database.  For
2756 ** example, an application may allow a user to enter arbitrary
2757 ** SQL queries for evaluation by a database.  But the application does
2758 ** not want the user to be able to make arbitrary changes to the
2759 ** database.  An authorizer could then be put in place while the
2760 ** user-entered SQL is being [sqlite3_prepare | prepared] that
2761 ** disallows everything except [SELECT] statements.
2762 **
2763 ** Applications that need to process SQL from untrusted sources
2764 ** might also consider lowering resource limits using [sqlite3_limit()]
2765 ** and limiting database size using the [max_page_count] [PRAGMA]
2766 ** in addition to using an authorizer.
2767 **
2768 ** ^(Only a single authorizer can be in place on a database connection
2769 ** at a time.  Each call to sqlite3_set_authorizer overrides the
2770 ** previous call.)^  ^Disable the authorizer by installing a NULL callback.
2771 ** The authorizer is disabled by default.
2772 **
2773 ** The authorizer callback must not do anything that will modify
2774 ** the database connection that invoked the authorizer callback.
2775 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2776 ** database connections for the meaning of "modify" in this paragraph.
2777 **
2778 ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
2779 ** statement might be re-prepared during [sqlite3_step()] due to a 
2780 ** schema change.  Hence, the application should ensure that the
2781 ** correct authorizer callback remains in place during the [sqlite3_step()].
2782 **
2783 ** ^Note that the authorizer callback is invoked only during
2784 ** [sqlite3_prepare()] or its variants.  Authorization is not
2785 ** performed during statement evaluation in [sqlite3_step()], unless
2786 ** as stated in the previous paragraph, sqlite3_step() invokes
2787 ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
2788 */
2789 SQLITE_API int SQLITE_STDCALL sqlite3_set_authorizer(
2790   sqlite3*,
2791   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
2792   void *pUserData
2793 );
2794
2795 /*
2796 ** CAPI3REF: Authorizer Return Codes
2797 **
2798 ** The [sqlite3_set_authorizer | authorizer callback function] must
2799 ** return either [SQLITE_OK] or one of these two constants in order
2800 ** to signal SQLite whether or not the action is permitted.  See the
2801 ** [sqlite3_set_authorizer | authorizer documentation] for additional
2802 ** information.
2803 **
2804 ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
2805 ** returned from the [sqlite3_vtab_on_conflict()] interface.
2806 */
2807 #define SQLITE_DENY   1   /* Abort the SQL statement with an error */
2808 #define SQLITE_IGNORE 2   /* Don't allow access, but don't generate an error */
2809
2810 /*
2811 ** CAPI3REF: Authorizer Action Codes
2812 **
2813 ** The [sqlite3_set_authorizer()] interface registers a callback function
2814 ** that is invoked to authorize certain SQL statement actions.  The
2815 ** second parameter to the callback is an integer code that specifies
2816 ** what action is being authorized.  These are the integer action codes that
2817 ** the authorizer callback may be passed.
2818 **
2819 ** These action code values signify what kind of operation is to be
2820 ** authorized.  The 3rd and 4th parameters to the authorization
2821 ** callback function will be parameters or NULL depending on which of these
2822 ** codes is used as the second parameter.  ^(The 5th parameter to the
2823 ** authorizer callback is the name of the database ("main", "temp",
2824 ** etc.) if applicable.)^  ^The 6th parameter to the authorizer callback
2825 ** is the name of the inner-most trigger or view that is responsible for
2826 ** the access attempt or NULL if this access attempt is directly from
2827 ** top-level SQL code.
2828 */
2829 /******************************************* 3rd ************ 4th ***********/
2830 #define SQLITE_CREATE_INDEX          1   /* Index Name      Table Name      */
2831 #define SQLITE_CREATE_TABLE          2   /* Table Name      NULL            */
2832 #define SQLITE_CREATE_TEMP_INDEX     3   /* Index Name      Table Name      */
2833 #define SQLITE_CREATE_TEMP_TABLE     4   /* Table Name      NULL            */
2834 #define SQLITE_CREATE_TEMP_TRIGGER   5   /* Trigger Name    Table Name      */
2835 #define SQLITE_CREATE_TEMP_VIEW      6   /* View Name       NULL            */
2836 #define SQLITE_CREATE_TRIGGER        7   /* Trigger Name    Table Name      */
2837 #define SQLITE_CREATE_VIEW           8   /* View Name       NULL            */
2838 #define SQLITE_DELETE                9   /* Table Name      NULL            */
2839 #define SQLITE_DROP_INDEX           10   /* Index Name      Table Name      */
2840 #define SQLITE_DROP_TABLE           11   /* Table Name      NULL            */
2841 #define SQLITE_DROP_TEMP_INDEX      12   /* Index Name      Table Name      */
2842 #define SQLITE_DROP_TEMP_TABLE      13   /* Table Name      NULL            */
2843 #define SQLITE_DROP_TEMP_TRIGGER    14   /* Trigger Name    Table Name      */
2844 #define SQLITE_DROP_TEMP_VIEW       15   /* View Name       NULL            */
2845 #define SQLITE_DROP_TRIGGER         16   /* Trigger Name    Table Name      */
2846 #define SQLITE_DROP_VIEW            17   /* View Name       NULL            */
2847 #define SQLITE_INSERT               18   /* Table Name      NULL            */
2848 #define SQLITE_PRAGMA               19   /* Pragma Name     1st arg or NULL */
2849 #define SQLITE_READ                 20   /* Table Name      Column Name     */
2850 #define SQLITE_SELECT               21   /* NULL            NULL            */
2851 #define SQLITE_TRANSACTION          22   /* Operation       NULL            */
2852 #define SQLITE_UPDATE               23   /* Table Name      Column Name     */
2853 #define SQLITE_ATTACH               24   /* Filename        NULL            */
2854 #define SQLITE_DETACH               25   /* Database Name   NULL            */
2855 #define SQLITE_ALTER_TABLE          26   /* Database Name   Table Name      */
2856 #define SQLITE_REINDEX              27   /* Index Name      NULL            */
2857 #define SQLITE_ANALYZE              28   /* Table Name      NULL            */
2858 #define SQLITE_CREATE_VTABLE        29   /* Table Name      Module Name     */
2859 #define SQLITE_DROP_VTABLE          30   /* Table Name      Module Name     */
2860 #define SQLITE_FUNCTION             31   /* NULL            Function Name   */
2861 #define SQLITE_SAVEPOINT            32   /* Operation       Savepoint Name  */
2862 #define SQLITE_COPY                  0   /* No longer used */
2863 #define SQLITE_RECURSIVE            33   /* NULL            NULL            */
2864
2865 /*
2866 ** CAPI3REF: Tracing And Profiling Functions
2867 **
2868 ** These routines register callback functions that can be used for
2869 ** tracing and profiling the execution of SQL statements.
2870 **
2871 ** ^The callback function registered by sqlite3_trace() is invoked at
2872 ** various times when an SQL statement is being run by [sqlite3_step()].
2873 ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
2874 ** SQL statement text as the statement first begins executing.
2875 ** ^(Additional sqlite3_trace() callbacks might occur
2876 ** as each triggered subprogram is entered.  The callbacks for triggers
2877 ** contain a UTF-8 SQL comment that identifies the trigger.)^
2878 **
2879 ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
2880 ** the length of [bound parameter] expansion in the output of sqlite3_trace().
2881 **
2882 ** ^The callback function registered by sqlite3_profile() is invoked
2883 ** as each SQL statement finishes.  ^The profile callback contains
2884 ** the original statement text and an estimate of wall-clock time
2885 ** of how long that statement took to run.  ^The profile callback
2886 ** time is in units of nanoseconds, however the current implementation
2887 ** is only capable of millisecond resolution so the six least significant
2888 ** digits in the time are meaningless.  Future versions of SQLite
2889 ** might provide greater resolution on the profiler callback.  The
2890 ** sqlite3_profile() function is considered experimental and is
2891 ** subject to change in future versions of SQLite.
2892 */
2893 SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
2894 SQLITE_API SQLITE_EXPERIMENTAL void *SQLITE_STDCALL sqlite3_profile(sqlite3*,
2895    void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
2896
2897 /*
2898 ** CAPI3REF: Query Progress Callbacks
2899 **
2900 ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
2901 ** function X to be invoked periodically during long running calls to
2902 ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
2903 ** database connection D.  An example use for this
2904 ** interface is to keep a GUI updated during a large query.
2905 **
2906 ** ^The parameter P is passed through as the only parameter to the 
2907 ** callback function X.  ^The parameter N is the approximate number of 
2908 ** [virtual machine instructions] that are evaluated between successive
2909 ** invocations of the callback X.  ^If N is less than one then the progress
2910 ** handler is disabled.
2911 **
2912 ** ^Only a single progress handler may be defined at one time per
2913 ** [database connection]; setting a new progress handler cancels the
2914 ** old one.  ^Setting parameter X to NULL disables the progress handler.
2915 ** ^The progress handler is also disabled by setting N to a value less
2916 ** than 1.
2917 **
2918 ** ^If the progress callback returns non-zero, the operation is
2919 ** interrupted.  This feature can be used to implement a
2920 ** "Cancel" button on a GUI progress dialog box.
2921 **
2922 ** The progress handler callback must not do anything that will modify
2923 ** the database connection that invoked the progress handler.
2924 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
2925 ** database connections for the meaning of "modify" in this paragraph.
2926 **
2927 */
2928 SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
2929
2930 /*
2931 ** CAPI3REF: Opening A New Database Connection
2932 **
2933 ** ^These routines open an SQLite database file as specified by the 
2934 ** filename argument. ^The filename argument is interpreted as UTF-8 for
2935 ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
2936 ** order for sqlite3_open16(). ^(A [database connection] handle is usually
2937 ** returned in *ppDb, even if an error occurs.  The only exception is that
2938 ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
2939 ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
2940 ** object.)^ ^(If the database is opened (and/or created) successfully, then
2941 ** [SQLITE_OK] is returned.  Otherwise an [error code] is returned.)^ ^The
2942 ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
2943 ** an English language description of the error following a failure of any
2944 ** of the sqlite3_open() routines.
2945 **
2946 ** ^The default encoding will be UTF-8 for databases created using
2947 ** sqlite3_open() or sqlite3_open_v2().  ^The default encoding for databases
2948 ** created using sqlite3_open16() will be UTF-16 in the native byte order.
2949 **
2950 ** Whether or not an error occurs when it is opened, resources
2951 ** associated with the [database connection] handle should be released by
2952 ** passing it to [sqlite3_close()] when it is no longer required.
2953 **
2954 ** The sqlite3_open_v2() interface works like sqlite3_open()
2955 ** except that it accepts two additional parameters for additional control
2956 ** over the new database connection.  ^(The flags parameter to
2957 ** sqlite3_open_v2() can take one of
2958 ** the following three values, optionally combined with the 
2959 ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
2960 ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
2961 **
2962 ** <dl>
2963 ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
2964 ** <dd>The database is opened in read-only mode.  If the database does not
2965 ** already exist, an error is returned.</dd>)^
2966 **
2967 ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
2968 ** <dd>The database is opened for reading and writing if possible, or reading
2969 ** only if the file is write protected by the operating system.  In either
2970 ** case the database must already exist, otherwise an error is returned.</dd>)^
2971 **
2972 ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
2973 ** <dd>The database is opened for reading and writing, and is created if
2974 ** it does not already exist. This is the behavior that is always used for
2975 ** sqlite3_open() and sqlite3_open16().</dd>)^
2976 ** </dl>
2977 **
2978 ** If the 3rd parameter to sqlite3_open_v2() is not one of the
2979 ** combinations shown above optionally combined with other
2980 ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
2981 ** then the behavior is undefined.
2982 **
2983 ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
2984 ** opens in the multi-thread [threading mode] as long as the single-thread
2985 ** mode has not been set at compile-time or start-time.  ^If the
2986 ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
2987 ** in the serialized [threading mode] unless single-thread was
2988 ** previously selected at compile-time or start-time.
2989 ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
2990 ** eligible to use [shared cache mode], regardless of whether or not shared
2991 ** cache is enabled using [sqlite3_enable_shared_cache()].  ^The
2992 ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
2993 ** participate in [shared cache mode] even if it is enabled.
2994 **
2995 ** ^The fourth parameter to sqlite3_open_v2() is the name of the
2996 ** [sqlite3_vfs] object that defines the operating system interface that
2997 ** the new database connection should use.  ^If the fourth parameter is
2998 ** a NULL pointer then the default [sqlite3_vfs] object is used.
2999 **
3000 ** ^If the filename is ":memory:", then a private, temporary in-memory database
3001 ** is created for the connection.  ^This in-memory database will vanish when
3002 ** the database connection is closed.  Future versions of SQLite might
3003 ** make use of additional special filenames that begin with the ":" character.
3004 ** It is recommended that when a database filename actually does begin with
3005 ** a ":" character you should prefix the filename with a pathname such as
3006 ** "./" to avoid ambiguity.
3007 **
3008 ** ^If the filename is an empty string, then a private, temporary
3009 ** on-disk database will be created.  ^This private database will be
3010 ** automatically deleted as soon as the database connection is closed.
3011 **
3012 ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
3013 **
3014 ** ^If [URI filename] interpretation is enabled, and the filename argument
3015 ** begins with "file:", then the filename is interpreted as a URI. ^URI
3016 ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
3017 ** set in the fourth argument to sqlite3_open_v2(), or if it has
3018 ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
3019 ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
3020 ** As of SQLite version 3.7.7, URI filename interpretation is turned off
3021 ** by default, but future releases of SQLite might enable URI filename
3022 ** interpretation by default.  See "[URI filenames]" for additional
3023 ** information.
3024 **
3025 ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
3026 ** authority, then it must be either an empty string or the string 
3027 ** "localhost". ^If the authority is not an empty string or "localhost", an 
3028 ** error is returned to the caller. ^The fragment component of a URI, if 
3029 ** present, is ignored.
3030 **
3031 ** ^SQLite uses the path component of the URI as the name of the disk file
3032 ** which contains the database. ^If the path begins with a '/' character, 
3033 ** then it is interpreted as an absolute path. ^If the path does not begin 
3034 ** with a '/' (meaning that the authority section is omitted from the URI)
3035 ** then the path is interpreted as a relative path. 
3036 ** ^(On windows, the first component of an absolute path 
3037 ** is a drive specification (e.g. "C:").)^
3038 **
3039 ** [[core URI query parameters]]
3040 ** The query component of a URI may contain parameters that are interpreted
3041 ** either by SQLite itself, or by a [VFS | custom VFS implementation].
3042 ** SQLite and its built-in [VFSes] interpret the
3043 ** following query parameters:
3044 **
3045 ** <ul>
3046 **   <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
3047 **     a VFS object that provides the operating system interface that should
3048 **     be used to access the database file on disk. ^If this option is set to
3049 **     an empty string the default VFS object is used. ^Specifying an unknown
3050 **     VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
3051 **     present, then the VFS specified by the option takes precedence over
3052 **     the value passed as the fourth parameter to sqlite3_open_v2().
3053 **
3054 **   <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
3055 **     "rwc", or "memory". Attempting to set it to any other value is
3056 **     an error)^. 
3057 **     ^If "ro" is specified, then the database is opened for read-only 
3058 **     access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the 
3059 **     third argument to sqlite3_open_v2(). ^If the mode option is set to 
3060 **     "rw", then the database is opened for read-write (but not create) 
3061 **     access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had 
3062 **     been set. ^Value "rwc" is equivalent to setting both 
3063 **     SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE.  ^If the mode option is
3064 **     set to "memory" then a pure [in-memory database] that never reads
3065 **     or writes from disk is used. ^It is an error to specify a value for
3066 **     the mode parameter that is less restrictive than that specified by
3067 **     the flags passed in the third parameter to sqlite3_open_v2().
3068 **
3069 **   <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
3070 **     "private". ^Setting it to "shared" is equivalent to setting the
3071 **     SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
3072 **     sqlite3_open_v2(). ^Setting the cache parameter to "private" is 
3073 **     equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
3074 **     ^If sqlite3_open_v2() is used and the "cache" parameter is present in
3075 **     a URI filename, its value overrides any behavior requested by setting
3076 **     SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
3077 **
3078 **  <li> <b>psow</b>: ^The psow parameter indicates whether or not the
3079 **     [powersafe overwrite] property does or does not apply to the
3080 **     storage media on which the database file resides.
3081 **
3082 **  <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
3083 **     which if set disables file locking in rollback journal modes.  This
3084 **     is useful for accessing a database on a filesystem that does not
3085 **     support locking.  Caution:  Database corruption might result if two
3086 **     or more processes write to the same database and any one of those
3087 **     processes uses nolock=1.
3088 **
3089 **  <li> <b>immutable</b>: ^The immutable parameter is a boolean query
3090 **     parameter that indicates that the database file is stored on
3091 **     read-only media.  ^When immutable is set, SQLite assumes that the
3092 **     database file cannot be changed, even by a process with higher
3093 **     privilege, and so the database is opened read-only and all locking
3094 **     and change detection is disabled.  Caution: Setting the immutable
3095 **     property on a database file that does in fact change can result
3096 **     in incorrect query results and/or [SQLITE_CORRUPT] errors.
3097 **     See also: [SQLITE_IOCAP_IMMUTABLE].
3098 **       
3099 ** </ul>
3100 **
3101 ** ^Specifying an unknown parameter in the query component of a URI is not an
3102 ** error.  Future versions of SQLite might understand additional query
3103 ** parameters.  See "[query parameters with special meaning to SQLite]" for
3104 ** additional information.
3105 **
3106 ** [[URI filename examples]] <h3>URI filename examples</h3>
3107 **
3108 ** <table border="1" align=center cellpadding=5>
3109 ** <tr><th> URI filenames <th> Results
3110 ** <tr><td> file:data.db <td> 
3111 **          Open the file "data.db" in the current directory.
3112 ** <tr><td> file:/home/fred/data.db<br>
3113 **          file:///home/fred/data.db <br> 
3114 **          file://localhost/home/fred/data.db <br> <td> 
3115 **          Open the database file "/home/fred/data.db".
3116 ** <tr><td> file://darkstar/home/fred/data.db <td> 
3117 **          An error. "darkstar" is not a recognized authority.
3118 ** <tr><td style="white-space:nowrap"> 
3119 **          file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
3120 **     <td> Windows only: Open the file "data.db" on fred's desktop on drive
3121 **          C:. Note that the %20 escaping in this example is not strictly 
3122 **          necessary - space characters can be used literally
3123 **          in URI filenames.
3124 ** <tr><td> file:data.db?mode=ro&cache=private <td> 
3125 **          Open file "data.db" in the current directory for read-only access.
3126 **          Regardless of whether or not shared-cache mode is enabled by
3127 **          default, use a private cache.
3128 ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
3129 **          Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
3130 **          that uses dot-files in place of posix advisory locking.
3131 ** <tr><td> file:data.db?mode=readonly <td> 
3132 **          An error. "readonly" is not a valid option for the "mode" parameter.
3133 ** </table>
3134 **
3135 ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
3136 ** query components of a URI. A hexadecimal escape sequence consists of a
3137 ** percent sign - "%" - followed by exactly two hexadecimal digits 
3138 ** specifying an octet value. ^Before the path or query components of a
3139 ** URI filename are interpreted, they are encoded using UTF-8 and all 
3140 ** hexadecimal escape sequences replaced by a single byte containing the
3141 ** corresponding octet. If this process generates an invalid UTF-8 encoding,
3142 ** the results are undefined.
3143 **
3144 ** <b>Note to Windows users:</b>  The encoding used for the filename argument
3145 ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
3146 ** codepage is currently defined.  Filenames containing international
3147 ** characters must be converted to UTF-8 prior to passing them into
3148 ** sqlite3_open() or sqlite3_open_v2().
3149 **
3150 ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
3151 ** prior to calling sqlite3_open() or sqlite3_open_v2().  Otherwise, various
3152 ** features that require the use of temporary files may fail.
3153 **
3154 ** See also: [sqlite3_temp_directory]
3155 */
3156 SQLITE_API int SQLITE_STDCALL sqlite3_open(
3157   const char *filename,   /* Database filename (UTF-8) */
3158   sqlite3 **ppDb          /* OUT: SQLite db handle */
3159 );
3160 SQLITE_API int SQLITE_STDCALL sqlite3_open16(
3161   const void *filename,   /* Database filename (UTF-16) */
3162   sqlite3 **ppDb          /* OUT: SQLite db handle */
3163 );
3164 SQLITE_API int SQLITE_STDCALL sqlite3_open_v2(
3165   const char *filename,   /* Database filename (UTF-8) */
3166   sqlite3 **ppDb,         /* OUT: SQLite db handle */
3167   int flags,              /* Flags */
3168   const char *zVfs        /* Name of VFS module to use */
3169 );
3170
3171 /*
3172 ** CAPI3REF: Obtain Values For URI Parameters
3173 **
3174 ** These are utility routines, useful to VFS implementations, that check
3175 ** to see if a database file was a URI that contained a specific query 
3176 ** parameter, and if so obtains the value of that query parameter.
3177 **
3178 ** If F is the database filename pointer passed into the xOpen() method of 
3179 ** a VFS implementation when the flags parameter to xOpen() has one or 
3180 ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
3181 ** P is the name of the query parameter, then
3182 ** sqlite3_uri_parameter(F,P) returns the value of the P
3183 ** parameter if it exists or a NULL pointer if P does not appear as a 
3184 ** query parameter on F.  If P is a query parameter of F
3185 ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
3186 ** a pointer to an empty string.
3187 **
3188 ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
3189 ** parameter and returns true (1) or false (0) according to the value
3190 ** of P.  The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
3191 ** value of query parameter P is one of "yes", "true", or "on" in any
3192 ** case or if the value begins with a non-zero number.  The 
3193 ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
3194 ** query parameter P is one of "no", "false", or "off" in any case or
3195 ** if the value begins with a numeric zero.  If P is not a query
3196 ** parameter on F or if the value of P is does not match any of the
3197 ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
3198 **
3199 ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
3200 ** 64-bit signed integer and returns that integer, or D if P does not
3201 ** exist.  If the value of P is something other than an integer, then
3202 ** zero is returned.
3203 ** 
3204 ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
3205 ** sqlite3_uri_boolean(F,P,B) returns B.  If F is not a NULL pointer and
3206 ** is not a database file pathname pointer that SQLite passed into the xOpen
3207 ** VFS method, then the behavior of this routine is undefined and probably
3208 ** undesirable.
3209 */
3210 SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam);
3211 SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
3212 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
3213
3214
3215 /*
3216 ** CAPI3REF: Error Codes And Messages
3217 **
3218 ** ^If the most recent sqlite3_* API call associated with 
3219 ** [database connection] D failed, then the sqlite3_errcode(D) interface
3220 ** returns the numeric [result code] or [extended result code] for that
3221 ** API call.
3222 ** If the most recent API call was successful,
3223 ** then the return value from sqlite3_errcode() is undefined.
3224 ** ^The sqlite3_extended_errcode()
3225 ** interface is the same except that it always returns the 
3226 ** [extended result code] even when extended result codes are
3227 ** disabled.
3228 **
3229 ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
3230 ** text that describes the error, as either UTF-8 or UTF-16 respectively.
3231 ** ^(Memory to hold the error message string is managed internally.
3232 ** The application does not need to worry about freeing the result.
3233 ** However, the error string might be overwritten or deallocated by
3234 ** subsequent calls to other SQLite interface functions.)^
3235 **
3236 ** ^The sqlite3_errstr() interface returns the English-language text
3237 ** that describes the [result code], as UTF-8.
3238 ** ^(Memory to hold the error message string is managed internally
3239 ** and must not be freed by the application)^.
3240 **
3241 ** When the serialized [threading mode] is in use, it might be the
3242 ** case that a second error occurs on a separate thread in between
3243 ** the time of the first error and the call to these interfaces.
3244 ** When that happens, the second error will be reported since these
3245 ** interfaces always report the most recent result.  To avoid
3246 ** this, each thread can obtain exclusive use of the [database connection] D
3247 ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
3248 ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
3249 ** all calls to the interfaces listed here are completed.
3250 **
3251 ** If an interface fails with SQLITE_MISUSE, that means the interface
3252 ** was invoked incorrectly by the application.  In that case, the
3253 ** error code and message may or may not be set.
3254 */
3255 SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db);
3256 SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db);
3257 SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3*);
3258 SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3*);
3259 SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int);
3260
3261 /*
3262 ** CAPI3REF: SQL Statement Object
3263 ** KEYWORDS: {prepared statement} {prepared statements}
3264 **
3265 ** An instance of this object represents a single SQL statement.
3266 ** This object is variously known as a "prepared statement" or a
3267 ** "compiled SQL statement" or simply as a "statement".
3268 **
3269 ** The life of a statement object goes something like this:
3270 **
3271 ** <ol>
3272 ** <li> Create the object using [sqlite3_prepare_v2()] or a related
3273 **      function.
3274 ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
3275 **      interfaces.
3276 ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
3277 ** <li> Reset the statement using [sqlite3_reset()] then go back
3278 **      to step 2.  Do this zero or more times.
3279 ** <li> Destroy the object using [sqlite3_finalize()].
3280 ** </ol>
3281 **
3282 ** Refer to documentation on individual methods above for additional
3283 ** information.
3284 */
3285 typedef struct sqlite3_stmt sqlite3_stmt;
3286
3287 /*
3288 ** CAPI3REF: Run-time Limits
3289 **
3290 ** ^(This interface allows the size of various constructs to be limited
3291 ** on a connection by connection basis.  The first parameter is the
3292 ** [database connection] whose limit is to be set or queried.  The
3293 ** second parameter is one of the [limit categories] that define a
3294 ** class of constructs to be size limited.  The third parameter is the
3295 ** new limit for that construct.)^
3296 **
3297 ** ^If the new limit is a negative number, the limit is unchanged.
3298 ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a 
3299 ** [limits | hard upper bound]
3300 ** set at compile-time by a C preprocessor macro called
3301 ** [limits | SQLITE_MAX_<i>NAME</i>].
3302 ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
3303 ** ^Attempts to increase a limit above its hard upper bound are
3304 ** silently truncated to the hard upper bound.
3305 **
3306 ** ^Regardless of whether or not the limit was changed, the 
3307 ** [sqlite3_limit()] interface returns the prior value of the limit.
3308 ** ^Hence, to find the current value of a limit without changing it,
3309 ** simply invoke this interface with the third parameter set to -1.
3310 **
3311 ** Run-time limits are intended for use in applications that manage
3312 ** both their own internal database and also databases that are controlled
3313 ** by untrusted external sources.  An example application might be a
3314 ** web browser that has its own databases for storing history and
3315 ** separate databases controlled by JavaScript applications downloaded
3316 ** off the Internet.  The internal databases can be given the
3317 ** large, default limits.  Databases managed by external sources can
3318 ** be given much smaller limits designed to prevent a denial of service
3319 ** attack.  Developers might also want to use the [sqlite3_set_authorizer()]
3320 ** interface to further control untrusted SQL.  The size of the database
3321 ** created by an untrusted script can be contained using the
3322 ** [max_page_count] [PRAGMA].
3323 **
3324 ** New run-time limit categories may be added in future releases.
3325 */
3326 SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3*, int id, int newVal);
3327
3328 /*
3329 ** CAPI3REF: Run-Time Limit Categories
3330 ** KEYWORDS: {limit category} {*limit categories}
3331 **
3332 ** These constants define various performance limits
3333 ** that can be lowered at run-time using [sqlite3_limit()].
3334 ** The synopsis of the meanings of the various limits is shown below.
3335 ** Additional information is available at [limits | Limits in SQLite].
3336 **
3337 ** <dl>
3338 ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
3339 ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
3340 **
3341 ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
3342 ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
3343 **
3344 ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
3345 ** <dd>The maximum number of columns in a table definition or in the
3346 ** result set of a [SELECT] or the maximum number of columns in an index
3347 ** or in an ORDER BY or GROUP BY clause.</dd>)^
3348 **
3349 ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
3350 ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
3351 **
3352 ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
3353 ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
3354 **
3355 ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
3356 ** <dd>The maximum number of instructions in a virtual machine program
3357 ** used to implement an SQL statement.  This limit is not currently
3358 ** enforced, though that might be added in some future release of
3359 ** SQLite.</dd>)^
3360 **
3361 ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
3362 ** <dd>The maximum number of arguments on a function.</dd>)^
3363 **
3364 ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
3365 ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
3366 **
3367 ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
3368 ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
3369 ** <dd>The maximum length of the pattern argument to the [LIKE] or
3370 ** [GLOB] operators.</dd>)^
3371 **
3372 ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
3373 ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
3374 ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
3375 **
3376 ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
3377 ** <dd>The maximum depth of recursion for triggers.</dd>)^
3378 **
3379 ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
3380 ** <dd>The maximum number of auxiliary worker threads that a single
3381 ** [prepared statement] may start.</dd>)^
3382 ** </dl>
3383 */
3384 #define SQLITE_LIMIT_LENGTH                    0
3385 #define SQLITE_LIMIT_SQL_LENGTH                1
3386 #define SQLITE_LIMIT_COLUMN                    2
3387 #define SQLITE_LIMIT_EXPR_DEPTH                3
3388 #define SQLITE_LIMIT_COMPOUND_SELECT           4
3389 #define SQLITE_LIMIT_VDBE_OP                   5
3390 #define SQLITE_LIMIT_FUNCTION_ARG              6
3391 #define SQLITE_LIMIT_ATTACHED                  7
3392 #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH       8
3393 #define SQLITE_LIMIT_VARIABLE_NUMBER           9
3394 #define SQLITE_LIMIT_TRIGGER_DEPTH            10
3395 #define SQLITE_LIMIT_WORKER_THREADS           11
3396
3397 /*
3398 ** CAPI3REF: Compiling An SQL Statement
3399 ** KEYWORDS: {SQL statement compiler}
3400 **
3401 ** To execute an SQL query, it must first be compiled into a byte-code
3402 ** program using one of these routines.
3403 **
3404 ** The first argument, "db", is a [database connection] obtained from a
3405 ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
3406 ** [sqlite3_open16()].  The database connection must not have been closed.
3407 **
3408 ** The second argument, "zSql", is the statement to be compiled, encoded
3409 ** as either UTF-8 or UTF-16.  The sqlite3_prepare() and sqlite3_prepare_v2()
3410 ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
3411 ** use UTF-16.
3412 **
3413 ** ^If the nByte argument is negative, then zSql is read up to the
3414 ** first zero terminator. ^If nByte is positive, then it is the
3415 ** number of bytes read from zSql.  ^If nByte is zero, then no prepared
3416 ** statement is generated.
3417 ** If the caller knows that the supplied string is nul-terminated, then
3418 ** there is a small performance advantage to passing an nByte parameter that
3419 ** is the number of bytes in the input string <i>including</i>
3420 ** the nul-terminator.
3421 **
3422 ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
3423 ** past the end of the first SQL statement in zSql.  These routines only
3424 ** compile the first statement in zSql, so *pzTail is left pointing to
3425 ** what remains uncompiled.
3426 **
3427 ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
3428 ** executed using [sqlite3_step()].  ^If there is an error, *ppStmt is set
3429 ** to NULL.  ^If the input text contains no SQL (if the input is an empty
3430 ** string or a comment) then *ppStmt is set to NULL.
3431 ** The calling procedure is responsible for deleting the compiled
3432 ** SQL statement using [sqlite3_finalize()] after it has finished with it.
3433 ** ppStmt may not be NULL.
3434 **
3435 ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
3436 ** otherwise an [error code] is returned.
3437 **
3438 ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
3439 ** recommended for all new programs. The two older interfaces are retained
3440 ** for backwards compatibility, but their use is discouraged.
3441 ** ^In the "v2" interfaces, the prepared statement
3442 ** that is returned (the [sqlite3_stmt] object) contains a copy of the
3443 ** original SQL text. This causes the [sqlite3_step()] interface to
3444 ** behave differently in three ways:
3445 **
3446 ** <ol>
3447 ** <li>
3448 ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
3449 ** always used to do, [sqlite3_step()] will automatically recompile the SQL
3450 ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
3451 ** retries will occur before sqlite3_step() gives up and returns an error.
3452 ** </li>
3453 **
3454 ** <li>
3455 ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
3456 ** [error codes] or [extended error codes].  ^The legacy behavior was that
3457 ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
3458 ** and the application would have to make a second call to [sqlite3_reset()]
3459 ** in order to find the underlying cause of the problem. With the "v2" prepare
3460 ** interfaces, the underlying reason for the error is returned immediately.
3461 ** </li>
3462 **
3463 ** <li>
3464 ** ^If the specific value bound to [parameter | host parameter] in the 
3465 ** WHERE clause might influence the choice of query plan for a statement,
3466 ** then the statement will be automatically recompiled, as if there had been 
3467 ** a schema change, on the first  [sqlite3_step()] call following any change
3468 ** to the [sqlite3_bind_text | bindings] of that [parameter]. 
3469 ** ^The specific value of WHERE-clause [parameter] might influence the 
3470 ** choice of query plan if the parameter is the left-hand side of a [LIKE]
3471 ** or [GLOB] operator or if the parameter is compared to an indexed column
3472 ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
3473 ** </li>
3474 ** </ol>
3475 */
3476 SQLITE_API int SQLITE_STDCALL sqlite3_prepare(
3477   sqlite3 *db,            /* Database handle */
3478   const char *zSql,       /* SQL statement, UTF-8 encoded */
3479   int nByte,              /* Maximum length of zSql in bytes. */
3480   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3481   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3482 );
3483 SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2(
3484   sqlite3 *db,            /* Database handle */
3485   const char *zSql,       /* SQL statement, UTF-8 encoded */
3486   int nByte,              /* Maximum length of zSql in bytes. */
3487   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3488   const char **pzTail     /* OUT: Pointer to unused portion of zSql */
3489 );
3490 SQLITE_API int SQLITE_STDCALL sqlite3_prepare16(
3491   sqlite3 *db,            /* Database handle */
3492   const void *zSql,       /* SQL statement, UTF-16 encoded */
3493   int nByte,              /* Maximum length of zSql in bytes. */
3494   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3495   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3496 );
3497 SQLITE_API int SQLITE_STDCALL sqlite3_prepare16_v2(
3498   sqlite3 *db,            /* Database handle */
3499   const void *zSql,       /* SQL statement, UTF-16 encoded */
3500   int nByte,              /* Maximum length of zSql in bytes. */
3501   sqlite3_stmt **ppStmt,  /* OUT: Statement handle */
3502   const void **pzTail     /* OUT: Pointer to unused portion of zSql */
3503 );
3504
3505 /*
3506 ** CAPI3REF: Retrieving Statement SQL
3507 **
3508 ** ^This interface can be used to retrieve a saved copy of the original
3509 ** SQL text used to create a [prepared statement] if that statement was
3510 ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
3511 */
3512 SQLITE_API const char *SQLITE_STDCALL sqlite3_sql(sqlite3_stmt *pStmt);
3513
3514 /*
3515 ** CAPI3REF: Determine If An SQL Statement Writes The Database
3516 **
3517 ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
3518 ** and only if the [prepared statement] X makes no direct changes to
3519 ** the content of the database file.
3520 **
3521 ** Note that [application-defined SQL functions] or
3522 ** [virtual tables] might change the database indirectly as a side effect.  
3523 ** ^(For example, if an application defines a function "eval()" that 
3524 ** calls [sqlite3_exec()], then the following SQL statement would
3525 ** change the database file through side-effects:
3526 **
3527 ** <blockquote><pre>
3528 **    SELECT eval('DELETE FROM t1') FROM t2;
3529 ** </pre></blockquote>
3530 **
3531 ** But because the [SELECT] statement does not change the database file
3532 ** directly, sqlite3_stmt_readonly() would still return true.)^
3533 **
3534 ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
3535 ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
3536 ** since the statements themselves do not actually modify the database but
3537 ** rather they control the timing of when other statements modify the 
3538 ** database.  ^The [ATTACH] and [DETACH] statements also cause
3539 ** sqlite3_stmt_readonly() to return true since, while those statements
3540 ** change the configuration of a database connection, they do not make 
3541 ** changes to the content of the database files on disk.
3542 */
3543 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
3544
3545 /*
3546 ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
3547 **
3548 ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
3549 ** [prepared statement] S has been stepped at least once using 
3550 ** [sqlite3_step(S)] but has not run to completion and/or has not 
3551 ** been reset using [sqlite3_reset(S)].  ^The sqlite3_stmt_busy(S)
3552 ** interface returns false if S is a NULL pointer.  If S is not a 
3553 ** NULL pointer and is not a pointer to a valid [prepared statement]
3554 ** object, then the behavior is undefined and probably undesirable.
3555 **
3556 ** This interface can be used in combination [sqlite3_next_stmt()]
3557 ** to locate all prepared statements associated with a database 
3558 ** connection that are in need of being reset.  This can be used,
3559 ** for example, in diagnostic routines to search for prepared 
3560 ** statements that are holding a transaction open.
3561 */
3562 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_busy(sqlite3_stmt*);
3563
3564 /*
3565 ** CAPI3REF: Dynamically Typed Value Object
3566 ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
3567 **
3568 ** SQLite uses the sqlite3_value object to represent all values
3569 ** that can be stored in a database table. SQLite uses dynamic typing
3570 ** for the values it stores.  ^Values stored in sqlite3_value objects
3571 ** can be integers, floating point values, strings, BLOBs, or NULL.
3572 **
3573 ** An sqlite3_value object may be either "protected" or "unprotected".
3574 ** Some interfaces require a protected sqlite3_value.  Other interfaces
3575 ** will accept either a protected or an unprotected sqlite3_value.
3576 ** Every interface that accepts sqlite3_value arguments specifies
3577 ** whether or not it requires a protected sqlite3_value.
3578 **
3579 ** The terms "protected" and "unprotected" refer to whether or not
3580 ** a mutex is held.  An internal mutex is held for a protected
3581 ** sqlite3_value object but no mutex is held for an unprotected
3582 ** sqlite3_value object.  If SQLite is compiled to be single-threaded
3583 ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
3584 ** or if SQLite is run in one of reduced mutex modes 
3585 ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
3586 ** then there is no distinction between protected and unprotected
3587 ** sqlite3_value objects and they can be used interchangeably.  However,
3588 ** for maximum code portability it is recommended that applications
3589 ** still make the distinction between protected and unprotected
3590 ** sqlite3_value objects even when not strictly required.
3591 **
3592 ** ^The sqlite3_value objects that are passed as parameters into the
3593 ** implementation of [application-defined SQL functions] are protected.
3594 ** ^The sqlite3_value object returned by
3595 ** [sqlite3_column_value()] is unprotected.
3596 ** Unprotected sqlite3_value objects may only be used with
3597 ** [sqlite3_result_value()] and [sqlite3_bind_value()].
3598 ** The [sqlite3_value_blob | sqlite3_value_type()] family of
3599 ** interfaces require protected sqlite3_value objects.
3600 */
3601 typedef struct Mem sqlite3_value;
3602
3603 /*
3604 ** CAPI3REF: SQL Function Context Object
3605 **
3606 ** The context in which an SQL function executes is stored in an
3607 ** sqlite3_context object.  ^A pointer to an sqlite3_context object
3608 ** is always first parameter to [application-defined SQL functions].
3609 ** The application-defined SQL function implementation will pass this
3610 ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
3611 ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
3612 ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
3613 ** and/or [sqlite3_set_auxdata()].
3614 */
3615 typedef struct sqlite3_context sqlite3_context;
3616
3617 /*
3618 ** CAPI3REF: Binding Values To Prepared Statements
3619 ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
3620 ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
3621 **
3622 ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
3623 ** literals may be replaced by a [parameter] that matches one of following
3624 ** templates:
3625 **
3626 ** <ul>
3627 ** <li>  ?
3628 ** <li>  ?NNN
3629 ** <li>  :VVV
3630 ** <li>  @VVV
3631 ** <li>  $VVV
3632 ** </ul>
3633 **
3634 ** In the templates above, NNN represents an integer literal,
3635 ** and VVV represents an alphanumeric identifier.)^  ^The values of these
3636 ** parameters (also called "host parameter names" or "SQL parameters")
3637 ** can be set using the sqlite3_bind_*() routines defined here.
3638 **
3639 ** ^The first argument to the sqlite3_bind_*() routines is always
3640 ** a pointer to the [sqlite3_stmt] object returned from
3641 ** [sqlite3_prepare_v2()] or its variants.
3642 **
3643 ** ^The second argument is the index of the SQL parameter to be set.
3644 ** ^The leftmost SQL parameter has an index of 1.  ^When the same named
3645 ** SQL parameter is used more than once, second and subsequent
3646 ** occurrences have the same index as the first occurrence.
3647 ** ^The index for named parameters can be looked up using the
3648 ** [sqlite3_bind_parameter_index()] API if desired.  ^The index
3649 ** for "?NNN" parameters is the value of NNN.
3650 ** ^The NNN value must be between 1 and the [sqlite3_limit()]
3651 ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
3652 **
3653 ** ^The third argument is the value to bind to the parameter.
3654 ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3655 ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
3656 ** is ignored and the end result is the same as sqlite3_bind_null().
3657 **
3658 ** ^(In those routines that have a fourth argument, its value is the
3659 ** number of bytes in the parameter.  To be clear: the value is the
3660 ** number of <u>bytes</u> in the value, not the number of characters.)^
3661 ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
3662 ** is negative, then the length of the string is
3663 ** the number of bytes up to the first zero terminator.
3664 ** If the fourth parameter to sqlite3_bind_blob() is negative, then
3665 ** the behavior is undefined.
3666 ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
3667 ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
3668 ** that parameter must be the byte offset
3669 ** where the NUL terminator would occur assuming the string were NUL
3670 ** terminated.  If any NUL characters occur at byte offsets less than 
3671 ** the value of the fourth parameter then the resulting string value will
3672 ** contain embedded NULs.  The result of expressions involving strings
3673 ** with embedded NULs is undefined.
3674 **
3675 ** ^The fifth argument to the BLOB and string binding interfaces
3676 ** is a destructor used to dispose of the BLOB or
3677 ** string after SQLite has finished with it.  ^The destructor is called
3678 ** to dispose of the BLOB or string even if the call to bind API fails.
3679 ** ^If the fifth argument is
3680 ** the special value [SQLITE_STATIC], then SQLite assumes that the
3681 ** information is in static, unmanaged space and does not need to be freed.
3682 ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
3683 ** SQLite makes its own private copy of the data immediately, before
3684 ** the sqlite3_bind_*() routine returns.
3685 **
3686 ** ^The sixth argument to sqlite3_bind_text64() must be one of
3687 ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
3688 ** to specify the encoding of the text in the third parameter.  If
3689 ** the sixth argument to sqlite3_bind_text64() is not one of the
3690 ** allowed values shown above, or if the text encoding is different
3691 ** from the encoding specified by the sixth parameter, then the behavior
3692 ** is undefined.
3693 **
3694 ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
3695 ** is filled with zeroes.  ^A zeroblob uses a fixed amount of memory
3696 ** (just an integer to hold its size) while it is being processed.
3697 ** Zeroblobs are intended to serve as placeholders for BLOBs whose
3698 ** content is later written using
3699 ** [sqlite3_blob_open | incremental BLOB I/O] routines.
3700 ** ^A negative value for the zeroblob results in a zero-length BLOB.
3701 **
3702 ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
3703 ** for the [prepared statement] or with a prepared statement for which
3704 ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
3705 ** then the call will return [SQLITE_MISUSE].  If any sqlite3_bind_()
3706 ** routine is passed a [prepared statement] that has been finalized, the
3707 ** result is undefined and probably harmful.
3708 **
3709 ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
3710 ** ^Unbound parameters are interpreted as NULL.
3711 **
3712 ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
3713 ** [error code] if anything goes wrong.
3714 ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
3715 ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
3716 ** [SQLITE_MAX_LENGTH].
3717 ** ^[SQLITE_RANGE] is returned if the parameter
3718 ** index is out of range.  ^[SQLITE_NOMEM] is returned if malloc() fails.
3719 **
3720 ** See also: [sqlite3_bind_parameter_count()],
3721 ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
3722 */
3723 SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
3724 SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
3725                         void(*)(void*));
3726 SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt*, int, double);
3727 SQLITE_API int SQLITE_STDCALL sqlite3_bind_int(sqlite3_stmt*, int, int);
3728 SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
3729 SQLITE_API int SQLITE_STDCALL sqlite3_bind_null(sqlite3_stmt*, int);
3730 SQLITE_API int SQLITE_STDCALL sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
3731 SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
3732 SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
3733                          void(*)(void*), unsigned char encoding);
3734 SQLITE_API int SQLITE_STDCALL sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
3735 SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
3736
3737 /*
3738 ** CAPI3REF: Number Of SQL Parameters
3739 **
3740 ** ^This routine can be used to find the number of [SQL parameters]
3741 ** in a [prepared statement].  SQL parameters are tokens of the
3742 ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
3743 ** placeholders for values that are [sqlite3_bind_blob | bound]
3744 ** to the parameters at a later time.
3745 **
3746 ** ^(This routine actually returns the index of the largest (rightmost)
3747 ** parameter. For all forms except ?NNN, this will correspond to the
3748 ** number of unique parameters.  If parameters of the ?NNN form are used,
3749 ** there may be gaps in the list.)^
3750 **
3751 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3752 ** [sqlite3_bind_parameter_name()], and
3753 ** [sqlite3_bind_parameter_index()].
3754 */
3755 SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_count(sqlite3_stmt*);
3756
3757 /*
3758 ** CAPI3REF: Name Of A Host Parameter
3759 **
3760 ** ^The sqlite3_bind_parameter_name(P,N) interface returns
3761 ** the name of the N-th [SQL parameter] in the [prepared statement] P.
3762 ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
3763 ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
3764 ** respectively.
3765 ** In other words, the initial ":" or "$" or "@" or "?"
3766 ** is included as part of the name.)^
3767 ** ^Parameters of the form "?" without a following integer have no name
3768 ** and are referred to as "nameless" or "anonymous parameters".
3769 **
3770 ** ^The first host parameter has an index of 1, not 0.
3771 **
3772 ** ^If the value N is out of range or if the N-th parameter is
3773 ** nameless, then NULL is returned.  ^The returned string is
3774 ** always in UTF-8 encoding even if the named parameter was
3775 ** originally specified as UTF-16 in [sqlite3_prepare16()] or
3776 ** [sqlite3_prepare16_v2()].
3777 **
3778 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3779 ** [sqlite3_bind_parameter_count()], and
3780 ** [sqlite3_bind_parameter_index()].
3781 */
3782 SQLITE_API const char *SQLITE_STDCALL sqlite3_bind_parameter_name(sqlite3_stmt*, int);
3783
3784 /*
3785 ** CAPI3REF: Index Of A Parameter With A Given Name
3786 **
3787 ** ^Return the index of an SQL parameter given its name.  ^The
3788 ** index value returned is suitable for use as the second
3789 ** parameter to [sqlite3_bind_blob|sqlite3_bind()].  ^A zero
3790 ** is returned if no matching parameter is found.  ^The parameter
3791 ** name must be given in UTF-8 even if the original statement
3792 ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
3793 **
3794 ** See also: [sqlite3_bind_blob|sqlite3_bind()],
3795 ** [sqlite3_bind_parameter_count()], and
3796 ** [sqlite3_bind_parameter_index()].
3797 */
3798 SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
3799
3800 /*
3801 ** CAPI3REF: Reset All Bindings On A Prepared Statement
3802 **
3803 ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
3804 ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
3805 ** ^Use this routine to reset all host parameters to NULL.
3806 */
3807 SQLITE_API int SQLITE_STDCALL sqlite3_clear_bindings(sqlite3_stmt*);
3808
3809 /*
3810 ** CAPI3REF: Number Of Columns In A Result Set
3811 **
3812 ** ^Return the number of columns in the result set returned by the
3813 ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
3814 ** statement that does not return data (for example an [UPDATE]).
3815 **
3816 ** See also: [sqlite3_data_count()]
3817 */
3818 SQLITE_API int SQLITE_STDCALL sqlite3_column_count(sqlite3_stmt *pStmt);
3819
3820 /*
3821 ** CAPI3REF: Column Names In A Result Set
3822 **
3823 ** ^These routines return the name assigned to a particular column
3824 ** in the result set of a [SELECT] statement.  ^The sqlite3_column_name()
3825 ** interface returns a pointer to a zero-terminated UTF-8 string
3826 ** and sqlite3_column_name16() returns a pointer to a zero-terminated
3827 ** UTF-16 string.  ^The first parameter is the [prepared statement]
3828 ** that implements the [SELECT] statement. ^The second parameter is the
3829 ** column number.  ^The leftmost column is number 0.
3830 **
3831 ** ^The returned string pointer is valid until either the [prepared statement]
3832 ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
3833 ** reprepared by the first call to [sqlite3_step()] for a particular run
3834 ** or until the next call to
3835 ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
3836 **
3837 ** ^If sqlite3_malloc() fails during the processing of either routine
3838 ** (for example during a conversion from UTF-8 to UTF-16) then a
3839 ** NULL pointer is returned.
3840 **
3841 ** ^The name of a result column is the value of the "AS" clause for
3842 ** that column, if there is an AS clause.  If there is no AS clause
3843 ** then the name of the column is unspecified and may change from
3844 ** one release of SQLite to the next.
3845 */
3846 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_name(sqlite3_stmt*, int N);
3847 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_name16(sqlite3_stmt*, int N);
3848
3849 /*
3850 ** CAPI3REF: Source Of Data In A Query Result
3851 **
3852 ** ^These routines provide a means to determine the database, table, and
3853 ** table column that is the origin of a particular result column in
3854 ** [SELECT] statement.
3855 ** ^The name of the database or table or column can be returned as
3856 ** either a UTF-8 or UTF-16 string.  ^The _database_ routines return
3857 ** the database name, the _table_ routines return the table name, and
3858 ** the origin_ routines return the column name.
3859 ** ^The returned string is valid until the [prepared statement] is destroyed
3860 ** using [sqlite3_finalize()] or until the statement is automatically
3861 ** reprepared by the first call to [sqlite3_step()] for a particular run
3862 ** or until the same information is requested
3863 ** again in a different encoding.
3864 **
3865 ** ^The names returned are the original un-aliased names of the
3866 ** database, table, and column.
3867 **
3868 ** ^The first argument to these interfaces is a [prepared statement].
3869 ** ^These functions return information about the Nth result column returned by
3870 ** the statement, where N is the second function argument.
3871 ** ^The left-most column is column 0 for these routines.
3872 **
3873 ** ^If the Nth column returned by the statement is an expression or
3874 ** subquery and is not a column value, then all of these functions return
3875 ** NULL.  ^These routine might also return NULL if a memory allocation error
3876 ** occurs.  ^Otherwise, they return the name of the attached database, table,
3877 ** or column that query result column was extracted from.
3878 **
3879 ** ^As with all other SQLite APIs, those whose names end with "16" return
3880 ** UTF-16 encoded strings and the other functions return UTF-8.
3881 **
3882 ** ^These APIs are only available if the library was compiled with the
3883 ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
3884 **
3885 ** If two or more threads call one or more of these routines against the same
3886 ** prepared statement and column at the same time then the results are
3887 ** undefined.
3888 **
3889 ** If two or more threads call one or more
3890 ** [sqlite3_column_database_name | column metadata interfaces]
3891 ** for the same [prepared statement] and result column
3892 ** at the same time then the results are undefined.
3893 */
3894 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_database_name(sqlite3_stmt*,int);
3895 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_database_name16(sqlite3_stmt*,int);
3896 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_table_name(sqlite3_stmt*,int);
3897 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_table_name16(sqlite3_stmt*,int);
3898 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_origin_name(sqlite3_stmt*,int);
3899 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_origin_name16(sqlite3_stmt*,int);
3900
3901 /*
3902 ** CAPI3REF: Declared Datatype Of A Query Result
3903 **
3904 ** ^(The first parameter is a [prepared statement].
3905 ** If this statement is a [SELECT] statement and the Nth column of the
3906 ** returned result set of that [SELECT] is a table column (not an
3907 ** expression or subquery) then the declared type of the table
3908 ** column is returned.)^  ^If the Nth column of the result set is an
3909 ** expression or subquery, then a NULL pointer is returned.
3910 ** ^The returned string is always UTF-8 encoded.
3911 **
3912 ** ^(For example, given the database schema:
3913 **
3914 ** CREATE TABLE t1(c1 VARIANT);
3915 **
3916 ** and the following statement to be compiled:
3917 **
3918 ** SELECT c1 + 1, c1 FROM t1;
3919 **
3920 ** this routine would return the string "VARIANT" for the second result
3921 ** column (i==1), and a NULL pointer for the first result column (i==0).)^
3922 **
3923 ** ^SQLite uses dynamic run-time typing.  ^So just because a column
3924 ** is declared to contain a particular type does not mean that the
3925 ** data stored in that column is of the declared type.  SQLite is
3926 ** strongly typed, but the typing is dynamic not static.  ^Type
3927 ** is associated with individual values, not with the containers
3928 ** used to hold those values.
3929 */
3930 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_decltype(sqlite3_stmt*,int);
3931 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_decltype16(sqlite3_stmt*,int);
3932
3933 /*
3934 ** CAPI3REF: Evaluate An SQL Statement
3935 **
3936 ** After a [prepared statement] has been prepared using either
3937 ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
3938 ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
3939 ** must be called one or more times to evaluate the statement.
3940 **
3941 ** The details of the behavior of the sqlite3_step() interface depend
3942 ** on whether the statement was prepared using the newer "v2" interface
3943 ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
3944 ** interface [sqlite3_prepare()] and [sqlite3_prepare16()].  The use of the
3945 ** new "v2" interface is recommended for new applications but the legacy
3946 ** interface will continue to be supported.
3947 **
3948 ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
3949 ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
3950 ** ^With the "v2" interface, any of the other [result codes] or
3951 ** [extended result codes] might be returned as well.
3952 **
3953 ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
3954 ** database locks it needs to do its job.  ^If the statement is a [COMMIT]
3955 ** or occurs outside of an explicit transaction, then you can retry the
3956 ** statement.  If the statement is not a [COMMIT] and occurs within an
3957 ** explicit transaction then you should rollback the transaction before
3958 ** continuing.
3959 **
3960 ** ^[SQLITE_DONE] means that the statement has finished executing
3961 ** successfully.  sqlite3_step() should not be called again on this virtual
3962 ** machine without first calling [sqlite3_reset()] to reset the virtual
3963 ** machine back to its initial state.
3964 **
3965 ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
3966 ** is returned each time a new row of data is ready for processing by the
3967 ** caller. The values may be accessed using the [column access functions].
3968 ** sqlite3_step() is called again to retrieve the next row of data.
3969 **
3970 ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
3971 ** violation) has occurred.  sqlite3_step() should not be called again on
3972 ** the VM. More information may be found by calling [sqlite3_errmsg()].
3973 ** ^With the legacy interface, a more specific error code (for example,
3974 ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
3975 ** can be obtained by calling [sqlite3_reset()] on the
3976 ** [prepared statement].  ^In the "v2" interface,
3977 ** the more specific error code is returned directly by sqlite3_step().
3978 **
3979 ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
3980 ** Perhaps it was called on a [prepared statement] that has
3981 ** already been [sqlite3_finalize | finalized] or on one that had
3982 ** previously returned [SQLITE_ERROR] or [SQLITE_DONE].  Or it could
3983 ** be the case that the same database connection is being used by two or
3984 ** more threads at the same moment in time.
3985 **
3986 ** For all versions of SQLite up to and including 3.6.23.1, a call to
3987 ** [sqlite3_reset()] was required after sqlite3_step() returned anything
3988 ** other than [SQLITE_ROW] before any subsequent invocation of
3989 ** sqlite3_step().  Failure to reset the prepared statement using 
3990 ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
3991 ** sqlite3_step().  But after version 3.6.23.1, sqlite3_step() began
3992 ** calling [sqlite3_reset()] automatically in this circumstance rather
3993 ** than returning [SQLITE_MISUSE].  This is not considered a compatibility
3994 ** break because any application that ever receives an SQLITE_MISUSE error
3995 ** is broken by definition.  The [SQLITE_OMIT_AUTORESET] compile-time option
3996 ** can be used to restore the legacy behavior.
3997 **
3998 ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
3999 ** API always returns a generic error code, [SQLITE_ERROR], following any
4000 ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE].  You must call
4001 ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
4002 ** specific [error codes] that better describes the error.
4003 ** We admit that this is a goofy design.  The problem has been fixed
4004 ** with the "v2" interface.  If you prepare all of your SQL statements
4005 ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
4006 ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
4007 ** then the more specific [error codes] are returned directly
4008 ** by sqlite3_step().  The use of the "v2" interface is recommended.
4009 */
4010 SQLITE_API int SQLITE_STDCALL sqlite3_step(sqlite3_stmt*);
4011
4012 /*
4013 ** CAPI3REF: Number of columns in a result set
4014 **
4015 ** ^The sqlite3_data_count(P) interface returns the number of columns in the
4016 ** current row of the result set of [prepared statement] P.
4017 ** ^If prepared statement P does not have results ready to return
4018 ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
4019 ** interfaces) then sqlite3_data_count(P) returns 0.
4020 ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
4021 ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
4022 ** [sqlite3_step](P) returned [SQLITE_DONE].  ^The sqlite3_data_count(P)
4023 ** will return non-zero if previous call to [sqlite3_step](P) returned
4024 ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
4025 ** where it always returns zero since each step of that multi-step
4026 ** pragma returns 0 columns of data.
4027 **
4028 ** See also: [sqlite3_column_count()]
4029 */
4030 SQLITE_API int SQLITE_STDCALL sqlite3_data_count(sqlite3_stmt *pStmt);
4031
4032 /*
4033 ** CAPI3REF: Fundamental Datatypes
4034 ** KEYWORDS: SQLITE_TEXT
4035 **
4036 ** ^(Every value in SQLite has one of five fundamental datatypes:
4037 **
4038 ** <ul>
4039 ** <li> 64-bit signed integer
4040 ** <li> 64-bit IEEE floating point number
4041 ** <li> string
4042 ** <li> BLOB
4043 ** <li> NULL
4044 ** </ul>)^
4045 **
4046 ** These constants are codes for each of those types.
4047 **
4048 ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
4049 ** for a completely different meaning.  Software that links against both
4050 ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
4051 ** SQLITE_TEXT.
4052 */
4053 #define SQLITE_INTEGER  1
4054 #define SQLITE_FLOAT    2
4055 #define SQLITE_BLOB     4
4056 #define SQLITE_NULL     5
4057 #ifdef SQLITE_TEXT
4058 # undef SQLITE_TEXT
4059 #else
4060 # define SQLITE_TEXT     3
4061 #endif
4062 #define SQLITE3_TEXT     3
4063
4064 /*
4065 ** CAPI3REF: Result Values From A Query
4066 ** KEYWORDS: {column access functions}
4067 **
4068 ** These routines form the "result set" interface.
4069 **
4070 ** ^These routines return information about a single column of the current
4071 ** result row of a query.  ^In every case the first argument is a pointer
4072 ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
4073 ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
4074 ** and the second argument is the index of the column for which information
4075 ** should be returned. ^The leftmost column of the result set has the index 0.
4076 ** ^The number of columns in the result can be determined using
4077 ** [sqlite3_column_count()].
4078 **
4079 ** If the SQL statement does not currently point to a valid row, or if the
4080 ** column index is out of range, the result is undefined.
4081 ** These routines may only be called when the most recent call to
4082 ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
4083 ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
4084 ** If any of these routines are called after [sqlite3_reset()] or
4085 ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
4086 ** something other than [SQLITE_ROW], the results are undefined.
4087 ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
4088 ** are called from a different thread while any of these routines
4089 ** are pending, then the results are undefined.
4090 **
4091 ** ^The sqlite3_column_type() routine returns the
4092 ** [SQLITE_INTEGER | datatype code] for the initial data type
4093 ** of the result column.  ^The returned value is one of [SQLITE_INTEGER],
4094 ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL].  The value
4095 ** returned by sqlite3_column_type() is only meaningful if no type
4096 ** conversions have occurred as described below.  After a type conversion,
4097 ** the value returned by sqlite3_column_type() is undefined.  Future
4098 ** versions of SQLite may change the behavior of sqlite3_column_type()
4099 ** following a type conversion.
4100 **
4101 ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
4102 ** routine returns the number of bytes in that BLOB or string.
4103 ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
4104 ** the string to UTF-8 and then returns the number of bytes.
4105 ** ^If the result is a numeric value then sqlite3_column_bytes() uses
4106 ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
4107 ** the number of bytes in that string.
4108 ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
4109 **
4110 ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
4111 ** routine returns the number of bytes in that BLOB or string.
4112 ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
4113 ** the string to UTF-16 and then returns the number of bytes.
4114 ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
4115 ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
4116 ** the number of bytes in that string.
4117 ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
4118 **
4119 ** ^The values returned by [sqlite3_column_bytes()] and 
4120 ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
4121 ** of the string.  ^For clarity: the values returned by
4122 ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
4123 ** bytes in the string, not the number of characters.
4124 **
4125 ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
4126 ** even empty strings, are always zero-terminated.  ^The return
4127 ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
4128 **
4129 ** ^The object returned by [sqlite3_column_value()] is an
4130 ** [unprotected sqlite3_value] object.  An unprotected sqlite3_value object
4131 ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
4132 ** If the [unprotected sqlite3_value] object returned by
4133 ** [sqlite3_column_value()] is used in any other way, including calls
4134 ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
4135 ** or [sqlite3_value_bytes()], then the behavior is undefined.
4136 **
4137 ** These routines attempt to convert the value where appropriate.  ^For
4138 ** example, if the internal representation is FLOAT and a text result
4139 ** is requested, [sqlite3_snprintf()] is used internally to perform the
4140 ** conversion automatically.  ^(The following table details the conversions
4141 ** that are applied:
4142 **
4143 ** <blockquote>
4144 ** <table border="1">
4145 ** <tr><th> Internal<br>Type <th> Requested<br>Type <th>  Conversion
4146 **
4147 ** <tr><td>  NULL    <td> INTEGER   <td> Result is 0
4148 ** <tr><td>  NULL    <td>  FLOAT    <td> Result is 0.0
4149 ** <tr><td>  NULL    <td>   TEXT    <td> Result is a NULL pointer
4150 ** <tr><td>  NULL    <td>   BLOB    <td> Result is a NULL pointer
4151 ** <tr><td> INTEGER  <td>  FLOAT    <td> Convert from integer to float
4152 ** <tr><td> INTEGER  <td>   TEXT    <td> ASCII rendering of the integer
4153 ** <tr><td> INTEGER  <td>   BLOB    <td> Same as INTEGER->TEXT
4154 ** <tr><td>  FLOAT   <td> INTEGER   <td> [CAST] to INTEGER
4155 ** <tr><td>  FLOAT   <td>   TEXT    <td> ASCII rendering of the float
4156 ** <tr><td>  FLOAT   <td>   BLOB    <td> [CAST] to BLOB
4157 ** <tr><td>  TEXT    <td> INTEGER   <td> [CAST] to INTEGER
4158 ** <tr><td>  TEXT    <td>  FLOAT    <td> [CAST] to REAL
4159 ** <tr><td>  TEXT    <td>   BLOB    <td> No change
4160 ** <tr><td>  BLOB    <td> INTEGER   <td> [CAST] to INTEGER
4161 ** <tr><td>  BLOB    <td>  FLOAT    <td> [CAST] to REAL
4162 ** <tr><td>  BLOB    <td>   TEXT    <td> Add a zero terminator if needed
4163 ** </table>
4164 ** </blockquote>)^
4165 **
4166 ** The table above makes reference to standard C library functions atoi()
4167 ** and atof().  SQLite does not really use these functions.  It has its
4168 ** own equivalent internal routines.  The atoi() and atof() names are
4169 ** used in the table for brevity and because they are familiar to most
4170 ** C programmers.
4171 **
4172 ** Note that when type conversions occur, pointers returned by prior
4173 ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
4174 ** sqlite3_column_text16() may be invalidated.
4175 ** Type conversions and pointer invalidations might occur
4176 ** in the following cases:
4177 **
4178 ** <ul>
4179 ** <li> The initial content is a BLOB and sqlite3_column_text() or
4180 **      sqlite3_column_text16() is called.  A zero-terminator might
4181 **      need to be added to the string.</li>
4182 ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
4183 **      sqlite3_column_text16() is called.  The content must be converted
4184 **      to UTF-16.</li>
4185 ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
4186 **      sqlite3_column_text() is called.  The content must be converted
4187 **      to UTF-8.</li>
4188 ** </ul>
4189 **
4190 ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
4191 ** not invalidate a prior pointer, though of course the content of the buffer
4192 ** that the prior pointer references will have been modified.  Other kinds
4193 ** of conversion are done in place when it is possible, but sometimes they
4194 ** are not possible and in those cases prior pointers are invalidated.
4195 **
4196 ** The safest and easiest to remember policy is to invoke these routines
4197 ** in one of the following ways:
4198 **
4199 ** <ul>
4200 **  <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
4201 **  <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
4202 **  <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
4203 ** </ul>
4204 **
4205 ** In other words, you should call sqlite3_column_text(),
4206 ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
4207 ** into the desired format, then invoke sqlite3_column_bytes() or
4208 ** sqlite3_column_bytes16() to find the size of the result.  Do not mix calls
4209 ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
4210 ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
4211 ** with calls to sqlite3_column_bytes().
4212 **
4213 ** ^The pointers returned are valid until a type conversion occurs as
4214 ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
4215 ** [sqlite3_finalize()] is called.  ^The memory space used to hold strings
4216 ** and BLOBs is freed automatically.  Do <b>not</b> pass the pointers returned
4217 ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
4218 ** [sqlite3_free()].
4219 **
4220 ** ^(If a memory allocation error occurs during the evaluation of any
4221 ** of these routines, a default value is returned.  The default value
4222 ** is either the integer 0, the floating point number 0.0, or a NULL
4223 ** pointer.  Subsequent calls to [sqlite3_errcode()] will return
4224 ** [SQLITE_NOMEM].)^
4225 */
4226 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_blob(sqlite3_stmt*, int iCol);
4227 SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes(sqlite3_stmt*, int iCol);
4228 SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
4229 SQLITE_API double SQLITE_STDCALL sqlite3_column_double(sqlite3_stmt*, int iCol);
4230 SQLITE_API int SQLITE_STDCALL sqlite3_column_int(sqlite3_stmt*, int iCol);
4231 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_column_int64(sqlite3_stmt*, int iCol);
4232 SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt*, int iCol);
4233 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_text16(sqlite3_stmt*, int iCol);
4234 SQLITE_API int SQLITE_STDCALL sqlite3_column_type(sqlite3_stmt*, int iCol);
4235 SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_column_value(sqlite3_stmt*, int iCol);
4236
4237 /*
4238 ** CAPI3REF: Destroy A Prepared Statement Object
4239 **
4240 ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
4241 ** ^If the most recent evaluation of the statement encountered no errors
4242 ** or if the statement is never been evaluated, then sqlite3_finalize() returns
4243 ** SQLITE_OK.  ^If the most recent evaluation of statement S failed, then
4244 ** sqlite3_finalize(S) returns the appropriate [error code] or
4245 ** [extended error code].
4246 **
4247 ** ^The sqlite3_finalize(S) routine can be called at any point during
4248 ** the life cycle of [prepared statement] S:
4249 ** before statement S is ever evaluated, after
4250 ** one or more calls to [sqlite3_reset()], or after any call
4251 ** to [sqlite3_step()] regardless of whether or not the statement has
4252 ** completed execution.
4253 **
4254 ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
4255 **
4256 ** The application must finalize every [prepared statement] in order to avoid
4257 ** resource leaks.  It is a grievous error for the application to try to use
4258 ** a prepared statement after it has been finalized.  Any use of a prepared
4259 ** statement after it has been finalized can result in undefined and
4260 ** undesirable behavior such as segfaults and heap corruption.
4261 */
4262 SQLITE_API int SQLITE_STDCALL sqlite3_finalize(sqlite3_stmt *pStmt);
4263
4264 /*
4265 ** CAPI3REF: Reset A Prepared Statement Object
4266 **
4267 ** The sqlite3_reset() function is called to reset a [prepared statement]
4268 ** object back to its initial state, ready to be re-executed.
4269 ** ^Any SQL statement variables that had values bound to them using
4270 ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
4271 ** Use [sqlite3_clear_bindings()] to reset the bindings.
4272 **
4273 ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
4274 ** back to the beginning of its program.
4275 **
4276 ** ^If the most recent call to [sqlite3_step(S)] for the
4277 ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
4278 ** or if [sqlite3_step(S)] has never before been called on S,
4279 ** then [sqlite3_reset(S)] returns [SQLITE_OK].
4280 **
4281 ** ^If the most recent call to [sqlite3_step(S)] for the
4282 ** [prepared statement] S indicated an error, then
4283 ** [sqlite3_reset(S)] returns an appropriate [error code].
4284 **
4285 ** ^The [sqlite3_reset(S)] interface does not change the values
4286 ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
4287 */
4288 SQLITE_API int SQLITE_STDCALL sqlite3_reset(sqlite3_stmt *pStmt);
4289
4290 /*
4291 ** CAPI3REF: Create Or Redefine SQL Functions
4292 ** KEYWORDS: {function creation routines}
4293 ** KEYWORDS: {application-defined SQL function}
4294 ** KEYWORDS: {application-defined SQL functions}
4295 **
4296 ** ^These functions (collectively known as "function creation routines")
4297 ** are used to add SQL functions or aggregates or to redefine the behavior
4298 ** of existing SQL functions or aggregates.  The only differences between
4299 ** these routines are the text encoding expected for
4300 ** the second parameter (the name of the function being created)
4301 ** and the presence or absence of a destructor callback for
4302 ** the application data pointer.
4303 **
4304 ** ^The first parameter is the [database connection] to which the SQL
4305 ** function is to be added.  ^If an application uses more than one database
4306 ** connection then application-defined SQL functions must be added
4307 ** to each database connection separately.
4308 **
4309 ** ^The second parameter is the name of the SQL function to be created or
4310 ** redefined.  ^The length of the name is limited to 255 bytes in a UTF-8
4311 ** representation, exclusive of the zero-terminator.  ^Note that the name
4312 ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.  
4313 ** ^Any attempt to create a function with a longer name
4314 ** will result in [SQLITE_MISUSE] being returned.
4315 **
4316 ** ^The third parameter (nArg)
4317 ** is the number of arguments that the SQL function or
4318 ** aggregate takes. ^If this parameter is -1, then the SQL function or
4319 ** aggregate may take any number of arguments between 0 and the limit
4320 ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]).  If the third
4321 ** parameter is less than -1 or greater than 127 then the behavior is
4322 ** undefined.
4323 **
4324 ** ^The fourth parameter, eTextRep, specifies what
4325 ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
4326 ** its parameters.  The application should set this parameter to
4327 ** [SQLITE_UTF16LE] if the function implementation invokes 
4328 ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
4329 ** implementation invokes [sqlite3_value_text16be()] on an input, or
4330 ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
4331 ** otherwise.  ^The same SQL function may be registered multiple times using
4332 ** different preferred text encodings, with different implementations for
4333 ** each encoding.
4334 ** ^When multiple implementations of the same function are available, SQLite
4335 ** will pick the one that involves the least amount of data conversion.
4336 **
4337 ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
4338 ** to signal that the function will always return the same result given
4339 ** the same inputs within a single SQL statement.  Most SQL functions are
4340 ** deterministic.  The built-in [random()] SQL function is an example of a
4341 ** function that is not deterministic.  The SQLite query planner is able to
4342 ** perform additional optimizations on deterministic functions, so use
4343 ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
4344 **
4345 ** ^(The fifth parameter is an arbitrary pointer.  The implementation of the
4346 ** function can gain access to this pointer using [sqlite3_user_data()].)^
4347 **
4348 ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
4349 ** pointers to C-language functions that implement the SQL function or
4350 ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
4351 ** callback only; NULL pointers must be passed as the xStep and xFinal
4352 ** parameters. ^An aggregate SQL function requires an implementation of xStep
4353 ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
4354 ** SQL function or aggregate, pass NULL pointers for all three function
4355 ** callbacks.
4356 **
4357 ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
4358 ** then it is destructor for the application data pointer. 
4359 ** The destructor is invoked when the function is deleted, either by being
4360 ** overloaded or when the database connection closes.)^
4361 ** ^The destructor is also invoked if the call to
4362 ** sqlite3_create_function_v2() fails.
4363 ** ^When the destructor callback of the tenth parameter is invoked, it
4364 ** is passed a single argument which is a copy of the application data 
4365 ** pointer which was the fifth parameter to sqlite3_create_function_v2().
4366 **
4367 ** ^It is permitted to register multiple implementations of the same
4368 ** functions with the same name but with either differing numbers of
4369 ** arguments or differing preferred text encodings.  ^SQLite will use
4370 ** the implementation that most closely matches the way in which the
4371 ** SQL function is used.  ^A function implementation with a non-negative
4372 ** nArg parameter is a better match than a function implementation with
4373 ** a negative nArg.  ^A function where the preferred text encoding
4374 ** matches the database encoding is a better
4375 ** match than a function where the encoding is different.  
4376 ** ^A function where the encoding difference is between UTF16le and UTF16be
4377 ** is a closer match than a function where the encoding difference is
4378 ** between UTF8 and UTF16.
4379 **
4380 ** ^Built-in functions may be overloaded by new application-defined functions.
4381 **
4382 ** ^An application-defined function is permitted to call other
4383 ** SQLite interfaces.  However, such calls must not
4384 ** close the database connection nor finalize or reset the prepared
4385 ** statement in which the function is running.
4386 */
4387 SQLITE_API int SQLITE_STDCALL sqlite3_create_function(
4388   sqlite3 *db,
4389   const char *zFunctionName,
4390   int nArg,
4391   int eTextRep,
4392   void *pApp,
4393   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4394   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4395   void (*xFinal)(sqlite3_context*)
4396 );
4397 SQLITE_API int SQLITE_STDCALL sqlite3_create_function16(
4398   sqlite3 *db,
4399   const void *zFunctionName,
4400   int nArg,
4401   int eTextRep,
4402   void *pApp,
4403   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4404   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4405   void (*xFinal)(sqlite3_context*)
4406 );
4407 SQLITE_API int SQLITE_STDCALL sqlite3_create_function_v2(
4408   sqlite3 *db,
4409   const char *zFunctionName,
4410   int nArg,
4411   int eTextRep,
4412   void *pApp,
4413   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
4414   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
4415   void (*xFinal)(sqlite3_context*),
4416   void(*xDestroy)(void*)
4417 );
4418
4419 /*
4420 ** CAPI3REF: Text Encodings
4421 **
4422 ** These constant define integer codes that represent the various
4423 ** text encodings supported by SQLite.
4424 */
4425 #define SQLITE_UTF8           1    /* IMP: R-37514-35566 */
4426 #define SQLITE_UTF16LE        2    /* IMP: R-03371-37637 */
4427 #define SQLITE_UTF16BE        3    /* IMP: R-51971-34154 */
4428 #define SQLITE_UTF16          4    /* Use native byte order */
4429 #define SQLITE_ANY            5    /* Deprecated */
4430 #define SQLITE_UTF16_ALIGNED  8    /* sqlite3_create_collation only */
4431
4432 /*
4433 ** CAPI3REF: Function Flags
4434 **
4435 ** These constants may be ORed together with the 
4436 ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
4437 ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
4438 ** [sqlite3_create_function_v2()].
4439 */
4440 #define SQLITE_DETERMINISTIC    0x800
4441
4442 /*
4443 ** CAPI3REF: Deprecated Functions
4444 ** DEPRECATED
4445 **
4446 ** These functions are [deprecated].  In order to maintain
4447 ** backwards compatibility with older code, these functions continue 
4448 ** to be supported.  However, new applications should avoid
4449 ** the use of these functions.  To encourage programmers to avoid
4450 ** these functions, we will not explain what they do.
4451 */
4452 #ifndef SQLITE_OMIT_DEPRECATED
4453 SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_aggregate_count(sqlite3_context*);
4454 SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_expired(sqlite3_stmt*);
4455 SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
4456 SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_global_recover(void);
4457 SQLITE_API SQLITE_DEPRECATED void SQLITE_STDCALL sqlite3_thread_cleanup(void);
4458 SQLITE_API SQLITE_DEPRECATED int SQLITE_STDCALL sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
4459                       void*,sqlite3_int64);
4460 #endif
4461
4462 /*
4463 ** CAPI3REF: Obtaining SQL Function Parameter Values
4464 **
4465 ** The C-language implementation of SQL functions and aggregates uses
4466 ** this set of interface routines to access the parameter values on
4467 ** the function or aggregate.
4468 **
4469 ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
4470 ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
4471 ** define callbacks that implement the SQL functions and aggregates.
4472 ** The 3rd parameter to these callbacks is an array of pointers to
4473 ** [protected sqlite3_value] objects.  There is one [sqlite3_value] object for
4474 ** each parameter to the SQL function.  These routines are used to
4475 ** extract values from the [sqlite3_value] objects.
4476 **
4477 ** These routines work only with [protected sqlite3_value] objects.
4478 ** Any attempt to use these routines on an [unprotected sqlite3_value]
4479 ** object results in undefined behavior.
4480 **
4481 ** ^These routines work just like the corresponding [column access functions]
4482 ** except that these routines take a single [protected sqlite3_value] object
4483 ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
4484 **
4485 ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
4486 ** in the native byte-order of the host machine.  ^The
4487 ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
4488 ** extract UTF-16 strings as big-endian and little-endian respectively.
4489 **
4490 ** ^(The sqlite3_value_numeric_type() interface attempts to apply
4491 ** numeric affinity to the value.  This means that an attempt is
4492 ** made to convert the value to an integer or floating point.  If
4493 ** such a conversion is possible without loss of information (in other
4494 ** words, if the value is a string that looks like a number)
4495 ** then the conversion is performed.  Otherwise no conversion occurs.
4496 ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
4497 **
4498 ** Please pay particular attention to the fact that the pointer returned
4499 ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
4500 ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
4501 ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
4502 ** or [sqlite3_value_text16()].
4503 **
4504 ** These routines must be called from the same thread as
4505 ** the SQL function that supplied the [sqlite3_value*] parameters.
4506 */
4507 SQLITE_API const void *SQLITE_STDCALL sqlite3_value_blob(sqlite3_value*);
4508 SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes(sqlite3_value*);
4509 SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes16(sqlite3_value*);
4510 SQLITE_API double SQLITE_STDCALL sqlite3_value_double(sqlite3_value*);
4511 SQLITE_API int SQLITE_STDCALL sqlite3_value_int(sqlite3_value*);
4512 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_value_int64(sqlite3_value*);
4513 SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_value_text(sqlite3_value*);
4514 SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16(sqlite3_value*);
4515 SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16le(sqlite3_value*);
4516 SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16be(sqlite3_value*);
4517 SQLITE_API int SQLITE_STDCALL sqlite3_value_type(sqlite3_value*);
4518 SQLITE_API int SQLITE_STDCALL sqlite3_value_numeric_type(sqlite3_value*);
4519
4520 /*
4521 ** CAPI3REF: Obtain Aggregate Function Context
4522 **
4523 ** Implementations of aggregate SQL functions use this
4524 ** routine to allocate memory for storing their state.
4525 **
4526 ** ^The first time the sqlite3_aggregate_context(C,N) routine is called 
4527 ** for a particular aggregate function, SQLite
4528 ** allocates N of memory, zeroes out that memory, and returns a pointer
4529 ** to the new memory. ^On second and subsequent calls to
4530 ** sqlite3_aggregate_context() for the same aggregate function instance,
4531 ** the same buffer is returned.  Sqlite3_aggregate_context() is normally
4532 ** called once for each invocation of the xStep callback and then one
4533 ** last time when the xFinal callback is invoked.  ^(When no rows match
4534 ** an aggregate query, the xStep() callback of the aggregate function
4535 ** implementation is never called and xFinal() is called exactly once.
4536 ** In those cases, sqlite3_aggregate_context() might be called for the
4537 ** first time from within xFinal().)^
4538 **
4539 ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer 
4540 ** when first called if N is less than or equal to zero or if a memory
4541 ** allocate error occurs.
4542 **
4543 ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
4544 ** determined by the N parameter on first successful call.  Changing the
4545 ** value of N in subsequent call to sqlite3_aggregate_context() within
4546 ** the same aggregate function instance will not resize the memory
4547 ** allocation.)^  Within the xFinal callback, it is customary to set
4548 ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no 
4549 ** pointless memory allocations occur.
4550 **
4551 ** ^SQLite automatically frees the memory allocated by 
4552 ** sqlite3_aggregate_context() when the aggregate query concludes.
4553 **
4554 ** The first parameter must be a copy of the
4555 ** [sqlite3_context | SQL function context] that is the first parameter
4556 ** to the xStep or xFinal callback routine that implements the aggregate
4557 ** function.
4558 **
4559 ** This routine must be called from the same thread in which
4560 ** the aggregate SQL function is running.
4561 */
4562 SQLITE_API void *SQLITE_STDCALL sqlite3_aggregate_context(sqlite3_context*, int nBytes);
4563
4564 /*
4565 ** CAPI3REF: User Data For Functions
4566 **
4567 ** ^The sqlite3_user_data() interface returns a copy of
4568 ** the pointer that was the pUserData parameter (the 5th parameter)
4569 ** of the [sqlite3_create_function()]
4570 ** and [sqlite3_create_function16()] routines that originally
4571 ** registered the application defined function.
4572 **
4573 ** This routine must be called from the same thread in which
4574 ** the application-defined function is running.
4575 */
4576 SQLITE_API void *SQLITE_STDCALL sqlite3_user_data(sqlite3_context*);
4577
4578 /*
4579 ** CAPI3REF: Database Connection For Functions
4580 **
4581 ** ^The sqlite3_context_db_handle() interface returns a copy of
4582 ** the pointer to the [database connection] (the 1st parameter)
4583 ** of the [sqlite3_create_function()]
4584 ** and [sqlite3_create_function16()] routines that originally
4585 ** registered the application defined function.
4586 */
4587 SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_context_db_handle(sqlite3_context*);
4588
4589 /*
4590 ** CAPI3REF: Function Auxiliary Data
4591 **
4592 ** These functions may be used by (non-aggregate) SQL functions to
4593 ** associate metadata with argument values. If the same value is passed to
4594 ** multiple invocations of the same SQL function during query execution, under
4595 ** some circumstances the associated metadata may be preserved.  An example
4596 ** of where this might be useful is in a regular-expression matching
4597 ** function. The compiled version of the regular expression can be stored as
4598 ** metadata associated with the pattern string.  
4599 ** Then as long as the pattern string remains the same,
4600 ** the compiled regular expression can be reused on multiple
4601 ** invocations of the same function.
4602 **
4603 ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
4604 ** associated by the sqlite3_set_auxdata() function with the Nth argument
4605 ** value to the application-defined function. ^If there is no metadata
4606 ** associated with the function argument, this sqlite3_get_auxdata() interface
4607 ** returns a NULL pointer.
4608 **
4609 ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
4610 ** argument of the application-defined function.  ^Subsequent
4611 ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
4612 ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
4613 ** NULL if the metadata has been discarded.
4614 ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
4615 ** SQLite will invoke the destructor function X with parameter P exactly
4616 ** once, when the metadata is discarded.
4617 ** SQLite is free to discard the metadata at any time, including: <ul>
4618 ** <li> when the corresponding function parameter changes, or
4619 ** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
4620 **      SQL statement, or
4621 ** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
4622 ** <li> during the original sqlite3_set_auxdata() call when a memory 
4623 **      allocation error occurs. </ul>)^
4624 **
4625 ** Note the last bullet in particular.  The destructor X in 
4626 ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
4627 ** sqlite3_set_auxdata() interface even returns.  Hence sqlite3_set_auxdata()
4628 ** should be called near the end of the function implementation and the
4629 ** function implementation should not make any use of P after
4630 ** sqlite3_set_auxdata() has been called.
4631 **
4632 ** ^(In practice, metadata is preserved between function calls for
4633 ** function parameters that are compile-time constants, including literal
4634 ** values and [parameters] and expressions composed from the same.)^
4635 **
4636 ** These routines must be called from the same thread in which
4637 ** the SQL function is running.
4638 */
4639 SQLITE_API void *SQLITE_STDCALL sqlite3_get_auxdata(sqlite3_context*, int N);
4640 SQLITE_API void SQLITE_STDCALL sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
4641
4642
4643 /*
4644 ** CAPI3REF: Constants Defining Special Destructor Behavior
4645 **
4646 ** These are special values for the destructor that is passed in as the
4647 ** final argument to routines like [sqlite3_result_blob()].  ^If the destructor
4648 ** argument is SQLITE_STATIC, it means that the content pointer is constant
4649 ** and will never change.  It does not need to be destroyed.  ^The
4650 ** SQLITE_TRANSIENT value means that the content will likely change in
4651 ** the near future and that SQLite should make its own private copy of
4652 ** the content before returning.
4653 **
4654 ** The typedef is necessary to work around problems in certain
4655 ** C++ compilers.
4656 */
4657 typedef void (*sqlite3_destructor_type)(void*);
4658 #define SQLITE_STATIC      ((sqlite3_destructor_type)0)
4659 #define SQLITE_TRANSIENT   ((sqlite3_destructor_type)-1)
4660
4661 /*
4662 ** CAPI3REF: Setting The Result Of An SQL Function
4663 **
4664 ** These routines are used by the xFunc or xFinal callbacks that
4665 ** implement SQL functions and aggregates.  See
4666 ** [sqlite3_create_function()] and [sqlite3_create_function16()]
4667 ** for additional information.
4668 **
4669 ** These functions work very much like the [parameter binding] family of
4670 ** functions used to bind values to host parameters in prepared statements.
4671 ** Refer to the [SQL parameter] documentation for additional information.
4672 **
4673 ** ^The sqlite3_result_blob() interface sets the result from
4674 ** an application-defined function to be the BLOB whose content is pointed
4675 ** to by the second parameter and which is N bytes long where N is the
4676 ** third parameter.
4677 **
4678 ** ^The sqlite3_result_zeroblob() interfaces set the result of
4679 ** the application-defined function to be a BLOB containing all zero
4680 ** bytes and N bytes in size, where N is the value of the 2nd parameter.
4681 **
4682 ** ^The sqlite3_result_double() interface sets the result from
4683 ** an application-defined function to be a floating point value specified
4684 ** by its 2nd argument.
4685 **
4686 ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
4687 ** cause the implemented SQL function to throw an exception.
4688 ** ^SQLite uses the string pointed to by the
4689 ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
4690 ** as the text of an error message.  ^SQLite interprets the error
4691 ** message string from sqlite3_result_error() as UTF-8. ^SQLite
4692 ** interprets the string from sqlite3_result_error16() as UTF-16 in native
4693 ** byte order.  ^If the third parameter to sqlite3_result_error()
4694 ** or sqlite3_result_error16() is negative then SQLite takes as the error
4695 ** message all text up through the first zero character.
4696 ** ^If the third parameter to sqlite3_result_error() or
4697 ** sqlite3_result_error16() is non-negative then SQLite takes that many
4698 ** bytes (not characters) from the 2nd parameter as the error message.
4699 ** ^The sqlite3_result_error() and sqlite3_result_error16()
4700 ** routines make a private copy of the error message text before
4701 ** they return.  Hence, the calling function can deallocate or
4702 ** modify the text after they return without harm.
4703 ** ^The sqlite3_result_error_code() function changes the error code
4704 ** returned by SQLite as a result of an error in a function.  ^By default,
4705 ** the error code is SQLITE_ERROR.  ^A subsequent call to sqlite3_result_error()
4706 ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
4707 **
4708 ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
4709 ** error indicating that a string or BLOB is too long to represent.
4710 **
4711 ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
4712 ** error indicating that a memory allocation failed.
4713 **
4714 ** ^The sqlite3_result_int() interface sets the return value
4715 ** of the application-defined function to be the 32-bit signed integer
4716 ** value given in the 2nd argument.
4717 ** ^The sqlite3_result_int64() interface sets the return value
4718 ** of the application-defined function to be the 64-bit signed integer
4719 ** value given in the 2nd argument.
4720 **
4721 ** ^The sqlite3_result_null() interface sets the return value
4722 ** of the application-defined function to be NULL.
4723 **
4724 ** ^The sqlite3_result_text(), sqlite3_result_text16(),
4725 ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
4726 ** set the return value of the application-defined function to be
4727 ** a text string which is represented as UTF-8, UTF-16 native byte order,
4728 ** UTF-16 little endian, or UTF-16 big endian, respectively.
4729 ** ^The sqlite3_result_text64() interface sets the return value of an
4730 ** application-defined function to be a text string in an encoding
4731 ** specified by the fifth (and last) parameter, which must be one
4732 ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
4733 ** ^SQLite takes the text result from the application from
4734 ** the 2nd parameter of the sqlite3_result_text* interfaces.
4735 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4736 ** is negative, then SQLite takes result text from the 2nd parameter
4737 ** through the first zero character.
4738 ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
4739 ** is non-negative, then as many bytes (not characters) of the text
4740 ** pointed to by the 2nd parameter are taken as the application-defined
4741 ** function result.  If the 3rd parameter is non-negative, then it
4742 ** must be the byte offset into the string where the NUL terminator would
4743 ** appear if the string where NUL terminated.  If any NUL characters occur
4744 ** in the string at a byte offset that is less than the value of the 3rd
4745 ** parameter, then the resulting string will contain embedded NULs and the
4746 ** result of expressions operating on strings with embedded NULs is undefined.
4747 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4748 ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
4749 ** function as the destructor on the text or BLOB result when it has
4750 ** finished using that result.
4751 ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
4752 ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
4753 ** assumes that the text or BLOB result is in constant space and does not
4754 ** copy the content of the parameter nor call a destructor on the content
4755 ** when it has finished using that result.
4756 ** ^If the 4th parameter to the sqlite3_result_text* interfaces
4757 ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
4758 ** then SQLite makes a copy of the result into space obtained from
4759 ** from [sqlite3_malloc()] before it returns.
4760 **
4761 ** ^The sqlite3_result_value() interface sets the result of
4762 ** the application-defined function to be a copy the
4763 ** [unprotected sqlite3_value] object specified by the 2nd parameter.  ^The
4764 ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
4765 ** so that the [sqlite3_value] specified in the parameter may change or
4766 ** be deallocated after sqlite3_result_value() returns without harm.
4767 ** ^A [protected sqlite3_value] object may always be used where an
4768 ** [unprotected sqlite3_value] object is required, so either
4769 ** kind of [sqlite3_value] object can be used with this interface.
4770 **
4771 ** If these routines are called from within the different thread
4772 ** than the one containing the application-defined function that received
4773 ** the [sqlite3_context] pointer, the results are undefined.
4774 */
4775 SQLITE_API void SQLITE_STDCALL sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
4776 SQLITE_API void SQLITE_STDCALL sqlite3_result_blob64(sqlite3_context*,const void*,
4777                            sqlite3_uint64,void(*)(void*));
4778 SQLITE_API void SQLITE_STDCALL sqlite3_result_double(sqlite3_context*, double);
4779 SQLITE_API void SQLITE_STDCALL sqlite3_result_error(sqlite3_context*, const char*, int);
4780 SQLITE_API void SQLITE_STDCALL sqlite3_result_error16(sqlite3_context*, const void*, int);
4781 SQLITE_API void SQLITE_STDCALL sqlite3_result_error_toobig(sqlite3_context*);
4782 SQLITE_API void SQLITE_STDCALL sqlite3_result_error_nomem(sqlite3_context*);
4783 SQLITE_API void SQLITE_STDCALL sqlite3_result_error_code(sqlite3_context*, int);
4784 SQLITE_API void SQLITE_STDCALL sqlite3_result_int(sqlite3_context*, int);
4785 SQLITE_API void SQLITE_STDCALL sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
4786 SQLITE_API void SQLITE_STDCALL sqlite3_result_null(sqlite3_context*);
4787 SQLITE_API void SQLITE_STDCALL sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
4788 SQLITE_API void SQLITE_STDCALL sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
4789                            void(*)(void*), unsigned char encoding);
4790 SQLITE_API void SQLITE_STDCALL sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
4791 SQLITE_API void SQLITE_STDCALL sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
4792 SQLITE_API void SQLITE_STDCALL sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
4793 SQLITE_API void SQLITE_STDCALL sqlite3_result_value(sqlite3_context*, sqlite3_value*);
4794 SQLITE_API void SQLITE_STDCALL sqlite3_result_zeroblob(sqlite3_context*, int n);
4795
4796 /*
4797 ** CAPI3REF: Define New Collating Sequences
4798 **
4799 ** ^These functions add, remove, or modify a [collation] associated
4800 ** with the [database connection] specified as the first argument.
4801 **
4802 ** ^The name of the collation is a UTF-8 string
4803 ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
4804 ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
4805 ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
4806 ** considered to be the same name.
4807 **
4808 ** ^(The third argument (eTextRep) must be one of the constants:
4809 ** <ul>
4810 ** <li> [SQLITE_UTF8],
4811 ** <li> [SQLITE_UTF16LE],
4812 ** <li> [SQLITE_UTF16BE],
4813 ** <li> [SQLITE_UTF16], or
4814 ** <li> [SQLITE_UTF16_ALIGNED].
4815 ** </ul>)^
4816 ** ^The eTextRep argument determines the encoding of strings passed
4817 ** to the collating function callback, xCallback.
4818 ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
4819 ** force strings to be UTF16 with native byte order.
4820 ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
4821 ** on an even byte address.
4822 **
4823 ** ^The fourth argument, pArg, is an application data pointer that is passed
4824 ** through as the first argument to the collating function callback.
4825 **
4826 ** ^The fifth argument, xCallback, is a pointer to the collating function.
4827 ** ^Multiple collating functions can be registered using the same name but
4828 ** with different eTextRep parameters and SQLite will use whichever
4829 ** function requires the least amount of data transformation.
4830 ** ^If the xCallback argument is NULL then the collating function is
4831 ** deleted.  ^When all collating functions having the same name are deleted,
4832 ** that collation is no longer usable.
4833 **
4834 ** ^The collating function callback is invoked with a copy of the pArg 
4835 ** application data pointer and with two strings in the encoding specified
4836 ** by the eTextRep argument.  The collating function must return an
4837 ** integer that is negative, zero, or positive
4838 ** if the first string is less than, equal to, or greater than the second,
4839 ** respectively.  A collating function must always return the same answer
4840 ** given the same inputs.  If two or more collating functions are registered
4841 ** to the same collation name (using different eTextRep values) then all
4842 ** must give an equivalent answer when invoked with equivalent strings.
4843 ** The collating function must obey the following properties for all
4844 ** strings A, B, and C:
4845 **
4846 ** <ol>
4847 ** <li> If A==B then B==A.
4848 ** <li> If A==B and B==C then A==C.
4849 ** <li> If A&lt;B THEN B&gt;A.
4850 ** <li> If A&lt;B and B&lt;C then A&lt;C.
4851 ** </ol>
4852 **
4853 ** If a collating function fails any of the above constraints and that
4854 ** collating function is  registered and used, then the behavior of SQLite
4855 ** is undefined.
4856 **
4857 ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
4858 ** with the addition that the xDestroy callback is invoked on pArg when
4859 ** the collating function is deleted.
4860 ** ^Collating functions are deleted when they are overridden by later
4861 ** calls to the collation creation functions or when the
4862 ** [database connection] is closed using [sqlite3_close()].
4863 **
4864 ** ^The xDestroy callback is <u>not</u> called if the 
4865 ** sqlite3_create_collation_v2() function fails.  Applications that invoke
4866 ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should 
4867 ** check the return code and dispose of the application data pointer
4868 ** themselves rather than expecting SQLite to deal with it for them.
4869 ** This is different from every other SQLite interface.  The inconsistency 
4870 ** is unfortunate but cannot be changed without breaking backwards 
4871 ** compatibility.
4872 **
4873 ** See also:  [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
4874 */
4875 SQLITE_API int SQLITE_STDCALL sqlite3_create_collation(
4876   sqlite3*, 
4877   const char *zName, 
4878   int eTextRep, 
4879   void *pArg,
4880   int(*xCompare)(void*,int,const void*,int,const void*)
4881 );
4882 SQLITE_API int SQLITE_STDCALL sqlite3_create_collation_v2(
4883   sqlite3*, 
4884   const char *zName, 
4885   int eTextRep, 
4886   void *pArg,
4887   int(*xCompare)(void*,int,const void*,int,const void*),
4888   void(*xDestroy)(void*)
4889 );
4890 SQLITE_API int SQLITE_STDCALL sqlite3_create_collation16(
4891   sqlite3*, 
4892   const void *zName,
4893   int eTextRep, 
4894   void *pArg,
4895   int(*xCompare)(void*,int,const void*,int,const void*)
4896 );
4897
4898 /*
4899 ** CAPI3REF: Collation Needed Callbacks
4900 **
4901 ** ^To avoid having to register all collation sequences before a database
4902 ** can be used, a single callback function may be registered with the
4903 ** [database connection] to be invoked whenever an undefined collation
4904 ** sequence is required.
4905 **
4906 ** ^If the function is registered using the sqlite3_collation_needed() API,
4907 ** then it is passed the names of undefined collation sequences as strings
4908 ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
4909 ** the names are passed as UTF-16 in machine native byte order.
4910 ** ^A call to either function replaces the existing collation-needed callback.
4911 **
4912 ** ^(When the callback is invoked, the first argument passed is a copy
4913 ** of the second argument to sqlite3_collation_needed() or
4914 ** sqlite3_collation_needed16().  The second argument is the database
4915 ** connection.  The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
4916 ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
4917 ** sequence function required.  The fourth parameter is the name of the
4918 ** required collation sequence.)^
4919 **
4920 ** The callback function should register the desired collation using
4921 ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
4922 ** [sqlite3_create_collation_v2()].
4923 */
4924 SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed(
4925   sqlite3*, 
4926   void*, 
4927   void(*)(void*,sqlite3*,int eTextRep,const char*)
4928 );
4929 SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed16(
4930   sqlite3*, 
4931   void*,
4932   void(*)(void*,sqlite3*,int eTextRep,const void*)
4933 );
4934
4935 #ifdef SQLITE_HAS_CODEC
4936 /*
4937 ** Specify the key for an encrypted database.  This routine should be
4938 ** called right after sqlite3_open().
4939 **
4940 ** The code to implement this API is not available in the public release
4941 ** of SQLite.
4942 */
4943 SQLITE_API int SQLITE_STDCALL sqlite3_key(
4944   sqlite3 *db,                   /* Database to be rekeyed */
4945   const void *pKey, int nKey     /* The key */
4946 );
4947 SQLITE_API int SQLITE_STDCALL sqlite3_key_v2(
4948   sqlite3 *db,                   /* Database to be rekeyed */
4949   const char *zDbName,           /* Name of the database */
4950   const void *pKey, int nKey     /* The key */
4951 );
4952
4953 /*
4954 ** Change the key on an open database.  If the current database is not
4955 ** encrypted, this routine will encrypt it.  If pNew==0 or nNew==0, the
4956 ** database is decrypted.
4957 **
4958 ** The code to implement this API is not available in the public release
4959 ** of SQLite.
4960 */
4961 SQLITE_API int SQLITE_STDCALL sqlite3_rekey(
4962   sqlite3 *db,                   /* Database to be rekeyed */
4963   const void *pKey, int nKey     /* The new key */
4964 );
4965 SQLITE_API int SQLITE_STDCALL sqlite3_rekey_v2(
4966   sqlite3 *db,                   /* Database to be rekeyed */
4967   const char *zDbName,           /* Name of the database */
4968   const void *pKey, int nKey     /* The new key */
4969 );
4970
4971 /*
4972 ** Specify the activation key for a SEE database.  Unless 
4973 ** activated, none of the SEE routines will work.
4974 */
4975 SQLITE_API void SQLITE_STDCALL sqlite3_activate_see(
4976   const char *zPassPhrase        /* Activation phrase */
4977 );
4978 #endif
4979
4980 #ifdef SQLITE_ENABLE_CEROD
4981 /*
4982 ** Specify the activation key for a CEROD database.  Unless 
4983 ** activated, none of the CEROD routines will work.
4984 */
4985 SQLITE_API void SQLITE_STDCALL sqlite3_activate_cerod(
4986   const char *zPassPhrase        /* Activation phrase */
4987 );
4988 #endif
4989
4990 /*
4991 ** CAPI3REF: Suspend Execution For A Short Time
4992 **
4993 ** The sqlite3_sleep() function causes the current thread to suspend execution
4994 ** for at least a number of milliseconds specified in its parameter.
4995 **
4996 ** If the operating system does not support sleep requests with
4997 ** millisecond time resolution, then the time will be rounded up to
4998 ** the nearest second. The number of milliseconds of sleep actually
4999 ** requested from the operating system is returned.
5000 **
5001 ** ^SQLite implements this interface by calling the xSleep()
5002 ** method of the default [sqlite3_vfs] object.  If the xSleep() method
5003 ** of the default VFS is not implemented correctly, or not implemented at
5004 ** all, then the behavior of sqlite3_sleep() may deviate from the description
5005 ** in the previous paragraphs.
5006 */
5007 SQLITE_API int SQLITE_STDCALL sqlite3_sleep(int);
5008
5009 /*
5010 ** CAPI3REF: Name Of The Folder Holding Temporary Files
5011 **
5012 ** ^(If this global variable is made to point to a string which is
5013 ** the name of a folder (a.k.a. directory), then all temporary files
5014 ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
5015 ** will be placed in that directory.)^  ^If this variable
5016 ** is a NULL pointer, then SQLite performs a search for an appropriate
5017 ** temporary file directory.
5018 **
5019 ** Applications are strongly discouraged from using this global variable.
5020 ** It is required to set a temporary folder on Windows Runtime (WinRT).
5021 ** But for all other platforms, it is highly recommended that applications
5022 ** neither read nor write this variable.  This global variable is a relic
5023 ** that exists for backwards compatibility of legacy applications and should
5024 ** be avoided in new projects.
5025 **
5026 ** It is not safe to read or modify this variable in more than one
5027 ** thread at a time.  It is not safe to read or modify this variable
5028 ** if a [database connection] is being used at the same time in a separate
5029 ** thread.
5030 ** It is intended that this variable be set once
5031 ** as part of process initialization and before any SQLite interface
5032 ** routines have been called and that this variable remain unchanged
5033 ** thereafter.
5034 **
5035 ** ^The [temp_store_directory pragma] may modify this variable and cause
5036 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
5037 ** the [temp_store_directory pragma] always assumes that any string
5038 ** that this variable points to is held in memory obtained from 
5039 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5040 ** using [sqlite3_free].
5041 ** Hence, if this variable is modified directly, either it should be
5042 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5043 ** or else the use of the [temp_store_directory pragma] should be avoided.
5044 ** Except when requested by the [temp_store_directory pragma], SQLite
5045 ** does not free the memory that sqlite3_temp_directory points to.  If
5046 ** the application wants that memory to be freed, it must do
5047 ** so itself, taking care to only do so after all [database connection]
5048 ** objects have been destroyed.
5049 **
5050 ** <b>Note to Windows Runtime users:</b>  The temporary directory must be set
5051 ** prior to calling [sqlite3_open] or [sqlite3_open_v2].  Otherwise, various
5052 ** features that require the use of temporary files may fail.  Here is an
5053 ** example of how to do this using C++ with the Windows Runtime:
5054 **
5055 ** <blockquote><pre>
5056 ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
5057 ** &nbsp;     TemporaryFolder->Path->Data();
5058 ** char zPathBuf&#91;MAX_PATH + 1&#93;;
5059 ** memset(zPathBuf, 0, sizeof(zPathBuf));
5060 ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
5061 ** &nbsp;     NULL, NULL);
5062 ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
5063 ** </pre></blockquote>
5064 */
5065 SQLITE_API char *sqlite3_temp_directory;
5066
5067 /*
5068 ** CAPI3REF: Name Of The Folder Holding Database Files
5069 **
5070 ** ^(If this global variable is made to point to a string which is
5071 ** the name of a folder (a.k.a. directory), then all database files
5072 ** specified with a relative pathname and created or accessed by
5073 ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
5074 ** to be relative to that directory.)^ ^If this variable is a NULL
5075 ** pointer, then SQLite assumes that all database files specified
5076 ** with a relative pathname are relative to the current directory
5077 ** for the process.  Only the windows VFS makes use of this global
5078 ** variable; it is ignored by the unix VFS.
5079 **
5080 ** Changing the value of this variable while a database connection is
5081 ** open can result in a corrupt database.
5082 **
5083 ** It is not safe to read or modify this variable in more than one
5084 ** thread at a time.  It is not safe to read or modify this variable
5085 ** if a [database connection] is being used at the same time in a separate
5086 ** thread.
5087 ** It is intended that this variable be set once
5088 ** as part of process initialization and before any SQLite interface
5089 ** routines have been called and that this variable remain unchanged
5090 ** thereafter.
5091 **
5092 ** ^The [data_store_directory pragma] may modify this variable and cause
5093 ** it to point to memory obtained from [sqlite3_malloc].  ^Furthermore,
5094 ** the [data_store_directory pragma] always assumes that any string
5095 ** that this variable points to is held in memory obtained from 
5096 ** [sqlite3_malloc] and the pragma may attempt to free that memory
5097 ** using [sqlite3_free].
5098 ** Hence, if this variable is modified directly, either it should be
5099 ** made NULL or made to point to memory obtained from [sqlite3_malloc]
5100 ** or else the use of the [data_store_directory pragma] should be avoided.
5101 */
5102 SQLITE_API char *sqlite3_data_directory;
5103
5104 /*
5105 ** CAPI3REF: Test For Auto-Commit Mode
5106 ** KEYWORDS: {autocommit mode}
5107 **
5108 ** ^The sqlite3_get_autocommit() interface returns non-zero or
5109 ** zero if the given database connection is or is not in autocommit mode,
5110 ** respectively.  ^Autocommit mode is on by default.
5111 ** ^Autocommit mode is disabled by a [BEGIN] statement.
5112 ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
5113 **
5114 ** If certain kinds of errors occur on a statement within a multi-statement
5115 ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
5116 ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
5117 ** transaction might be rolled back automatically.  The only way to
5118 ** find out whether SQLite automatically rolled back the transaction after
5119 ** an error is to use this function.
5120 **
5121 ** If another thread changes the autocommit status of the database
5122 ** connection while this routine is running, then the return value
5123 ** is undefined.
5124 */
5125 SQLITE_API int SQLITE_STDCALL sqlite3_get_autocommit(sqlite3*);
5126
5127 /*
5128 ** CAPI3REF: Find The Database Handle Of A Prepared Statement
5129 **
5130 ** ^The sqlite3_db_handle interface returns the [database connection] handle
5131 ** to which a [prepared statement] belongs.  ^The [database connection]
5132 ** returned by sqlite3_db_handle is the same [database connection]
5133 ** that was the first argument
5134 ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
5135 ** create the statement in the first place.
5136 */
5137 SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_db_handle(sqlite3_stmt*);
5138
5139 /*
5140 ** CAPI3REF: Return The Filename For A Database Connection
5141 **
5142 ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
5143 ** associated with database N of connection D.  ^The main database file
5144 ** has the name "main".  If there is no attached database N on the database
5145 ** connection D, or if database N is a temporary or in-memory database, then
5146 ** a NULL pointer is returned.
5147 **
5148 ** ^The filename returned by this function is the output of the
5149 ** xFullPathname method of the [VFS].  ^In other words, the filename
5150 ** will be an absolute pathname, even if the filename used
5151 ** to open the database originally was a URI or relative pathname.
5152 */
5153 SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName);
5154
5155 /*
5156 ** CAPI3REF: Determine if a database is read-only
5157 **
5158 ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
5159 ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
5160 ** the name of a database on connection D.
5161 */
5162 SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
5163
5164 /*
5165 ** CAPI3REF: Find the next prepared statement
5166 **
5167 ** ^This interface returns a pointer to the next [prepared statement] after
5168 ** pStmt associated with the [database connection] pDb.  ^If pStmt is NULL
5169 ** then this interface returns a pointer to the first prepared statement
5170 ** associated with the database connection pDb.  ^If no prepared statement
5171 ** satisfies the conditions of this routine, it returns NULL.
5172 **
5173 ** The [database connection] pointer D in a call to
5174 ** [sqlite3_next_stmt(D,S)] must refer to an open database
5175 ** connection and in particular must not be a NULL pointer.
5176 */
5177 SQLITE_API sqlite3_stmt *SQLITE_STDCALL sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
5178
5179 /*
5180 ** CAPI3REF: Commit And Rollback Notification Callbacks
5181 **
5182 ** ^The sqlite3_commit_hook() interface registers a callback
5183 ** function to be invoked whenever a transaction is [COMMIT | committed].
5184 ** ^Any callback set by a previous call to sqlite3_commit_hook()
5185 ** for the same database connection is overridden.
5186 ** ^The sqlite3_rollback_hook() interface registers a callback
5187 ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
5188 ** ^Any callback set by a previous call to sqlite3_rollback_hook()
5189 ** for the same database connection is overridden.
5190 ** ^The pArg argument is passed through to the callback.
5191 ** ^If the callback on a commit hook function returns non-zero,
5192 ** then the commit is converted into a rollback.
5193 **
5194 ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
5195 ** return the P argument from the previous call of the same function
5196 ** on the same [database connection] D, or NULL for
5197 ** the first call for each function on D.
5198 **
5199 ** The commit and rollback hook callbacks are not reentrant.
5200 ** The callback implementation must not do anything that will modify
5201 ** the database connection that invoked the callback.  Any actions
5202 ** to modify the database connection must be deferred until after the
5203 ** completion of the [sqlite3_step()] call that triggered the commit
5204 ** or rollback hook in the first place.
5205 ** Note that running any other SQL statements, including SELECT statements,
5206 ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
5207 ** the database connections for the meaning of "modify" in this paragraph.
5208 **
5209 ** ^Registering a NULL function disables the callback.
5210 **
5211 ** ^When the commit hook callback routine returns zero, the [COMMIT]
5212 ** operation is allowed to continue normally.  ^If the commit hook
5213 ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
5214 ** ^The rollback hook is invoked on a rollback that results from a commit
5215 ** hook returning non-zero, just as it would be with any other rollback.
5216 **
5217 ** ^For the purposes of this API, a transaction is said to have been
5218 ** rolled back if an explicit "ROLLBACK" statement is executed, or
5219 ** an error or constraint causes an implicit rollback to occur.
5220 ** ^The rollback callback is not invoked if a transaction is
5221 ** automatically rolled back because the database connection is closed.
5222 **
5223 ** See also the [sqlite3_update_hook()] interface.
5224 */
5225 SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
5226 SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
5227
5228 /*
5229 ** CAPI3REF: Data Change Notification Callbacks
5230 **
5231 ** ^The sqlite3_update_hook() interface registers a callback function
5232 ** with the [database connection] identified by the first argument
5233 ** to be invoked whenever a row is updated, inserted or deleted in
5234 ** a rowid table.
5235 ** ^Any callback set by a previous call to this function
5236 ** for the same database connection is overridden.
5237 **
5238 ** ^The second argument is a pointer to the function to invoke when a
5239 ** row is updated, inserted or deleted in a rowid table.
5240 ** ^The first argument to the callback is a copy of the third argument
5241 ** to sqlite3_update_hook().
5242 ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
5243 ** or [SQLITE_UPDATE], depending on the operation that caused the callback
5244 ** to be invoked.
5245 ** ^The third and fourth arguments to the callback contain pointers to the
5246 ** database and table name containing the affected row.
5247 ** ^The final callback parameter is the [rowid] of the row.
5248 ** ^In the case of an update, this is the [rowid] after the update takes place.
5249 **
5250 ** ^(The update hook is not invoked when internal system tables are
5251 ** modified (i.e. sqlite_master and sqlite_sequence).)^
5252 ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
5253 **
5254 ** ^In the current implementation, the update hook
5255 ** is not invoked when duplication rows are deleted because of an
5256 ** [ON CONFLICT | ON CONFLICT REPLACE] clause.  ^Nor is the update hook
5257 ** invoked when rows are deleted using the [truncate optimization].
5258 ** The exceptions defined in this paragraph might change in a future
5259 ** release of SQLite.
5260 **
5261 ** The update hook implementation must not do anything that will modify
5262 ** the database connection that invoked the update hook.  Any actions
5263 ** to modify the database connection must be deferred until after the
5264 ** completion of the [sqlite3_step()] call that triggered the update hook.
5265 ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
5266 ** database connections for the meaning of "modify" in this paragraph.
5267 **
5268 ** ^The sqlite3_update_hook(D,C,P) function
5269 ** returns the P argument from the previous call
5270 ** on the same [database connection] D, or NULL for
5271 ** the first call on D.
5272 **
5273 ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
5274 ** interfaces.
5275 */
5276 SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
5277   sqlite3*, 
5278   void(*)(void *,int ,char const *,char const *,sqlite3_int64),
5279   void*
5280 );
5281
5282 /*
5283 ** CAPI3REF: Enable Or Disable Shared Pager Cache
5284 **
5285 ** ^(This routine enables or disables the sharing of the database cache
5286 ** and schema data structures between [database connection | connections]
5287 ** to the same database. Sharing is enabled if the argument is true
5288 ** and disabled if the argument is false.)^
5289 **
5290 ** ^Cache sharing is enabled and disabled for an entire process.
5291 ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
5292 ** sharing was enabled or disabled for each thread separately.
5293 **
5294 ** ^(The cache sharing mode set by this interface effects all subsequent
5295 ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
5296 ** Existing database connections continue use the sharing mode
5297 ** that was in effect at the time they were opened.)^
5298 **
5299 ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
5300 ** successfully.  An [error code] is returned otherwise.)^
5301 **
5302 ** ^Shared cache is disabled by default. But this might change in
5303 ** future releases of SQLite.  Applications that care about shared
5304 ** cache setting should set it explicitly.
5305 **
5306 ** Note: This method is disabled on MacOS X 10.7 and iOS version 5.0
5307 ** and will always return SQLITE_MISUSE. On those systems, 
5308 ** shared cache mode should be enabled per-database connection via 
5309 ** [sqlite3_open_v2()] with [SQLITE_OPEN_SHAREDCACHE].
5310 **
5311 ** This interface is threadsafe on processors where writing a
5312 ** 32-bit integer is atomic.
5313 **
5314 ** See Also:  [SQLite Shared-Cache Mode]
5315 */
5316 SQLITE_API int SQLITE_STDCALL sqlite3_enable_shared_cache(int);
5317
5318 /*
5319 ** CAPI3REF: Attempt To Free Heap Memory
5320 **
5321 ** ^The sqlite3_release_memory() interface attempts to free N bytes
5322 ** of heap memory by deallocating non-essential memory allocations
5323 ** held by the database library.   Memory used to cache database
5324 ** pages to improve performance is an example of non-essential memory.
5325 ** ^sqlite3_release_memory() returns the number of bytes actually freed,
5326 ** which might be more or less than the amount requested.
5327 ** ^The sqlite3_release_memory() routine is a no-op returning zero
5328 ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5329 **
5330 ** See also: [sqlite3_db_release_memory()]
5331 */
5332 SQLITE_API int SQLITE_STDCALL sqlite3_release_memory(int);
5333
5334 /*
5335 ** CAPI3REF: Free Memory Used By A Database Connection
5336 **
5337 ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
5338 ** memory as possible from database connection D. Unlike the
5339 ** [sqlite3_release_memory()] interface, this interface is in effect even
5340 ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
5341 ** omitted.
5342 **
5343 ** See also: [sqlite3_release_memory()]
5344 */
5345 SQLITE_API int SQLITE_STDCALL sqlite3_db_release_memory(sqlite3*);
5346
5347 /*
5348 ** CAPI3REF: Impose A Limit On Heap Size
5349 **
5350 ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
5351 ** soft limit on the amount of heap memory that may be allocated by SQLite.
5352 ** ^SQLite strives to keep heap memory utilization below the soft heap
5353 ** limit by reducing the number of pages held in the page cache
5354 ** as heap memory usages approaches the limit.
5355 ** ^The soft heap limit is "soft" because even though SQLite strives to stay
5356 ** below the limit, it will exceed the limit rather than generate
5357 ** an [SQLITE_NOMEM] error.  In other words, the soft heap limit 
5358 ** is advisory only.
5359 **
5360 ** ^The return value from sqlite3_soft_heap_limit64() is the size of
5361 ** the soft heap limit prior to the call, or negative in the case of an
5362 ** error.  ^If the argument N is negative
5363 ** then no change is made to the soft heap limit.  Hence, the current
5364 ** size of the soft heap limit can be determined by invoking
5365 ** sqlite3_soft_heap_limit64() with a negative argument.
5366 **
5367 ** ^If the argument N is zero then the soft heap limit is disabled.
5368 **
5369 ** ^(The soft heap limit is not enforced in the current implementation
5370 ** if one or more of following conditions are true:
5371 **
5372 ** <ul>
5373 ** <li> The soft heap limit is set to zero.
5374 ** <li> Memory accounting is disabled using a combination of the
5375 **      [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
5376 **      the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
5377 ** <li> An alternative page cache implementation is specified using
5378 **      [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
5379 ** <li> The page cache allocates from its own memory pool supplied
5380 **      by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
5381 **      from the heap.
5382 ** </ul>)^
5383 **
5384 ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
5385 ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
5386 ** compile-time option is invoked.  With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
5387 ** the soft heap limit is enforced on every memory allocation.  Without
5388 ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
5389 ** when memory is allocated by the page cache.  Testing suggests that because
5390 ** the page cache is the predominate memory user in SQLite, most
5391 ** applications will achieve adequate soft heap limit enforcement without
5392 ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
5393 **
5394 ** The circumstances under which SQLite will enforce the soft heap limit may
5395 ** changes in future releases of SQLite.
5396 */
5397 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_soft_heap_limit64(sqlite3_int64 N);
5398
5399 /*
5400 ** CAPI3REF: Deprecated Soft Heap Limit Interface
5401 ** DEPRECATED
5402 **
5403 ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
5404 ** interface.  This routine is provided for historical compatibility
5405 ** only.  All new applications should use the
5406 ** [sqlite3_soft_heap_limit64()] interface rather than this one.
5407 */
5408 SQLITE_API SQLITE_DEPRECATED void SQLITE_STDCALL sqlite3_soft_heap_limit(int N);
5409
5410
5411 /*
5412 ** CAPI3REF: Extract Metadata About A Column Of A Table
5413 **
5414 ** ^(The sqlite3_table_column_metadata(X,D,T,C,....) routine returns
5415 ** information about column C of table T in database D
5416 ** on [database connection] X.)^  ^The sqlite3_table_column_metadata()
5417 ** interface returns SQLITE_OK and fills in the non-NULL pointers in
5418 ** the final five arguments with appropriate values if the specified
5419 ** column exists.  ^The sqlite3_table_column_metadata() interface returns
5420 ** SQLITE_ERROR and if the specified column does not exist.
5421 ** ^If the column-name parameter to sqlite3_table_column_metadata() is a
5422 ** NULL pointer, then this routine simply checks for the existance of the
5423 ** table and returns SQLITE_OK if the table exists and SQLITE_ERROR if it
5424 ** does not.
5425 **
5426 ** ^The column is identified by the second, third and fourth parameters to
5427 ** this function. ^(The second parameter is either the name of the database
5428 ** (i.e. "main", "temp", or an attached database) containing the specified
5429 ** table or NULL.)^ ^If it is NULL, then all attached databases are searched
5430 ** for the table using the same algorithm used by the database engine to
5431 ** resolve unqualified table references.
5432 **
5433 ** ^The third and fourth parameters to this function are the table and column
5434 ** name of the desired column, respectively.
5435 **
5436 ** ^Metadata is returned by writing to the memory locations passed as the 5th
5437 ** and subsequent parameters to this function. ^Any of these arguments may be
5438 ** NULL, in which case the corresponding element of metadata is omitted.
5439 **
5440 ** ^(<blockquote>
5441 ** <table border="1">
5442 ** <tr><th> Parameter <th> Output<br>Type <th>  Description
5443 **
5444 ** <tr><td> 5th <td> const char* <td> Data type
5445 ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
5446 ** <tr><td> 7th <td> int         <td> True if column has a NOT NULL constraint
5447 ** <tr><td> 8th <td> int         <td> True if column is part of the PRIMARY KEY
5448 ** <tr><td> 9th <td> int         <td> True if column is [AUTOINCREMENT]
5449 ** </table>
5450 ** </blockquote>)^
5451 **
5452 ** ^The memory pointed to by the character pointers returned for the
5453 ** declaration type and collation sequence is valid until the next
5454 ** call to any SQLite API function.
5455 **
5456 ** ^If the specified table is actually a view, an [error code] is returned.
5457 **
5458 ** ^If the specified column is "rowid", "oid" or "_rowid_" and the table 
5459 ** is not a [WITHOUT ROWID] table and an
5460 ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
5461 ** parameters are set for the explicitly declared column. ^(If there is no
5462 ** [INTEGER PRIMARY KEY] column, then the outputs
5463 ** for the [rowid] are set as follows:
5464 **
5465 ** <pre>
5466 **     data type: "INTEGER"
5467 **     collation sequence: "BINARY"
5468 **     not null: 0
5469 **     primary key: 1
5470 **     auto increment: 0
5471 ** </pre>)^
5472 **
5473 ** ^This function causes all database schemas to be read from disk and
5474 ** parsed, if that has not already been done, and returns an error if
5475 ** any errors are encountered while loading the schema.
5476 */
5477 SQLITE_API int SQLITE_STDCALL sqlite3_table_column_metadata(
5478   sqlite3 *db,                /* Connection handle */
5479   const char *zDbName,        /* Database name or NULL */
5480   const char *zTableName,     /* Table name */
5481   const char *zColumnName,    /* Column name */
5482   char const **pzDataType,    /* OUTPUT: Declared data type */
5483   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
5484   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
5485   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
5486   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
5487 );
5488
5489 /*
5490 ** CAPI3REF: Load An Extension
5491 **
5492 ** ^This interface loads an SQLite extension library from the named file.
5493 **
5494 ** ^The sqlite3_load_extension() interface attempts to load an
5495 ** [SQLite extension] library contained in the file zFile.  If
5496 ** the file cannot be loaded directly, attempts are made to load
5497 ** with various operating-system specific extensions added.
5498 ** So for example, if "samplelib" cannot be loaded, then names like
5499 ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
5500 ** be tried also.
5501 **
5502 ** ^The entry point is zProc.
5503 ** ^(zProc may be 0, in which case SQLite will try to come up with an
5504 ** entry point name on its own.  It first tries "sqlite3_extension_init".
5505 ** If that does not work, it constructs a name "sqlite3_X_init" where the
5506 ** X is consists of the lower-case equivalent of all ASCII alphabetic
5507 ** characters in the filename from the last "/" to the first following
5508 ** "." and omitting any initial "lib".)^
5509 ** ^The sqlite3_load_extension() interface returns
5510 ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
5511 ** ^If an error occurs and pzErrMsg is not 0, then the
5512 ** [sqlite3_load_extension()] interface shall attempt to
5513 ** fill *pzErrMsg with error message text stored in memory
5514 ** obtained from [sqlite3_malloc()]. The calling function
5515 ** should free this memory by calling [sqlite3_free()].
5516 **
5517 ** ^Extension loading must be enabled using
5518 ** [sqlite3_enable_load_extension()] prior to calling this API,
5519 ** otherwise an error will be returned.
5520 **
5521 ** See also the [load_extension() SQL function].
5522 */
5523 SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
5524   sqlite3 *db,          /* Load the extension into this database connection */
5525   const char *zFile,    /* Name of the shared library containing extension */
5526   const char *zProc,    /* Entry point.  Derived from zFile if 0 */
5527   char **pzErrMsg       /* Put error message here if not 0 */
5528 );
5529
5530 /*
5531 ** CAPI3REF: Enable Or Disable Extension Loading
5532 **
5533 ** ^So as not to open security holes in older applications that are
5534 ** unprepared to deal with [extension loading], and as a means of disabling
5535 ** [extension loading] while evaluating user-entered SQL, the following API
5536 ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
5537 **
5538 ** ^Extension loading is off by default.
5539 ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
5540 ** to turn extension loading on and call it with onoff==0 to turn
5541 ** it back off again.
5542 */
5543 SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff);
5544
5545 /*
5546 ** CAPI3REF: Automatically Load Statically Linked Extensions
5547 **
5548 ** ^This interface causes the xEntryPoint() function to be invoked for
5549 ** each new [database connection] that is created.  The idea here is that
5550 ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
5551 ** that is to be automatically loaded into all new database connections.
5552 **
5553 ** ^(Even though the function prototype shows that xEntryPoint() takes
5554 ** no arguments and returns void, SQLite invokes xEntryPoint() with three
5555 ** arguments and expects and integer result as if the signature of the
5556 ** entry point where as follows:
5557 **
5558 ** <blockquote><pre>
5559 ** &nbsp;  int xEntryPoint(
5560 ** &nbsp;    sqlite3 *db,
5561 ** &nbsp;    const char **pzErrMsg,
5562 ** &nbsp;    const struct sqlite3_api_routines *pThunk
5563 ** &nbsp;  );
5564 ** </pre></blockquote>)^
5565 **
5566 ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
5567 ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
5568 ** and return an appropriate [error code].  ^SQLite ensures that *pzErrMsg
5569 ** is NULL before calling the xEntryPoint().  ^SQLite will invoke
5570 ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns.  ^If any
5571 ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
5572 ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
5573 **
5574 ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
5575 ** on the list of automatic extensions is a harmless no-op. ^No entry point
5576 ** will be called more than once for each database connection that is opened.
5577 **
5578 ** See also: [sqlite3_reset_auto_extension()]
5579 ** and [sqlite3_cancel_auto_extension()]
5580 */
5581 SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(void (*xEntryPoint)(void));
5582
5583 /*
5584 ** CAPI3REF: Cancel Automatic Extension Loading
5585 **
5586 ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
5587 ** initialization routine X that was registered using a prior call to
5588 ** [sqlite3_auto_extension(X)].  ^The [sqlite3_cancel_auto_extension(X)]
5589 ** routine returns 1 if initialization routine X was successfully 
5590 ** unregistered and it returns 0 if X was not on the list of initialization
5591 ** routines.
5592 */
5593 SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(void (*xEntryPoint)(void));
5594
5595 /*
5596 ** CAPI3REF: Reset Automatic Extension Loading
5597 **
5598 ** ^This interface disables all automatic extensions previously
5599 ** registered using [sqlite3_auto_extension()].
5600 */
5601 SQLITE_API void SQLITE_STDCALL sqlite3_reset_auto_extension(void);
5602
5603 /*
5604 ** The interface to the virtual-table mechanism is currently considered
5605 ** to be experimental.  The interface might change in incompatible ways.
5606 ** If this is a problem for you, do not use the interface at this time.
5607 **
5608 ** When the virtual-table mechanism stabilizes, we will declare the
5609 ** interface fixed, support it indefinitely, and remove this comment.
5610 */
5611
5612 /*
5613 ** Structures used by the virtual table interface
5614 */
5615 typedef struct sqlite3_vtab sqlite3_vtab;
5616 typedef struct sqlite3_index_info sqlite3_index_info;
5617 typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
5618 typedef struct sqlite3_module sqlite3_module;
5619
5620 /*
5621 ** CAPI3REF: Virtual Table Object
5622 ** KEYWORDS: sqlite3_module {virtual table module}
5623 **
5624 ** This structure, sometimes called a "virtual table module", 
5625 ** defines the implementation of a [virtual tables].  
5626 ** This structure consists mostly of methods for the module.
5627 **
5628 ** ^A virtual table module is created by filling in a persistent
5629 ** instance of this structure and passing a pointer to that instance
5630 ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
5631 ** ^The registration remains valid until it is replaced by a different
5632 ** module or until the [database connection] closes.  The content
5633 ** of this structure must not change while it is registered with
5634 ** any database connection.
5635 */
5636 struct sqlite3_module {
5637   int iVersion;
5638   int (*xCreate)(sqlite3*, void *pAux,
5639                int argc, const char *const*argv,
5640                sqlite3_vtab **ppVTab, char**);
5641   int (*xConnect)(sqlite3*, void *pAux,
5642                int argc, const char *const*argv,
5643                sqlite3_vtab **ppVTab, char**);
5644   int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
5645   int (*xDisconnect)(sqlite3_vtab *pVTab);
5646   int (*xDestroy)(sqlite3_vtab *pVTab);
5647   int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
5648   int (*xClose)(sqlite3_vtab_cursor*);
5649   int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
5650                 int argc, sqlite3_value **argv);
5651   int (*xNext)(sqlite3_vtab_cursor*);
5652   int (*xEof)(sqlite3_vtab_cursor*);
5653   int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
5654   int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
5655   int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
5656   int (*xBegin)(sqlite3_vtab *pVTab);
5657   int (*xSync)(sqlite3_vtab *pVTab);
5658   int (*xCommit)(sqlite3_vtab *pVTab);
5659   int (*xRollback)(sqlite3_vtab *pVTab);
5660   int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
5661                        void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
5662                        void **ppArg);
5663   int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
5664   /* The methods above are in version 1 of the sqlite_module object. Those 
5665   ** below are for version 2 and greater. */
5666   int (*xSavepoint)(sqlite3_vtab *pVTab, int);
5667   int (*xRelease)(sqlite3_vtab *pVTab, int);
5668   int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
5669 };
5670
5671 /*
5672 ** CAPI3REF: Virtual Table Indexing Information
5673 ** KEYWORDS: sqlite3_index_info
5674 **
5675 ** The sqlite3_index_info structure and its substructures is used as part
5676 ** of the [virtual table] interface to
5677 ** pass information into and receive the reply from the [xBestIndex]
5678 ** method of a [virtual table module].  The fields under **Inputs** are the
5679 ** inputs to xBestIndex and are read-only.  xBestIndex inserts its
5680 ** results into the **Outputs** fields.
5681 **
5682 ** ^(The aConstraint[] array records WHERE clause constraints of the form:
5683 **
5684 ** <blockquote>column OP expr</blockquote>
5685 **
5686 ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^  ^(The particular operator is
5687 ** stored in aConstraint[].op using one of the
5688 ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
5689 ** ^(The index of the column is stored in
5690 ** aConstraint[].iColumn.)^  ^(aConstraint[].usable is TRUE if the
5691 ** expr on the right-hand side can be evaluated (and thus the constraint
5692 ** is usable) and false if it cannot.)^
5693 **
5694 ** ^The optimizer automatically inverts terms of the form "expr OP column"
5695 ** and makes other simplifications to the WHERE clause in an attempt to
5696 ** get as many WHERE clause terms into the form shown above as possible.
5697 ** ^The aConstraint[] array only reports WHERE clause terms that are
5698 ** relevant to the particular virtual table being queried.
5699 **
5700 ** ^Information about the ORDER BY clause is stored in aOrderBy[].
5701 ** ^Each term of aOrderBy records a column of the ORDER BY clause.
5702 **
5703 ** The [xBestIndex] method must fill aConstraintUsage[] with information
5704 ** about what parameters to pass to xFilter.  ^If argvIndex>0 then
5705 ** the right-hand side of the corresponding aConstraint[] is evaluated
5706 ** and becomes the argvIndex-th entry in argv.  ^(If aConstraintUsage[].omit
5707 ** is true, then the constraint is assumed to be fully handled by the
5708 ** virtual table and is not checked again by SQLite.)^
5709 **
5710 ** ^The idxNum and idxPtr values are recorded and passed into the
5711 ** [xFilter] method.
5712 ** ^[sqlite3_free()] is used to free idxPtr if and only if
5713 ** needToFreeIdxPtr is true.
5714 **
5715 ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
5716 ** the correct order to satisfy the ORDER BY clause so that no separate
5717 ** sorting step is required.
5718 **
5719 ** ^The estimatedCost value is an estimate of the cost of a particular
5720 ** strategy. A cost of N indicates that the cost of the strategy is similar
5721 ** to a linear scan of an SQLite table with N rows. A cost of log(N) 
5722 ** indicates that the expense of the operation is similar to that of a
5723 ** binary search on a unique indexed field of an SQLite table with N rows.
5724 **
5725 ** ^The estimatedRows value is an estimate of the number of rows that
5726 ** will be returned by the strategy.
5727 **
5728 ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
5729 ** structure for SQLite version 3.8.2. If a virtual table extension is
5730 ** used with an SQLite version earlier than 3.8.2, the results of attempting 
5731 ** to read or write the estimatedRows field are undefined (but are likely 
5732 ** to included crashing the application). The estimatedRows field should
5733 ** therefore only be used if [sqlite3_libversion_number()] returns a
5734 ** value greater than or equal to 3008002.
5735 */
5736 struct sqlite3_index_info {
5737   /* Inputs */
5738   int nConstraint;           /* Number of entries in aConstraint */
5739   struct sqlite3_index_constraint {
5740      int iColumn;              /* Column on left-hand side of constraint */
5741      unsigned char op;         /* Constraint operator */
5742      unsigned char usable;     /* True if this constraint is usable */
5743      int iTermOffset;          /* Used internally - xBestIndex should ignore */
5744   } *aConstraint;            /* Table of WHERE clause constraints */
5745   int nOrderBy;              /* Number of terms in the ORDER BY clause */
5746   struct sqlite3_index_orderby {
5747      int iColumn;              /* Column number */
5748      unsigned char desc;       /* True for DESC.  False for ASC. */
5749   } *aOrderBy;               /* The ORDER BY clause */
5750   /* Outputs */
5751   struct sqlite3_index_constraint_usage {
5752     int argvIndex;           /* if >0, constraint is part of argv to xFilter */
5753     unsigned char omit;      /* Do not code a test for this constraint */
5754   } *aConstraintUsage;
5755   int idxNum;                /* Number used to identify the index */
5756   char *idxStr;              /* String, possibly obtained from sqlite3_malloc */
5757   int needToFreeIdxStr;      /* Free idxStr using sqlite3_free() if true */
5758   int orderByConsumed;       /* True if output is already ordered */
5759   double estimatedCost;           /* Estimated cost of using this index */
5760   /* Fields below are only available in SQLite 3.8.2 and later */
5761   sqlite3_int64 estimatedRows;    /* Estimated number of rows returned */
5762 };
5763
5764 /*
5765 ** CAPI3REF: Virtual Table Constraint Operator Codes
5766 **
5767 ** These macros defined the allowed values for the
5768 ** [sqlite3_index_info].aConstraint[].op field.  Each value represents
5769 ** an operator that is part of a constraint term in the wHERE clause of
5770 ** a query that uses a [virtual table].
5771 */
5772 #define SQLITE_INDEX_CONSTRAINT_EQ    2
5773 #define SQLITE_INDEX_CONSTRAINT_GT    4
5774 #define SQLITE_INDEX_CONSTRAINT_LE    8
5775 #define SQLITE_INDEX_CONSTRAINT_LT    16
5776 #define SQLITE_INDEX_CONSTRAINT_GE    32
5777 #define SQLITE_INDEX_CONSTRAINT_MATCH 64
5778
5779 /*
5780 ** CAPI3REF: Register A Virtual Table Implementation
5781 **
5782 ** ^These routines are used to register a new [virtual table module] name.
5783 ** ^Module names must be registered before
5784 ** creating a new [virtual table] using the module and before using a
5785 ** preexisting [virtual table] for the module.
5786 **
5787 ** ^The module name is registered on the [database connection] specified
5788 ** by the first parameter.  ^The name of the module is given by the 
5789 ** second parameter.  ^The third parameter is a pointer to
5790 ** the implementation of the [virtual table module].   ^The fourth
5791 ** parameter is an arbitrary client data pointer that is passed through
5792 ** into the [xCreate] and [xConnect] methods of the virtual table module
5793 ** when a new virtual table is be being created or reinitialized.
5794 **
5795 ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
5796 ** is a pointer to a destructor for the pClientData.  ^SQLite will
5797 ** invoke the destructor function (if it is not NULL) when SQLite
5798 ** no longer needs the pClientData pointer.  ^The destructor will also
5799 ** be invoked if the call to sqlite3_create_module_v2() fails.
5800 ** ^The sqlite3_create_module()
5801 ** interface is equivalent to sqlite3_create_module_v2() with a NULL
5802 ** destructor.
5803 */
5804 SQLITE_API int SQLITE_STDCALL sqlite3_create_module(
5805   sqlite3 *db,               /* SQLite connection to register module with */
5806   const char *zName,         /* Name of the module */
5807   const sqlite3_module *p,   /* Methods for the module */
5808   void *pClientData          /* Client data for xCreate/xConnect */
5809 );
5810 SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2(
5811   sqlite3 *db,               /* SQLite connection to register module with */
5812   const char *zName,         /* Name of the module */
5813   const sqlite3_module *p,   /* Methods for the module */
5814   void *pClientData,         /* Client data for xCreate/xConnect */
5815   void(*xDestroy)(void*)     /* Module destructor function */
5816 );
5817
5818 /*
5819 ** CAPI3REF: Virtual Table Instance Object
5820 ** KEYWORDS: sqlite3_vtab
5821 **
5822 ** Every [virtual table module] implementation uses a subclass
5823 ** of this object to describe a particular instance
5824 ** of the [virtual table].  Each subclass will
5825 ** be tailored to the specific needs of the module implementation.
5826 ** The purpose of this superclass is to define certain fields that are
5827 ** common to all module implementations.
5828 **
5829 ** ^Virtual tables methods can set an error message by assigning a
5830 ** string obtained from [sqlite3_mprintf()] to zErrMsg.  The method should
5831 ** take care that any prior string is freed by a call to [sqlite3_free()]
5832 ** prior to assigning a new string to zErrMsg.  ^After the error message
5833 ** is delivered up to the client application, the string will be automatically
5834 ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
5835 */
5836 struct sqlite3_vtab {
5837   const sqlite3_module *pModule;  /* The module for this virtual table */
5838   int nRef;                       /* Number of open cursors */
5839   char *zErrMsg;                  /* Error message from sqlite3_mprintf() */
5840   /* Virtual table implementations will typically add additional fields */
5841 };
5842
5843 /*
5844 ** CAPI3REF: Virtual Table Cursor Object
5845 ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
5846 **
5847 ** Every [virtual table module] implementation uses a subclass of the
5848 ** following structure to describe cursors that point into the
5849 ** [virtual table] and are used
5850 ** to loop through the virtual table.  Cursors are created using the
5851 ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
5852 ** by the [sqlite3_module.xClose | xClose] method.  Cursors are used
5853 ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
5854 ** of the module.  Each module implementation will define
5855 ** the content of a cursor structure to suit its own needs.
5856 **
5857 ** This superclass exists in order to define fields of the cursor that
5858 ** are common to all implementations.
5859 */
5860 struct sqlite3_vtab_cursor {
5861   sqlite3_vtab *pVtab;      /* Virtual table of this cursor */
5862   /* Virtual table implementations will typically add additional fields */
5863 };
5864
5865 /*
5866 ** CAPI3REF: Declare The Schema Of A Virtual Table
5867 **
5868 ** ^The [xCreate] and [xConnect] methods of a
5869 ** [virtual table module] call this interface
5870 ** to declare the format (the names and datatypes of the columns) of
5871 ** the virtual tables they implement.
5872 */
5873 SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3*, const char *zSQL);
5874
5875 /*
5876 ** CAPI3REF: Overload A Function For A Virtual Table
5877 **
5878 ** ^(Virtual tables can provide alternative implementations of functions
5879 ** using the [xFindFunction] method of the [virtual table module].  
5880 ** But global versions of those functions
5881 ** must exist in order to be overloaded.)^
5882 **
5883 ** ^(This API makes sure a global version of a function with a particular
5884 ** name and number of parameters exists.  If no such function exists
5885 ** before this API is called, a new function is created.)^  ^The implementation
5886 ** of the new function always causes an exception to be thrown.  So
5887 ** the new function is not good for anything by itself.  Its only
5888 ** purpose is to be a placeholder function that can be overloaded
5889 ** by a [virtual table].
5890 */
5891 SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
5892
5893 /*
5894 ** The interface to the virtual-table mechanism defined above (back up
5895 ** to a comment remarkably similar to this one) is currently considered
5896 ** to be experimental.  The interface might change in incompatible ways.
5897 ** If this is a problem for you, do not use the interface at this time.
5898 **
5899 ** When the virtual-table mechanism stabilizes, we will declare the
5900 ** interface fixed, support it indefinitely, and remove this comment.
5901 */
5902
5903 /*
5904 ** CAPI3REF: A Handle To An Open BLOB
5905 ** KEYWORDS: {BLOB handle} {BLOB handles}
5906 **
5907 ** An instance of this object represents an open BLOB on which
5908 ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
5909 ** ^Objects of this type are created by [sqlite3_blob_open()]
5910 ** and destroyed by [sqlite3_blob_close()].
5911 ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
5912 ** can be used to read or write small subsections of the BLOB.
5913 ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
5914 */
5915 typedef struct sqlite3_blob sqlite3_blob;
5916
5917 /*
5918 ** CAPI3REF: Open A BLOB For Incremental I/O
5919 **
5920 ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
5921 ** in row iRow, column zColumn, table zTable in database zDb;
5922 ** in other words, the same BLOB that would be selected by:
5923 **
5924 ** <pre>
5925 **     SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
5926 ** </pre>)^
5927 **
5928 ** ^(Parameter zDb is not the filename that contains the database, but 
5929 ** rather the symbolic name of the database. For attached databases, this is
5930 ** the name that appears after the AS keyword in the [ATTACH] statement.
5931 ** For the main database file, the database name is "main". For TEMP
5932 ** tables, the database name is "temp".)^
5933 **
5934 ** ^If the flags parameter is non-zero, then the BLOB is opened for read
5935 ** and write access. ^If the flags parameter is zero, the BLOB is opened for
5936 ** read-only access.
5937 **
5938 ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is stored
5939 ** in *ppBlob. Otherwise an [error code] is returned and, unless the error
5940 ** code is SQLITE_MISUSE, *ppBlob is set to NULL.)^ ^This means that, provided
5941 ** the API is not misused, it is always safe to call [sqlite3_blob_close()] 
5942 ** on *ppBlob after this function it returns.
5943 **
5944 ** This function fails with SQLITE_ERROR if any of the following are true:
5945 ** <ul>
5946 **   <li> ^(Database zDb does not exist)^, 
5947 **   <li> ^(Table zTable does not exist within database zDb)^, 
5948 **   <li> ^(Table zTable is a WITHOUT ROWID table)^, 
5949 **   <li> ^(Column zColumn does not exist)^,
5950 **   <li> ^(Row iRow is not present in the table)^,
5951 **   <li> ^(The specified column of row iRow contains a value that is not
5952 **         a TEXT or BLOB value)^,
5953 **   <li> ^(Column zColumn is part of an index, PRIMARY KEY or UNIQUE 
5954 **         constraint and the blob is being opened for read/write access)^,
5955 **   <li> ^([foreign key constraints | Foreign key constraints] are enabled, 
5956 **         column zColumn is part of a [child key] definition and the blob is
5957 **         being opened for read/write access)^.
5958 ** </ul>
5959 **
5960 ** ^Unless it returns SQLITE_MISUSE, this function sets the 
5961 ** [database connection] error code and message accessible via 
5962 ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. 
5963 **
5964 **
5965 ** ^(If the row that a BLOB handle points to is modified by an
5966 ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
5967 ** then the BLOB handle is marked as "expired".
5968 ** This is true if any column of the row is changed, even a column
5969 ** other than the one the BLOB handle is open on.)^
5970 ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
5971 ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
5972 ** ^(Changes written into a BLOB prior to the BLOB expiring are not
5973 ** rolled back by the expiration of the BLOB.  Such changes will eventually
5974 ** commit if the transaction continues to completion.)^
5975 **
5976 ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
5977 ** the opened blob.  ^The size of a blob may not be changed by this
5978 ** interface.  Use the [UPDATE] SQL command to change the size of a
5979 ** blob.
5980 **
5981 ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
5982 ** and the built-in [zeroblob] SQL function may be used to create a 
5983 ** zero-filled blob to read or write using the incremental-blob interface.
5984 **
5985 ** To avoid a resource leak, every open [BLOB handle] should eventually
5986 ** be released by a call to [sqlite3_blob_close()].
5987 */
5988 SQLITE_API int SQLITE_STDCALL sqlite3_blob_open(
5989   sqlite3*,
5990   const char *zDb,
5991   const char *zTable,
5992   const char *zColumn,
5993   sqlite3_int64 iRow,
5994   int flags,
5995   sqlite3_blob **ppBlob
5996 );
5997
5998 /*
5999 ** CAPI3REF: Move a BLOB Handle to a New Row
6000 **
6001 ** ^This function is used to move an existing blob handle so that it points
6002 ** to a different row of the same database table. ^The new row is identified
6003 ** by the rowid value passed as the second argument. Only the row can be
6004 ** changed. ^The database, table and column on which the blob handle is open
6005 ** remain the same. Moving an existing blob handle to a new row can be
6006 ** faster than closing the existing handle and opening a new one.
6007 **
6008 ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
6009 ** it must exist and there must be either a blob or text value stored in
6010 ** the nominated column.)^ ^If the new row is not present in the table, or if
6011 ** it does not contain a blob or text value, or if another error occurs, an
6012 ** SQLite error code is returned and the blob handle is considered aborted.
6013 ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
6014 ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
6015 ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
6016 ** always returns zero.
6017 **
6018 ** ^This function sets the database handle error code and message.
6019 */
6020 SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
6021
6022 /*
6023 ** CAPI3REF: Close A BLOB Handle
6024 **
6025 ** ^This function closes an open [BLOB handle]. ^(The BLOB handle is closed
6026 ** unconditionally.  Even if this routine returns an error code, the 
6027 ** handle is still closed.)^
6028 **
6029 ** ^If the blob handle being closed was opened for read-write access, and if
6030 ** the database is in auto-commit mode and there are no other open read-write
6031 ** blob handles or active write statements, the current transaction is
6032 ** committed. ^If an error occurs while committing the transaction, an error
6033 ** code is returned and the transaction rolled back.
6034 **
6035 ** Calling this function with an argument that is not a NULL pointer or an
6036 ** open blob handle results in undefined behaviour. ^Calling this routine 
6037 ** with a null pointer (such as would be returned by a failed call to 
6038 ** [sqlite3_blob_open()]) is a harmless no-op. ^Otherwise, if this function
6039 ** is passed a valid open blob handle, the values returned by the 
6040 ** sqlite3_errcode() and sqlite3_errmsg() functions are set before returning.
6041 */
6042 SQLITE_API int SQLITE_STDCALL sqlite3_blob_close(sqlite3_blob *);
6043
6044 /*
6045 ** CAPI3REF: Return The Size Of An Open BLOB
6046 **
6047 ** ^Returns the size in bytes of the BLOB accessible via the 
6048 ** successfully opened [BLOB handle] in its only argument.  ^The
6049 ** incremental blob I/O routines can only read or overwriting existing
6050 ** blob content; they cannot change the size of a blob.
6051 **
6052 ** This routine only works on a [BLOB handle] which has been created
6053 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6054 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6055 ** to this routine results in undefined and probably undesirable behavior.
6056 */
6057 SQLITE_API int SQLITE_STDCALL sqlite3_blob_bytes(sqlite3_blob *);
6058
6059 /*
6060 ** CAPI3REF: Read Data From A BLOB Incrementally
6061 **
6062 ** ^(This function is used to read data from an open [BLOB handle] into a
6063 ** caller-supplied buffer. N bytes of data are copied into buffer Z
6064 ** from the open BLOB, starting at offset iOffset.)^
6065 **
6066 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6067 ** [SQLITE_ERROR] is returned and no data is read.  ^If N or iOffset is
6068 ** less than zero, [SQLITE_ERROR] is returned and no data is read.
6069 ** ^The size of the blob (and hence the maximum value of N+iOffset)
6070 ** can be determined using the [sqlite3_blob_bytes()] interface.
6071 **
6072 ** ^An attempt to read from an expired [BLOB handle] fails with an
6073 ** error code of [SQLITE_ABORT].
6074 **
6075 ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
6076 ** Otherwise, an [error code] or an [extended error code] is returned.)^
6077 **
6078 ** This routine only works on a [BLOB handle] which has been created
6079 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6080 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6081 ** to this routine results in undefined and probably undesirable behavior.
6082 **
6083 ** See also: [sqlite3_blob_write()].
6084 */
6085 SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
6086
6087 /*
6088 ** CAPI3REF: Write Data Into A BLOB Incrementally
6089 **
6090 ** ^(This function is used to write data into an open [BLOB handle] from a
6091 ** caller-supplied buffer. N bytes of data are copied from the buffer Z
6092 ** into the open BLOB, starting at offset iOffset.)^
6093 **
6094 ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
6095 ** Otherwise, an  [error code] or an [extended error code] is returned.)^
6096 ** ^Unless SQLITE_MISUSE is returned, this function sets the 
6097 ** [database connection] error code and message accessible via 
6098 ** [sqlite3_errcode()] and [sqlite3_errmsg()] and related functions. 
6099 **
6100 ** ^If the [BLOB handle] passed as the first argument was not opened for
6101 ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
6102 ** this function returns [SQLITE_READONLY].
6103 **
6104 ** This function may only modify the contents of the BLOB; it is
6105 ** not possible to increase the size of a BLOB using this API.
6106 ** ^If offset iOffset is less than N bytes from the end of the BLOB,
6107 ** [SQLITE_ERROR] is returned and no data is written. The size of the 
6108 ** BLOB (and hence the maximum value of N+iOffset) can be determined 
6109 ** using the [sqlite3_blob_bytes()] interface. ^If N or iOffset are less 
6110 ** than zero [SQLITE_ERROR] is returned and no data is written.
6111 **
6112 ** ^An attempt to write to an expired [BLOB handle] fails with an
6113 ** error code of [SQLITE_ABORT].  ^Writes to the BLOB that occurred
6114 ** before the [BLOB handle] expired are not rolled back by the
6115 ** expiration of the handle, though of course those changes might
6116 ** have been overwritten by the statement that expired the BLOB handle
6117 ** or by other independent statements.
6118 **
6119 ** This routine only works on a [BLOB handle] which has been created
6120 ** by a prior successful call to [sqlite3_blob_open()] and which has not
6121 ** been closed by [sqlite3_blob_close()].  Passing any other pointer in
6122 ** to this routine results in undefined and probably undesirable behavior.
6123 **
6124 ** See also: [sqlite3_blob_read()].
6125 */
6126 SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
6127
6128 /*
6129 ** CAPI3REF: Virtual File System Objects
6130 **
6131 ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
6132 ** that SQLite uses to interact
6133 ** with the underlying operating system.  Most SQLite builds come with a
6134 ** single default VFS that is appropriate for the host computer.
6135 ** New VFSes can be registered and existing VFSes can be unregistered.
6136 ** The following interfaces are provided.
6137 **
6138 ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
6139 ** ^Names are case sensitive.
6140 ** ^Names are zero-terminated UTF-8 strings.
6141 ** ^If there is no match, a NULL pointer is returned.
6142 ** ^If zVfsName is NULL then the default VFS is returned.
6143 **
6144 ** ^New VFSes are registered with sqlite3_vfs_register().
6145 ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
6146 ** ^The same VFS can be registered multiple times without injury.
6147 ** ^To make an existing VFS into the default VFS, register it again
6148 ** with the makeDflt flag set.  If two different VFSes with the
6149 ** same name are registered, the behavior is undefined.  If a
6150 ** VFS is registered with a name that is NULL or an empty string,
6151 ** then the behavior is undefined.
6152 **
6153 ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
6154 ** ^(If the default VFS is unregistered, another VFS is chosen as
6155 ** the default.  The choice for the new VFS is arbitrary.)^
6156 */
6157 SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfsName);
6158 SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
6159 SQLITE_API int SQLITE_STDCALL sqlite3_vfs_unregister(sqlite3_vfs*);
6160
6161 /*
6162 ** CAPI3REF: Mutexes
6163 **
6164 ** The SQLite core uses these routines for thread
6165 ** synchronization. Though they are intended for internal
6166 ** use by SQLite, code that links against SQLite is
6167 ** permitted to use any of these routines.
6168 **
6169 ** The SQLite source code contains multiple implementations
6170 ** of these mutex routines.  An appropriate implementation
6171 ** is selected automatically at compile-time.  The following
6172 ** implementations are available in the SQLite core:
6173 **
6174 ** <ul>
6175 ** <li>   SQLITE_MUTEX_PTHREADS
6176 ** <li>   SQLITE_MUTEX_W32
6177 ** <li>   SQLITE_MUTEX_NOOP
6178 ** </ul>
6179 **
6180 ** The SQLITE_MUTEX_NOOP implementation is a set of routines
6181 ** that does no real locking and is appropriate for use in
6182 ** a single-threaded application.  The SQLITE_MUTEX_PTHREADS and
6183 ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
6184 ** and Windows.
6185 **
6186 ** If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
6187 ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
6188 ** implementation is included with the library. In this case the
6189 ** application must supply a custom mutex implementation using the
6190 ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
6191 ** before calling sqlite3_initialize() or any other public sqlite3_
6192 ** function that calls sqlite3_initialize().
6193 **
6194 ** ^The sqlite3_mutex_alloc() routine allocates a new
6195 ** mutex and returns a pointer to it. ^The sqlite3_mutex_alloc()
6196 ** routine returns NULL if it is unable to allocate the requested
6197 ** mutex.  The argument to sqlite3_mutex_alloc() must one of these
6198 ** integer constants:
6199 **
6200 ** <ul>
6201 ** <li>  SQLITE_MUTEX_FAST
6202 ** <li>  SQLITE_MUTEX_RECURSIVE
6203 ** <li>  SQLITE_MUTEX_STATIC_MASTER
6204 ** <li>  SQLITE_MUTEX_STATIC_MEM
6205 ** <li>  SQLITE_MUTEX_STATIC_OPEN
6206 ** <li>  SQLITE_MUTEX_STATIC_PRNG
6207 ** <li>  SQLITE_MUTEX_STATIC_LRU
6208 ** <li>  SQLITE_MUTEX_STATIC_PMEM
6209 ** <li>  SQLITE_MUTEX_STATIC_APP1
6210 ** <li>  SQLITE_MUTEX_STATIC_APP2
6211 ** <li>  SQLITE_MUTEX_STATIC_APP3
6212 ** </ul>
6213 **
6214 ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
6215 ** cause sqlite3_mutex_alloc() to create
6216 ** a new mutex.  ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
6217 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
6218 ** The mutex implementation does not need to make a distinction
6219 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
6220 ** not want to.  SQLite will only request a recursive mutex in
6221 ** cases where it really needs one.  If a faster non-recursive mutex
6222 ** implementation is available on the host platform, the mutex subsystem
6223 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
6224 **
6225 ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
6226 ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
6227 ** a pointer to a static preexisting mutex.  ^Nine static mutexes are
6228 ** used by the current version of SQLite.  Future versions of SQLite
6229 ** may add additional static mutexes.  Static mutexes are for internal
6230 ** use by SQLite only.  Applications that use SQLite mutexes should
6231 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
6232 ** SQLITE_MUTEX_RECURSIVE.
6233 **
6234 ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
6235 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
6236 ** returns a different mutex on every call.  ^For the static
6237 ** mutex types, the same mutex is returned on every call that has
6238 ** the same type number.
6239 **
6240 ** ^The sqlite3_mutex_free() routine deallocates a previously
6241 ** allocated dynamic mutex.  Attempting to deallocate a static
6242 ** mutex results in undefined behavior.
6243 **
6244 ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
6245 ** to enter a mutex.  ^If another thread is already within the mutex,
6246 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
6247 ** SQLITE_BUSY.  ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
6248 ** upon successful entry.  ^(Mutexes created using
6249 ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
6250 ** In such cases, the
6251 ** mutex must be exited an equal number of times before another thread
6252 ** can enter.)^  If the same thread tries to enter any mutex other
6253 ** than an SQLITE_MUTEX_RECURSIVE more than once, the behavior is undefined.
6254 **
6255 ** ^(Some systems (for example, Windows 95) do not support the operation
6256 ** implemented by sqlite3_mutex_try().  On those systems, sqlite3_mutex_try()
6257 ** will always return SQLITE_BUSY. The SQLite core only ever uses
6258 ** sqlite3_mutex_try() as an optimization so this is acceptable 
6259 ** behavior.)^
6260 **
6261 ** ^The sqlite3_mutex_leave() routine exits a mutex that was
6262 ** previously entered by the same thread.   The behavior
6263 ** is undefined if the mutex is not currently entered by the
6264 ** calling thread or is not currently allocated.
6265 **
6266 ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
6267 ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
6268 ** behave as no-ops.
6269 **
6270 ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
6271 */
6272 SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_mutex_alloc(int);
6273 SQLITE_API void SQLITE_STDCALL sqlite3_mutex_free(sqlite3_mutex*);
6274 SQLITE_API void SQLITE_STDCALL sqlite3_mutex_enter(sqlite3_mutex*);
6275 SQLITE_API int SQLITE_STDCALL sqlite3_mutex_try(sqlite3_mutex*);
6276 SQLITE_API void SQLITE_STDCALL sqlite3_mutex_leave(sqlite3_mutex*);
6277
6278 /*
6279 ** CAPI3REF: Mutex Methods Object
6280 **
6281 ** An instance of this structure defines the low-level routines
6282 ** used to allocate and use mutexes.
6283 **
6284 ** Usually, the default mutex implementations provided by SQLite are
6285 ** sufficient, however the application has the option of substituting a custom
6286 ** implementation for specialized deployments or systems for which SQLite
6287 ** does not provide a suitable implementation. In this case, the application
6288 ** creates and populates an instance of this structure to pass
6289 ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
6290 ** Additionally, an instance of this structure can be used as an
6291 ** output variable when querying the system for the current mutex
6292 ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
6293 **
6294 ** ^The xMutexInit method defined by this structure is invoked as
6295 ** part of system initialization by the sqlite3_initialize() function.
6296 ** ^The xMutexInit routine is called by SQLite exactly once for each
6297 ** effective call to [sqlite3_initialize()].
6298 **
6299 ** ^The xMutexEnd method defined by this structure is invoked as
6300 ** part of system shutdown by the sqlite3_shutdown() function. The
6301 ** implementation of this method is expected to release all outstanding
6302 ** resources obtained by the mutex methods implementation, especially
6303 ** those obtained by the xMutexInit method.  ^The xMutexEnd()
6304 ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
6305 **
6306 ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
6307 ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
6308 ** xMutexNotheld) implement the following interfaces (respectively):
6309 **
6310 ** <ul>
6311 **   <li>  [sqlite3_mutex_alloc()] </li>
6312 **   <li>  [sqlite3_mutex_free()] </li>
6313 **   <li>  [sqlite3_mutex_enter()] </li>
6314 **   <li>  [sqlite3_mutex_try()] </li>
6315 **   <li>  [sqlite3_mutex_leave()] </li>
6316 **   <li>  [sqlite3_mutex_held()] </li>
6317 **   <li>  [sqlite3_mutex_notheld()] </li>
6318 ** </ul>)^
6319 **
6320 ** The only difference is that the public sqlite3_XXX functions enumerated
6321 ** above silently ignore any invocations that pass a NULL pointer instead
6322 ** of a valid mutex handle. The implementations of the methods defined
6323 ** by this structure are not required to handle this case, the results
6324 ** of passing a NULL pointer instead of a valid mutex handle are undefined
6325 ** (i.e. it is acceptable to provide an implementation that segfaults if
6326 ** it is passed a NULL pointer).
6327 **
6328 ** The xMutexInit() method must be threadsafe.  It must be harmless to
6329 ** invoke xMutexInit() multiple times within the same process and without
6330 ** intervening calls to xMutexEnd().  Second and subsequent calls to
6331 ** xMutexInit() must be no-ops.
6332 **
6333 ** xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
6334 ** and its associates).  Similarly, xMutexAlloc() must not use SQLite memory
6335 ** allocation for a static mutex.  ^However xMutexAlloc() may use SQLite
6336 ** memory allocation for a fast or recursive mutex.
6337 **
6338 ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
6339 ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
6340 ** If xMutexInit fails in any way, it is expected to clean up after itself
6341 ** prior to returning.
6342 */
6343 typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
6344 struct sqlite3_mutex_methods {
6345   int (*xMutexInit)(void);
6346   int (*xMutexEnd)(void);
6347   sqlite3_mutex *(*xMutexAlloc)(int);
6348   void (*xMutexFree)(sqlite3_mutex *);
6349   void (*xMutexEnter)(sqlite3_mutex *);
6350   int (*xMutexTry)(sqlite3_mutex *);
6351   void (*xMutexLeave)(sqlite3_mutex *);
6352   int (*xMutexHeld)(sqlite3_mutex *);
6353   int (*xMutexNotheld)(sqlite3_mutex *);
6354 };
6355
6356 /*
6357 ** CAPI3REF: Mutex Verification Routines
6358 **
6359 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
6360 ** are intended for use inside assert() statements.  The SQLite core
6361 ** never uses these routines except inside an assert() and applications
6362 ** are advised to follow the lead of the core.  The SQLite core only
6363 ** provides implementations for these routines when it is compiled
6364 ** with the SQLITE_DEBUG flag.  External mutex implementations
6365 ** are only required to provide these routines if SQLITE_DEBUG is
6366 ** defined and if NDEBUG is not defined.
6367 **
6368 ** These routines should return true if the mutex in their argument
6369 ** is held or not held, respectively, by the calling thread.
6370 **
6371 ** The implementation is not required to provide versions of these
6372 ** routines that actually work. If the implementation does not provide working
6373 ** versions of these routines, it should at least provide stubs that always
6374 ** return true so that one does not get spurious assertion failures.
6375 **
6376 ** If the argument to sqlite3_mutex_held() is a NULL pointer then
6377 ** the routine should return 1.   This seems counter-intuitive since
6378 ** clearly the mutex cannot be held if it does not exist.  But
6379 ** the reason the mutex does not exist is because the build is not
6380 ** using mutexes.  And we do not want the assert() containing the
6381 ** call to sqlite3_mutex_held() to fail, so a non-zero return is
6382 ** the appropriate thing to do.  The sqlite3_mutex_notheld()
6383 ** interface should also return 1 when given a NULL pointer.
6384 */
6385 #ifndef NDEBUG
6386 SQLITE_API int SQLITE_STDCALL sqlite3_mutex_held(sqlite3_mutex*);
6387 SQLITE_API int SQLITE_STDCALL sqlite3_mutex_notheld(sqlite3_mutex*);
6388 #endif
6389
6390 /*
6391 ** CAPI3REF: Mutex Types
6392 **
6393 ** The [sqlite3_mutex_alloc()] interface takes a single argument
6394 ** which is one of these integer constants.
6395 **
6396 ** The set of static mutexes may change from one SQLite release to the
6397 ** next.  Applications that override the built-in mutex logic must be
6398 ** prepared to accommodate additional static mutexes.
6399 */
6400 #define SQLITE_MUTEX_FAST             0
6401 #define SQLITE_MUTEX_RECURSIVE        1
6402 #define SQLITE_MUTEX_STATIC_MASTER    2
6403 #define SQLITE_MUTEX_STATIC_MEM       3  /* sqlite3_malloc() */
6404 #define SQLITE_MUTEX_STATIC_MEM2      4  /* NOT USED */
6405 #define SQLITE_MUTEX_STATIC_OPEN      4  /* sqlite3BtreeOpen() */
6406 #define SQLITE_MUTEX_STATIC_PRNG      5  /* sqlite3_random() */
6407 #define SQLITE_MUTEX_STATIC_LRU       6  /* lru page list */
6408 #define SQLITE_MUTEX_STATIC_LRU2      7  /* NOT USED */
6409 #define SQLITE_MUTEX_STATIC_PMEM      7  /* sqlite3PageMalloc() */
6410 #define SQLITE_MUTEX_STATIC_APP1      8  /* For use by application */
6411 #define SQLITE_MUTEX_STATIC_APP2      9  /* For use by application */
6412 #define SQLITE_MUTEX_STATIC_APP3     10  /* For use by application */
6413
6414 /*
6415 ** CAPI3REF: Retrieve the mutex for a database connection
6416 **
6417 ** ^This interface returns a pointer the [sqlite3_mutex] object that 
6418 ** serializes access to the [database connection] given in the argument
6419 ** when the [threading mode] is Serialized.
6420 ** ^If the [threading mode] is Single-thread or Multi-thread then this
6421 ** routine returns a NULL pointer.
6422 */
6423 SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_db_mutex(sqlite3*);
6424
6425 /*
6426 ** CAPI3REF: Low-Level Control Of Database Files
6427 **
6428 ** ^The [sqlite3_file_control()] interface makes a direct call to the
6429 ** xFileControl method for the [sqlite3_io_methods] object associated
6430 ** with a particular database identified by the second argument. ^The
6431 ** name of the database is "main" for the main database or "temp" for the
6432 ** TEMP database, or the name that appears after the AS keyword for
6433 ** databases that are added using the [ATTACH] SQL command.
6434 ** ^A NULL pointer can be used in place of "main" to refer to the
6435 ** main database file.
6436 ** ^The third and fourth parameters to this routine
6437 ** are passed directly through to the second and third parameters of
6438 ** the xFileControl method.  ^The return value of the xFileControl
6439 ** method becomes the return value of this routine.
6440 **
6441 ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
6442 ** a pointer to the underlying [sqlite3_file] object to be written into
6443 ** the space pointed to by the 4th parameter.  ^The SQLITE_FCNTL_FILE_POINTER
6444 ** case is a short-circuit path which does not actually invoke the
6445 ** underlying sqlite3_io_methods.xFileControl method.
6446 **
6447 ** ^If the second parameter (zDbName) does not match the name of any
6448 ** open database file, then SQLITE_ERROR is returned.  ^This error
6449 ** code is not remembered and will not be recalled by [sqlite3_errcode()]
6450 ** or [sqlite3_errmsg()].  The underlying xFileControl method might
6451 ** also return SQLITE_ERROR.  There is no way to distinguish between
6452 ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
6453 ** xFileControl method.
6454 **
6455 ** See also: [SQLITE_FCNTL_LOCKSTATE]
6456 */
6457 SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
6458
6459 /*
6460 ** CAPI3REF: Testing Interface
6461 **
6462 ** ^The sqlite3_test_control() interface is used to read out internal
6463 ** state of SQLite and to inject faults into SQLite for testing
6464 ** purposes.  ^The first parameter is an operation code that determines
6465 ** the number, meaning, and operation of all subsequent parameters.
6466 **
6467 ** This interface is not for use by applications.  It exists solely
6468 ** for verifying the correct operation of the SQLite library.  Depending
6469 ** on how the SQLite library is compiled, this interface might not exist.
6470 **
6471 ** The details of the operation codes, their meanings, the parameters
6472 ** they take, and what they do are all subject to change without notice.
6473 ** Unlike most of the SQLite API, this function is not guaranteed to
6474 ** operate consistently from one release to the next.
6475 */
6476 SQLITE_API int SQLITE_CDECL sqlite3_test_control(int op, ...);
6477
6478 /*
6479 ** CAPI3REF: Testing Interface Operation Codes
6480 **
6481 ** These constants are the valid operation code parameters used
6482 ** as the first argument to [sqlite3_test_control()].
6483 **
6484 ** These parameters and their meanings are subject to change
6485 ** without notice.  These values are for testing purposes only.
6486 ** Applications should not use any of these parameters or the
6487 ** [sqlite3_test_control()] interface.
6488 */
6489 #define SQLITE_TESTCTRL_FIRST                    5
6490 #define SQLITE_TESTCTRL_PRNG_SAVE                5
6491 #define SQLITE_TESTCTRL_PRNG_RESTORE             6
6492 #define SQLITE_TESTCTRL_PRNG_RESET               7
6493 #define SQLITE_TESTCTRL_BITVEC_TEST              8
6494 #define SQLITE_TESTCTRL_FAULT_INSTALL            9
6495 #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS     10
6496 #define SQLITE_TESTCTRL_PENDING_BYTE            11
6497 #define SQLITE_TESTCTRL_ASSERT                  12
6498 #define SQLITE_TESTCTRL_ALWAYS                  13
6499 #define SQLITE_TESTCTRL_RESERVE                 14
6500 #define SQLITE_TESTCTRL_OPTIMIZATIONS           15
6501 #define SQLITE_TESTCTRL_ISKEYWORD               16
6502 #define SQLITE_TESTCTRL_SCRATCHMALLOC           17
6503 #define SQLITE_TESTCTRL_LOCALTIME_FAULT         18
6504 #define SQLITE_TESTCTRL_EXPLAIN_STMT            19  /* NOT USED */
6505 #define SQLITE_TESTCTRL_NEVER_CORRUPT           20
6506 #define SQLITE_TESTCTRL_VDBE_COVERAGE           21
6507 #define SQLITE_TESTCTRL_BYTEORDER               22
6508 #define SQLITE_TESTCTRL_ISINIT                  23
6509 #define SQLITE_TESTCTRL_SORTER_MMAP             24
6510 #define SQLITE_TESTCTRL_IMPOSTER                25
6511 #define SQLITE_TESTCTRL_LAST                    25
6512
6513 /*
6514 ** CAPI3REF: SQLite Runtime Status
6515 **
6516 ** ^These interfaces are used to retrieve runtime status information
6517 ** about the performance of SQLite, and optionally to reset various
6518 ** highwater marks.  ^The first argument is an integer code for
6519 ** the specific parameter to measure.  ^(Recognized integer codes
6520 ** are of the form [status parameters | SQLITE_STATUS_...].)^
6521 ** ^The current value of the parameter is returned into *pCurrent.
6522 ** ^The highest recorded value is returned in *pHighwater.  ^If the
6523 ** resetFlag is true, then the highest record value is reset after
6524 ** *pHighwater is written.  ^(Some parameters do not record the highest
6525 ** value.  For those parameters
6526 ** nothing is written into *pHighwater and the resetFlag is ignored.)^
6527 ** ^(Other parameters record only the highwater mark and not the current
6528 ** value.  For these latter parameters nothing is written into *pCurrent.)^
6529 **
6530 ** ^The sqlite3_status() and sqlite3_status64() routines return
6531 ** SQLITE_OK on success and a non-zero [error code] on failure.
6532 **
6533 ** If either the current value or the highwater mark is too large to
6534 ** be represented by a 32-bit integer, then the values returned by
6535 ** sqlite3_status() are undefined.
6536 **
6537 ** See also: [sqlite3_db_status()]
6538 */
6539 SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
6540 SQLITE_API int SQLITE_STDCALL sqlite3_status64(
6541   int op,
6542   sqlite3_int64 *pCurrent,
6543   sqlite3_int64 *pHighwater,
6544   int resetFlag
6545 );
6546
6547
6548 /*
6549 ** CAPI3REF: Status Parameters
6550 ** KEYWORDS: {status parameters}
6551 **
6552 ** These integer constants designate various run-time status parameters
6553 ** that can be returned by [sqlite3_status()].
6554 **
6555 ** <dl>
6556 ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
6557 ** <dd>This parameter is the current amount of memory checked out
6558 ** using [sqlite3_malloc()], either directly or indirectly.  The
6559 ** figure includes calls made to [sqlite3_malloc()] by the application
6560 ** and internal memory usage by the SQLite library.  Scratch memory
6561 ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
6562 ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
6563 ** this parameter.  The amount returned is the sum of the allocation
6564 ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
6565 **
6566 ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
6567 ** <dd>This parameter records the largest memory allocation request
6568 ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
6569 ** internal equivalents).  Only the value returned in the
6570 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6571 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6572 **
6573 ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
6574 ** <dd>This parameter records the number of separate memory allocations
6575 ** currently checked out.</dd>)^
6576 **
6577 ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
6578 ** <dd>This parameter returns the number of pages used out of the
6579 ** [pagecache memory allocator] that was configured using 
6580 ** [SQLITE_CONFIG_PAGECACHE].  The
6581 ** value returned is in pages, not in bytes.</dd>)^
6582 **
6583 ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]] 
6584 ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
6585 ** <dd>This parameter returns the number of bytes of page cache
6586 ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
6587 ** buffer and where forced to overflow to [sqlite3_malloc()].  The
6588 ** returned value includes allocations that overflowed because they
6589 ** where too large (they were larger than the "sz" parameter to
6590 ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
6591 ** no space was left in the page cache.</dd>)^
6592 **
6593 ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
6594 ** <dd>This parameter records the largest memory allocation request
6595 ** handed to [pagecache memory allocator].  Only the value returned in the
6596 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6597 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6598 **
6599 ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
6600 ** <dd>This parameter returns the number of allocations used out of the
6601 ** [scratch memory allocator] configured using
6602 ** [SQLITE_CONFIG_SCRATCH].  The value returned is in allocations, not
6603 ** in bytes.  Since a single thread may only have one scratch allocation
6604 ** outstanding at time, this parameter also reports the number of threads
6605 ** using scratch memory at the same time.</dd>)^
6606 **
6607 ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
6608 ** <dd>This parameter returns the number of bytes of scratch memory
6609 ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
6610 ** buffer and where forced to overflow to [sqlite3_malloc()].  The values
6611 ** returned include overflows because the requested allocation was too
6612 ** larger (that is, because the requested allocation was larger than the
6613 ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
6614 ** slots were available.
6615 ** </dd>)^
6616 **
6617 ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
6618 ** <dd>This parameter records the largest memory allocation request
6619 ** handed to [scratch memory allocator].  Only the value returned in the
6620 ** *pHighwater parameter to [sqlite3_status()] is of interest.  
6621 ** The value written into the *pCurrent parameter is undefined.</dd>)^
6622 **
6623 ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
6624 ** <dd>This parameter records the deepest parser stack.  It is only
6625 ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
6626 ** </dl>
6627 **
6628 ** New status parameters may be added from time to time.
6629 */
6630 #define SQLITE_STATUS_MEMORY_USED          0
6631 #define SQLITE_STATUS_PAGECACHE_USED       1
6632 #define SQLITE_STATUS_PAGECACHE_OVERFLOW   2
6633 #define SQLITE_STATUS_SCRATCH_USED         3
6634 #define SQLITE_STATUS_SCRATCH_OVERFLOW     4
6635 #define SQLITE_STATUS_MALLOC_SIZE          5
6636 #define SQLITE_STATUS_PARSER_STACK         6
6637 #define SQLITE_STATUS_PAGECACHE_SIZE       7
6638 #define SQLITE_STATUS_SCRATCH_SIZE         8
6639 #define SQLITE_STATUS_MALLOC_COUNT         9
6640
6641 /*
6642 ** CAPI3REF: Database Connection Status
6643 **
6644 ** ^This interface is used to retrieve runtime status information 
6645 ** about a single [database connection].  ^The first argument is the
6646 ** database connection object to be interrogated.  ^The second argument
6647 ** is an integer constant, taken from the set of
6648 ** [SQLITE_DBSTATUS options], that
6649 ** determines the parameter to interrogate.  The set of 
6650 ** [SQLITE_DBSTATUS options] is likely
6651 ** to grow in future releases of SQLite.
6652 **
6653 ** ^The current value of the requested parameter is written into *pCur
6654 ** and the highest instantaneous value is written into *pHiwtr.  ^If
6655 ** the resetFlg is true, then the highest instantaneous value is
6656 ** reset back down to the current value.
6657 **
6658 ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
6659 ** non-zero [error code] on failure.
6660 **
6661 ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
6662 */
6663 SQLITE_API int SQLITE_STDCALL sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
6664
6665 /*
6666 ** CAPI3REF: Status Parameters for database connections
6667 ** KEYWORDS: {SQLITE_DBSTATUS options}
6668 **
6669 ** These constants are the available integer "verbs" that can be passed as
6670 ** the second argument to the [sqlite3_db_status()] interface.
6671 **
6672 ** New verbs may be added in future releases of SQLite. Existing verbs
6673 ** might be discontinued. Applications should check the return code from
6674 ** [sqlite3_db_status()] to make sure that the call worked.
6675 ** The [sqlite3_db_status()] interface will return a non-zero error code
6676 ** if a discontinued or unsupported verb is invoked.
6677 **
6678 ** <dl>
6679 ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
6680 ** <dd>This parameter returns the number of lookaside memory slots currently
6681 ** checked out.</dd>)^
6682 **
6683 ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
6684 ** <dd>This parameter returns the number malloc attempts that were 
6685 ** satisfied using lookaside memory. Only the high-water value is meaningful;
6686 ** the current value is always zero.)^
6687 **
6688 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
6689 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
6690 ** <dd>This parameter returns the number malloc attempts that might have
6691 ** been satisfied using lookaside memory but failed due to the amount of
6692 ** memory requested being larger than the lookaside slot size.
6693 ** Only the high-water value is meaningful;
6694 ** the current value is always zero.)^
6695 **
6696 ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
6697 ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
6698 ** <dd>This parameter returns the number malloc attempts that might have
6699 ** been satisfied using lookaside memory but failed due to all lookaside
6700 ** memory already being in use.
6701 ** Only the high-water value is meaningful;
6702 ** the current value is always zero.)^
6703 **
6704 ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
6705 ** <dd>This parameter returns the approximate number of bytes of heap
6706 ** memory used by all pager caches associated with the database connection.)^
6707 ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
6708 **
6709 ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
6710 ** <dd>This parameter returns the approximate number of bytes of heap
6711 ** memory used to store the schema for all databases associated
6712 ** with the connection - main, temp, and any [ATTACH]-ed databases.)^ 
6713 ** ^The full amount of memory used by the schemas is reported, even if the
6714 ** schema memory is shared with other database connections due to
6715 ** [shared cache mode] being enabled.
6716 ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
6717 **
6718 ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
6719 ** <dd>This parameter returns the approximate number of bytes of heap
6720 ** and lookaside memory used by all prepared statements associated with
6721 ** the database connection.)^
6722 ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
6723 ** </dd>
6724 **
6725 ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
6726 ** <dd>This parameter returns the number of pager cache hits that have
6727 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT 
6728 ** is always 0.
6729 ** </dd>
6730 **
6731 ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
6732 ** <dd>This parameter returns the number of pager cache misses that have
6733 ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS 
6734 ** is always 0.
6735 ** </dd>
6736 **
6737 ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
6738 ** <dd>This parameter returns the number of dirty cache entries that have
6739 ** been written to disk. Specifically, the number of pages written to the
6740 ** wal file in wal mode databases, or the number of pages written to the
6741 ** database file in rollback mode databases. Any pages written as part of
6742 ** transaction rollback or database recovery operations are not included.
6743 ** If an IO or other error occurs while writing a page to disk, the effect
6744 ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
6745 ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
6746 ** </dd>
6747 **
6748 ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
6749 ** <dd>This parameter returns zero for the current value if and only if
6750 ** all foreign key constraints (deferred or immediate) have been
6751 ** resolved.)^  ^The highwater mark is always 0.
6752 ** </dd>
6753 ** </dl>
6754 */
6755 #define SQLITE_DBSTATUS_LOOKASIDE_USED       0
6756 #define SQLITE_DBSTATUS_CACHE_USED           1
6757 #define SQLITE_DBSTATUS_SCHEMA_USED          2
6758 #define SQLITE_DBSTATUS_STMT_USED            3
6759 #define SQLITE_DBSTATUS_LOOKASIDE_HIT        4
6760 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE  5
6761 #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL  6
6762 #define SQLITE_DBSTATUS_CACHE_HIT            7
6763 #define SQLITE_DBSTATUS_CACHE_MISS           8
6764 #define SQLITE_DBSTATUS_CACHE_WRITE          9
6765 #define SQLITE_DBSTATUS_DEFERRED_FKS        10
6766 #define SQLITE_DBSTATUS_MAX                 10   /* Largest defined DBSTATUS */
6767
6768
6769 /*
6770 ** CAPI3REF: Prepared Statement Status
6771 **
6772 ** ^(Each prepared statement maintains various
6773 ** [SQLITE_STMTSTATUS counters] that measure the number
6774 ** of times it has performed specific operations.)^  These counters can
6775 ** be used to monitor the performance characteristics of the prepared
6776 ** statements.  For example, if the number of table steps greatly exceeds
6777 ** the number of table searches or result rows, that would tend to indicate
6778 ** that the prepared statement is using a full table scan rather than
6779 ** an index.  
6780 **
6781 ** ^(This interface is used to retrieve and reset counter values from
6782 ** a [prepared statement].  The first argument is the prepared statement
6783 ** object to be interrogated.  The second argument
6784 ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
6785 ** to be interrogated.)^
6786 ** ^The current value of the requested counter is returned.
6787 ** ^If the resetFlg is true, then the counter is reset to zero after this
6788 ** interface call returns.
6789 **
6790 ** See also: [sqlite3_status()] and [sqlite3_db_status()].
6791 */
6792 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
6793
6794 /*
6795 ** CAPI3REF: Status Parameters for prepared statements
6796 ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
6797 **
6798 ** These preprocessor macros define integer codes that name counter
6799 ** values associated with the [sqlite3_stmt_status()] interface.
6800 ** The meanings of the various counters are as follows:
6801 **
6802 ** <dl>
6803 ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
6804 ** <dd>^This is the number of times that SQLite has stepped forward in
6805 ** a table as part of a full table scan.  Large numbers for this counter
6806 ** may indicate opportunities for performance improvement through 
6807 ** careful use of indices.</dd>
6808 **
6809 ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
6810 ** <dd>^This is the number of sort operations that have occurred.
6811 ** A non-zero value in this counter may indicate an opportunity to
6812 ** improvement performance through careful use of indices.</dd>
6813 **
6814 ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
6815 ** <dd>^This is the number of rows inserted into transient indices that
6816 ** were created automatically in order to help joins run faster.
6817 ** A non-zero value in this counter may indicate an opportunity to
6818 ** improvement performance by adding permanent indices that do not
6819 ** need to be reinitialized each time the statement is run.</dd>
6820 **
6821 ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
6822 ** <dd>^This is the number of virtual machine operations executed
6823 ** by the prepared statement if that number is less than or equal
6824 ** to 2147483647.  The number of virtual machine operations can be 
6825 ** used as a proxy for the total work done by the prepared statement.
6826 ** If the number of virtual machine operations exceeds 2147483647
6827 ** then the value returned by this statement status code is undefined.
6828 ** </dd>
6829 ** </dl>
6830 */
6831 #define SQLITE_STMTSTATUS_FULLSCAN_STEP     1
6832 #define SQLITE_STMTSTATUS_SORT              2
6833 #define SQLITE_STMTSTATUS_AUTOINDEX         3
6834 #define SQLITE_STMTSTATUS_VM_STEP           4
6835
6836 /*
6837 ** CAPI3REF: Custom Page Cache Object
6838 **
6839 ** The sqlite3_pcache type is opaque.  It is implemented by
6840 ** the pluggable module.  The SQLite core has no knowledge of
6841 ** its size or internal structure and never deals with the
6842 ** sqlite3_pcache object except by holding and passing pointers
6843 ** to the object.
6844 **
6845 ** See [sqlite3_pcache_methods2] for additional information.
6846 */
6847 typedef struct sqlite3_pcache sqlite3_pcache;
6848
6849 /*
6850 ** CAPI3REF: Custom Page Cache Object
6851 **
6852 ** The sqlite3_pcache_page object represents a single page in the
6853 ** page cache.  The page cache will allocate instances of this
6854 ** object.  Various methods of the page cache use pointers to instances
6855 ** of this object as parameters or as their return value.
6856 **
6857 ** See [sqlite3_pcache_methods2] for additional information.
6858 */
6859 typedef struct sqlite3_pcache_page sqlite3_pcache_page;
6860 struct sqlite3_pcache_page {
6861   void *pBuf;        /* The content of the page */
6862   void *pExtra;      /* Extra information associated with the page */
6863 };
6864
6865 /*
6866 ** CAPI3REF: Application Defined Page Cache.
6867 ** KEYWORDS: {page cache}
6868 **
6869 ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
6870 ** register an alternative page cache implementation by passing in an 
6871 ** instance of the sqlite3_pcache_methods2 structure.)^
6872 ** In many applications, most of the heap memory allocated by 
6873 ** SQLite is used for the page cache.
6874 ** By implementing a 
6875 ** custom page cache using this API, an application can better control
6876 ** the amount of memory consumed by SQLite, the way in which 
6877 ** that memory is allocated and released, and the policies used to 
6878 ** determine exactly which parts of a database file are cached and for 
6879 ** how long.
6880 **
6881 ** The alternative page cache mechanism is an
6882 ** extreme measure that is only needed by the most demanding applications.
6883 ** The built-in page cache is recommended for most uses.
6884 **
6885 ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
6886 ** internal buffer by SQLite within the call to [sqlite3_config].  Hence
6887 ** the application may discard the parameter after the call to
6888 ** [sqlite3_config()] returns.)^
6889 **
6890 ** [[the xInit() page cache method]]
6891 ** ^(The xInit() method is called once for each effective 
6892 ** call to [sqlite3_initialize()])^
6893 ** (usually only once during the lifetime of the process). ^(The xInit()
6894 ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
6895 ** The intent of the xInit() method is to set up global data structures 
6896 ** required by the custom page cache implementation. 
6897 ** ^(If the xInit() method is NULL, then the 
6898 ** built-in default page cache is used instead of the application defined
6899 ** page cache.)^
6900 **
6901 ** [[the xShutdown() page cache method]]
6902 ** ^The xShutdown() method is called by [sqlite3_shutdown()].
6903 ** It can be used to clean up 
6904 ** any outstanding resources before process shutdown, if required.
6905 ** ^The xShutdown() method may be NULL.
6906 **
6907 ** ^SQLite automatically serializes calls to the xInit method,
6908 ** so the xInit method need not be threadsafe.  ^The
6909 ** xShutdown method is only called from [sqlite3_shutdown()] so it does
6910 ** not need to be threadsafe either.  All other methods must be threadsafe
6911 ** in multithreaded applications.
6912 **
6913 ** ^SQLite will never invoke xInit() more than once without an intervening
6914 ** call to xShutdown().
6915 **
6916 ** [[the xCreate() page cache methods]]
6917 ** ^SQLite invokes the xCreate() method to construct a new cache instance.
6918 ** SQLite will typically create one cache instance for each open database file,
6919 ** though this is not guaranteed. ^The
6920 ** first parameter, szPage, is the size in bytes of the pages that must
6921 ** be allocated by the cache.  ^szPage will always a power of two.  ^The
6922 ** second parameter szExtra is a number of bytes of extra storage 
6923 ** associated with each page cache entry.  ^The szExtra parameter will
6924 ** a number less than 250.  SQLite will use the
6925 ** extra szExtra bytes on each page to store metadata about the underlying
6926 ** database page on disk.  The value passed into szExtra depends
6927 ** on the SQLite version, the target platform, and how SQLite was compiled.
6928 ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
6929 ** created will be used to cache database pages of a file stored on disk, or
6930 ** false if it is used for an in-memory database. The cache implementation
6931 ** does not have to do anything special based with the value of bPurgeable;
6932 ** it is purely advisory.  ^On a cache where bPurgeable is false, SQLite will
6933 ** never invoke xUnpin() except to deliberately delete a page.
6934 ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
6935 ** false will always have the "discard" flag set to true.  
6936 ** ^Hence, a cache created with bPurgeable false will
6937 ** never contain any unpinned pages.
6938 **
6939 ** [[the xCachesize() page cache method]]
6940 ** ^(The xCachesize() method may be called at any time by SQLite to set the
6941 ** suggested maximum cache-size (number of pages stored by) the cache
6942 ** instance passed as the first argument. This is the value configured using
6943 ** the SQLite "[PRAGMA cache_size]" command.)^  As with the bPurgeable
6944 ** parameter, the implementation is not required to do anything with this
6945 ** value; it is advisory only.
6946 **
6947 ** [[the xPagecount() page cache methods]]
6948 ** The xPagecount() method must return the number of pages currently
6949 ** stored in the cache, both pinned and unpinned.
6950 ** 
6951 ** [[the xFetch() page cache methods]]
6952 ** The xFetch() method locates a page in the cache and returns a pointer to 
6953 ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
6954 ** The pBuf element of the returned sqlite3_pcache_page object will be a
6955 ** pointer to a buffer of szPage bytes used to store the content of a 
6956 ** single database page.  The pExtra element of sqlite3_pcache_page will be
6957 ** a pointer to the szExtra bytes of extra storage that SQLite has requested
6958 ** for each entry in the page cache.
6959 **
6960 ** The page to be fetched is determined by the key. ^The minimum key value
6961 ** is 1.  After it has been retrieved using xFetch, the page is considered
6962 ** to be "pinned".
6963 **
6964 ** If the requested page is already in the page cache, then the page cache
6965 ** implementation must return a pointer to the page buffer with its content
6966 ** intact.  If the requested page is not already in the cache, then the
6967 ** cache implementation should use the value of the createFlag
6968 ** parameter to help it determined what action to take:
6969 **
6970 ** <table border=1 width=85% align=center>
6971 ** <tr><th> createFlag <th> Behavior when page is not already in cache
6972 ** <tr><td> 0 <td> Do not allocate a new page.  Return NULL.
6973 ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
6974 **                 Otherwise return NULL.
6975 ** <tr><td> 2 <td> Make every effort to allocate a new page.  Only return
6976 **                 NULL if allocating a new page is effectively impossible.
6977 ** </table>
6978 **
6979 ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1.  SQLite
6980 ** will only use a createFlag of 2 after a prior call with a createFlag of 1
6981 ** failed.)^  In between the to xFetch() calls, SQLite may
6982 ** attempt to unpin one or more cache pages by spilling the content of
6983 ** pinned pages to disk and synching the operating system disk cache.
6984 **
6985 ** [[the xUnpin() page cache method]]
6986 ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
6987 ** as its second argument.  If the third parameter, discard, is non-zero,
6988 ** then the page must be evicted from the cache.
6989 ** ^If the discard parameter is
6990 ** zero, then the page may be discarded or retained at the discretion of
6991 ** page cache implementation. ^The page cache implementation
6992 ** may choose to evict unpinned pages at any time.
6993 **
6994 ** The cache must not perform any reference counting. A single 
6995 ** call to xUnpin() unpins the page regardless of the number of prior calls 
6996 ** to xFetch().
6997 **
6998 ** [[the xRekey() page cache methods]]
6999 ** The xRekey() method is used to change the key value associated with the
7000 ** page passed as the second argument. If the cache
7001 ** previously contains an entry associated with newKey, it must be
7002 ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
7003 ** to be pinned.
7004 **
7005 ** When SQLite calls the xTruncate() method, the cache must discard all
7006 ** existing cache entries with page numbers (keys) greater than or equal
7007 ** to the value of the iLimit parameter passed to xTruncate(). If any
7008 ** of these pages are pinned, they are implicitly unpinned, meaning that
7009 ** they can be safely discarded.
7010 **
7011 ** [[the xDestroy() page cache method]]
7012 ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
7013 ** All resources associated with the specified cache should be freed. ^After
7014 ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
7015 ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
7016 ** functions.
7017 **
7018 ** [[the xShrink() page cache method]]
7019 ** ^SQLite invokes the xShrink() method when it wants the page cache to
7020 ** free up as much of heap memory as possible.  The page cache implementation
7021 ** is not obligated to free any memory, but well-behaved implementations should
7022 ** do their best.
7023 */
7024 typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
7025 struct sqlite3_pcache_methods2 {
7026   int iVersion;
7027   void *pArg;
7028   int (*xInit)(void*);
7029   void (*xShutdown)(void*);
7030   sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
7031   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7032   int (*xPagecount)(sqlite3_pcache*);
7033   sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7034   void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
7035   void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*, 
7036       unsigned oldKey, unsigned newKey);
7037   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7038   void (*xDestroy)(sqlite3_pcache*);
7039   void (*xShrink)(sqlite3_pcache*);
7040 };
7041
7042 /*
7043 ** This is the obsolete pcache_methods object that has now been replaced
7044 ** by sqlite3_pcache_methods2.  This object is not used by SQLite.  It is
7045 ** retained in the header file for backwards compatibility only.
7046 */
7047 typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
7048 struct sqlite3_pcache_methods {
7049   void *pArg;
7050   int (*xInit)(void*);
7051   void (*xShutdown)(void*);
7052   sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
7053   void (*xCachesize)(sqlite3_pcache*, int nCachesize);
7054   int (*xPagecount)(sqlite3_pcache*);
7055   void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
7056   void (*xUnpin)(sqlite3_pcache*, void*, int discard);
7057   void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
7058   void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
7059   void (*xDestroy)(sqlite3_pcache*);
7060 };
7061
7062
7063 /*
7064 ** CAPI3REF: Online Backup Object
7065 **
7066 ** The sqlite3_backup object records state information about an ongoing
7067 ** online backup operation.  ^The sqlite3_backup object is created by
7068 ** a call to [sqlite3_backup_init()] and is destroyed by a call to
7069 ** [sqlite3_backup_finish()].
7070 **
7071 ** See Also: [Using the SQLite Online Backup API]
7072 */
7073 typedef struct sqlite3_backup sqlite3_backup;
7074
7075 /*
7076 ** CAPI3REF: Online Backup API.
7077 **
7078 ** The backup API copies the content of one database into another.
7079 ** It is useful either for creating backups of databases or
7080 ** for copying in-memory databases to or from persistent files. 
7081 **
7082 ** See Also: [Using the SQLite Online Backup API]
7083 **
7084 ** ^SQLite holds a write transaction open on the destination database file
7085 ** for the duration of the backup operation.
7086 ** ^The source database is read-locked only while it is being read;
7087 ** it is not locked continuously for the entire backup operation.
7088 ** ^Thus, the backup may be performed on a live source database without
7089 ** preventing other database connections from
7090 ** reading or writing to the source database while the backup is underway.
7091 ** 
7092 ** ^(To perform a backup operation: 
7093 **   <ol>
7094 **     <li><b>sqlite3_backup_init()</b> is called once to initialize the
7095 **         backup, 
7096 **     <li><b>sqlite3_backup_step()</b> is called one or more times to transfer 
7097 **         the data between the two databases, and finally
7098 **     <li><b>sqlite3_backup_finish()</b> is called to release all resources 
7099 **         associated with the backup operation. 
7100 **   </ol>)^
7101 ** There should be exactly one call to sqlite3_backup_finish() for each
7102 ** successful call to sqlite3_backup_init().
7103 **
7104 ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
7105 **
7106 ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the 
7107 ** [database connection] associated with the destination database 
7108 ** and the database name, respectively.
7109 ** ^The database name is "main" for the main database, "temp" for the
7110 ** temporary database, or the name specified after the AS keyword in
7111 ** an [ATTACH] statement for an attached database.
7112 ** ^The S and M arguments passed to 
7113 ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
7114 ** and database name of the source database, respectively.
7115 ** ^The source and destination [database connections] (parameters S and D)
7116 ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
7117 ** an error.
7118 **
7119 ** ^A call to sqlite3_backup_init() will fail, returning SQLITE_ERROR, if 
7120 ** there is already a read or read-write transaction open on the 
7121 ** destination database.
7122 **
7123 ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
7124 ** returned and an error code and error message are stored in the
7125 ** destination [database connection] D.
7126 ** ^The error code and message for the failed call to sqlite3_backup_init()
7127 ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
7128 ** [sqlite3_errmsg16()] functions.
7129 ** ^A successful call to sqlite3_backup_init() returns a pointer to an
7130 ** [sqlite3_backup] object.
7131 ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
7132 ** sqlite3_backup_finish() functions to perform the specified backup 
7133 ** operation.
7134 **
7135 ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
7136 **
7137 ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between 
7138 ** the source and destination databases specified by [sqlite3_backup] object B.
7139 ** ^If N is negative, all remaining source pages are copied. 
7140 ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
7141 ** are still more pages to be copied, then the function returns [SQLITE_OK].
7142 ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
7143 ** from source to destination, then it returns [SQLITE_DONE].
7144 ** ^If an error occurs while running sqlite3_backup_step(B,N),
7145 ** then an [error code] is returned. ^As well as [SQLITE_OK] and
7146 ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
7147 ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
7148 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
7149 **
7150 ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
7151 ** <ol>
7152 ** <li> the destination database was opened read-only, or
7153 ** <li> the destination database is using write-ahead-log journaling
7154 ** and the destination and source page sizes differ, or
7155 ** <li> the destination database is an in-memory database and the
7156 ** destination and source page sizes differ.
7157 ** </ol>)^
7158 **
7159 ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
7160 ** the [sqlite3_busy_handler | busy-handler function]
7161 ** is invoked (if one is specified). ^If the 
7162 ** busy-handler returns non-zero before the lock is available, then 
7163 ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
7164 ** sqlite3_backup_step() can be retried later. ^If the source
7165 ** [database connection]
7166 ** is being used to write to the source database when sqlite3_backup_step()
7167 ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
7168 ** case the call to sqlite3_backup_step() can be retried later on. ^(If
7169 ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
7170 ** [SQLITE_READONLY] is returned, then 
7171 ** there is no point in retrying the call to sqlite3_backup_step(). These 
7172 ** errors are considered fatal.)^  The application must accept 
7173 ** that the backup operation has failed and pass the backup operation handle 
7174 ** to the sqlite3_backup_finish() to release associated resources.
7175 **
7176 ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
7177 ** on the destination file. ^The exclusive lock is not released until either 
7178 ** sqlite3_backup_finish() is called or the backup operation is complete 
7179 ** and sqlite3_backup_step() returns [SQLITE_DONE].  ^Every call to
7180 ** sqlite3_backup_step() obtains a [shared lock] on the source database that
7181 ** lasts for the duration of the sqlite3_backup_step() call.
7182 ** ^Because the source database is not locked between calls to
7183 ** sqlite3_backup_step(), the source database may be modified mid-way
7184 ** through the backup process.  ^If the source database is modified by an
7185 ** external process or via a database connection other than the one being
7186 ** used by the backup operation, then the backup will be automatically
7187 ** restarted by the next call to sqlite3_backup_step(). ^If the source 
7188 ** database is modified by the using the same database connection as is used
7189 ** by the backup operation, then the backup database is automatically
7190 ** updated at the same time.
7191 **
7192 ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
7193 **
7194 ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the 
7195 ** application wishes to abandon the backup operation, the application
7196 ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
7197 ** ^The sqlite3_backup_finish() interfaces releases all
7198 ** resources associated with the [sqlite3_backup] object. 
7199 ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
7200 ** active write-transaction on the destination database is rolled back.
7201 ** The [sqlite3_backup] object is invalid
7202 ** and may not be used following a call to sqlite3_backup_finish().
7203 **
7204 ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
7205 ** sqlite3_backup_step() errors occurred, regardless or whether or not
7206 ** sqlite3_backup_step() completed.
7207 ** ^If an out-of-memory condition or IO error occurred during any prior
7208 ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
7209 ** sqlite3_backup_finish() returns the corresponding [error code].
7210 **
7211 ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
7212 ** is not a permanent error and does not affect the return value of
7213 ** sqlite3_backup_finish().
7214 **
7215 ** [[sqlite3_backup_remaining()]] [[sqlite3_backup_pagecount()]]
7216 ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
7217 **
7218 ** ^The sqlite3_backup_remaining() routine returns the number of pages still
7219 ** to be backed up at the conclusion of the most recent sqlite3_backup_step().
7220 ** ^The sqlite3_backup_pagecount() routine returns the total number of pages
7221 ** in the source database at the conclusion of the most recent
7222 ** sqlite3_backup_step().
7223 ** ^(The values returned by these functions are only updated by
7224 ** sqlite3_backup_step(). If the source database is modified in a way that
7225 ** changes the size of the source database or the number of pages remaining,
7226 ** those changes are not reflected in the output of sqlite3_backup_pagecount()
7227 ** and sqlite3_backup_remaining() until after the next
7228 ** sqlite3_backup_step().)^
7229 **
7230 ** <b>Concurrent Usage of Database Handles</b>
7231 **
7232 ** ^The source [database connection] may be used by the application for other
7233 ** purposes while a backup operation is underway or being initialized.
7234 ** ^If SQLite is compiled and configured to support threadsafe database
7235 ** connections, then the source database connection may be used concurrently
7236 ** from within other threads.
7237 **
7238 ** However, the application must guarantee that the destination 
7239 ** [database connection] is not passed to any other API (by any thread) after 
7240 ** sqlite3_backup_init() is called and before the corresponding call to
7241 ** sqlite3_backup_finish().  SQLite does not currently check to see
7242 ** if the application incorrectly accesses the destination [database connection]
7243 ** and so no error code is reported, but the operations may malfunction
7244 ** nevertheless.  Use of the destination database connection while a
7245 ** backup is in progress might also also cause a mutex deadlock.
7246 **
7247 ** If running in [shared cache mode], the application must
7248 ** guarantee that the shared cache used by the destination database
7249 ** is not accessed while the backup is running. In practice this means
7250 ** that the application must guarantee that the disk file being 
7251 ** backed up to is not accessed by any connection within the process,
7252 ** not just the specific connection that was passed to sqlite3_backup_init().
7253 **
7254 ** The [sqlite3_backup] object itself is partially threadsafe. Multiple 
7255 ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
7256 ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
7257 ** APIs are not strictly speaking threadsafe. If they are invoked at the
7258 ** same time as another thread is invoking sqlite3_backup_step() it is
7259 ** possible that they return invalid values.
7260 */
7261 SQLITE_API sqlite3_backup *SQLITE_STDCALL sqlite3_backup_init(
7262   sqlite3 *pDest,                        /* Destination database handle */
7263   const char *zDestName,                 /* Destination database name */
7264   sqlite3 *pSource,                      /* Source database handle */
7265   const char *zSourceName                /* Source database name */
7266 );
7267 SQLITE_API int SQLITE_STDCALL sqlite3_backup_step(sqlite3_backup *p, int nPage);
7268 SQLITE_API int SQLITE_STDCALL sqlite3_backup_finish(sqlite3_backup *p);
7269 SQLITE_API int SQLITE_STDCALL sqlite3_backup_remaining(sqlite3_backup *p);
7270 SQLITE_API int SQLITE_STDCALL sqlite3_backup_pagecount(sqlite3_backup *p);
7271
7272 /*
7273 ** CAPI3REF: Unlock Notification
7274 **
7275 ** ^When running in shared-cache mode, a database operation may fail with
7276 ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
7277 ** individual tables within the shared-cache cannot be obtained. See
7278 ** [SQLite Shared-Cache Mode] for a description of shared-cache locking. 
7279 ** ^This API may be used to register a callback that SQLite will invoke 
7280 ** when the connection currently holding the required lock relinquishes it.
7281 ** ^This API is only available if the library was compiled with the
7282 ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
7283 **
7284 ** See Also: [Using the SQLite Unlock Notification Feature].
7285 **
7286 ** ^Shared-cache locks are released when a database connection concludes
7287 ** its current transaction, either by committing it or rolling it back. 
7288 **
7289 ** ^When a connection (known as the blocked connection) fails to obtain a
7290 ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
7291 ** identity of the database connection (the blocking connection) that
7292 ** has locked the required resource is stored internally. ^After an 
7293 ** application receives an SQLITE_LOCKED error, it may call the
7294 ** sqlite3_unlock_notify() method with the blocked connection handle as 
7295 ** the first argument to register for a callback that will be invoked
7296 ** when the blocking connections current transaction is concluded. ^The
7297 ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
7298 ** call that concludes the blocking connections transaction.
7299 **
7300 ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
7301 ** there is a chance that the blocking connection will have already
7302 ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
7303 ** If this happens, then the specified callback is invoked immediately,
7304 ** from within the call to sqlite3_unlock_notify().)^
7305 **
7306 ** ^If the blocked connection is attempting to obtain a write-lock on a
7307 ** shared-cache table, and more than one other connection currently holds
7308 ** a read-lock on the same table, then SQLite arbitrarily selects one of 
7309 ** the other connections to use as the blocking connection.
7310 **
7311 ** ^(There may be at most one unlock-notify callback registered by a 
7312 ** blocked connection. If sqlite3_unlock_notify() is called when the
7313 ** blocked connection already has a registered unlock-notify callback,
7314 ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
7315 ** called with a NULL pointer as its second argument, then any existing
7316 ** unlock-notify callback is canceled. ^The blocked connections 
7317 ** unlock-notify callback may also be canceled by closing the blocked
7318 ** connection using [sqlite3_close()].
7319 **
7320 ** The unlock-notify callback is not reentrant. If an application invokes
7321 ** any sqlite3_xxx API functions from within an unlock-notify callback, a
7322 ** crash or deadlock may be the result.
7323 **
7324 ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
7325 ** returns SQLITE_OK.
7326 **
7327 ** <b>Callback Invocation Details</b>
7328 **
7329 ** When an unlock-notify callback is registered, the application provides a 
7330 ** single void* pointer that is passed to the callback when it is invoked.
7331 ** However, the signature of the callback function allows SQLite to pass
7332 ** it an array of void* context pointers. The first argument passed to
7333 ** an unlock-notify callback is a pointer to an array of void* pointers,
7334 ** and the second is the number of entries in the array.
7335 **
7336 ** When a blocking connections transaction is concluded, there may be
7337 ** more than one blocked connection that has registered for an unlock-notify
7338 ** callback. ^If two or more such blocked connections have specified the
7339 ** same callback function, then instead of invoking the callback function
7340 ** multiple times, it is invoked once with the set of void* context pointers
7341 ** specified by the blocked connections bundled together into an array.
7342 ** This gives the application an opportunity to prioritize any actions 
7343 ** related to the set of unblocked database connections.
7344 **
7345 ** <b>Deadlock Detection</b>
7346 **
7347 ** Assuming that after registering for an unlock-notify callback a 
7348 ** database waits for the callback to be issued before taking any further
7349 ** action (a reasonable assumption), then using this API may cause the
7350 ** application to deadlock. For example, if connection X is waiting for
7351 ** connection Y's transaction to be concluded, and similarly connection
7352 ** Y is waiting on connection X's transaction, then neither connection
7353 ** will proceed and the system may remain deadlocked indefinitely.
7354 **
7355 ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
7356 ** detection. ^If a given call to sqlite3_unlock_notify() would put the
7357 ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
7358 ** unlock-notify callback is registered. The system is said to be in
7359 ** a deadlocked state if connection A has registered for an unlock-notify
7360 ** callback on the conclusion of connection B's transaction, and connection
7361 ** B has itself registered for an unlock-notify callback when connection
7362 ** A's transaction is concluded. ^Indirect deadlock is also detected, so
7363 ** the system is also considered to be deadlocked if connection B has
7364 ** registered for an unlock-notify callback on the conclusion of connection
7365 ** C's transaction, where connection C is waiting on connection A. ^Any
7366 ** number of levels of indirection are allowed.
7367 **
7368 ** <b>The "DROP TABLE" Exception</b>
7369 **
7370 ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost 
7371 ** always appropriate to call sqlite3_unlock_notify(). There is however,
7372 ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
7373 ** SQLite checks if there are any currently executing SELECT statements
7374 ** that belong to the same connection. If there are, SQLITE_LOCKED is
7375 ** returned. In this case there is no "blocking connection", so invoking
7376 ** sqlite3_unlock_notify() results in the unlock-notify callback being
7377 ** invoked immediately. If the application then re-attempts the "DROP TABLE"
7378 ** or "DROP INDEX" query, an infinite loop might be the result.
7379 **
7380 ** One way around this problem is to check the extended error code returned
7381 ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
7382 ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
7383 ** the special "DROP TABLE/INDEX" case, the extended error code is just 
7384 ** SQLITE_LOCKED.)^
7385 */
7386 SQLITE_API int SQLITE_STDCALL sqlite3_unlock_notify(
7387   sqlite3 *pBlocked,                          /* Waiting connection */
7388   void (*xNotify)(void **apArg, int nArg),    /* Callback function to invoke */
7389   void *pNotifyArg                            /* Argument to pass to xNotify */
7390 );
7391
7392
7393 /*
7394 ** CAPI3REF: String Comparison
7395 **
7396 ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
7397 ** and extensions to compare the contents of two buffers containing UTF-8
7398 ** strings in a case-independent fashion, using the same definition of "case
7399 ** independence" that SQLite uses internally when comparing identifiers.
7400 */
7401 SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *, const char *);
7402 SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *, const char *, int);
7403
7404 /*
7405 ** CAPI3REF: String Globbing
7406 *
7407 ** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches
7408 ** the glob pattern P, and it returns non-zero if string X does not match
7409 ** the glob pattern P.  ^The definition of glob pattern matching used in
7410 ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
7411 ** SQL dialect used by SQLite.  ^The sqlite3_strglob(P,X) function is case
7412 ** sensitive.
7413 **
7414 ** Note that this routine returns zero on a match and non-zero if the strings
7415 ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
7416 */
7417 SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlob, const char *zStr);
7418
7419 /*
7420 ** CAPI3REF: Error Logging Interface
7421 **
7422 ** ^The [sqlite3_log()] interface writes a message into the [error log]
7423 ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
7424 ** ^If logging is enabled, the zFormat string and subsequent arguments are
7425 ** used with [sqlite3_snprintf()] to generate the final output string.
7426 **
7427 ** The sqlite3_log() interface is intended for use by extensions such as
7428 ** virtual tables, collating functions, and SQL functions.  While there is
7429 ** nothing to prevent an application from calling sqlite3_log(), doing so
7430 ** is considered bad form.
7431 **
7432 ** The zFormat string must not be NULL.
7433 **
7434 ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
7435 ** will not use dynamically allocated memory.  The log message is stored in
7436 ** a fixed-length buffer on the stack.  If the log message is longer than
7437 ** a few hundred characters, it will be truncated to the length of the
7438 ** buffer.
7439 */
7440 SQLITE_API void SQLITE_CDECL sqlite3_log(int iErrCode, const char *zFormat, ...);
7441
7442 /*
7443 ** CAPI3REF: Write-Ahead Log Commit Hook
7444 **
7445 ** ^The [sqlite3_wal_hook()] function is used to register a callback that
7446 ** is invoked each time data is committed to a database in wal mode.
7447 **
7448 ** ^(The callback is invoked by SQLite after the commit has taken place and 
7449 ** the associated write-lock on the database released)^, so the implementation 
7450 ** may read, write or [checkpoint] the database as required.
7451 **
7452 ** ^The first parameter passed to the callback function when it is invoked
7453 ** is a copy of the third parameter passed to sqlite3_wal_hook() when
7454 ** registering the callback. ^The second is a copy of the database handle.
7455 ** ^The third parameter is the name of the database that was written to -
7456 ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
7457 ** is the number of pages currently in the write-ahead log file,
7458 ** including those that were just committed.
7459 **
7460 ** The callback function should normally return [SQLITE_OK].  ^If an error
7461 ** code is returned, that error will propagate back up through the
7462 ** SQLite code base to cause the statement that provoked the callback
7463 ** to report an error, though the commit will have still occurred. If the
7464 ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
7465 ** that does not correspond to any valid SQLite error code, the results
7466 ** are undefined.
7467 **
7468 ** A single database handle may have at most a single write-ahead log callback 
7469 ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
7470 ** previously registered write-ahead log callback. ^Note that the
7471 ** [sqlite3_wal_autocheckpoint()] interface and the
7472 ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
7473 ** those overwrite any prior [sqlite3_wal_hook()] settings.
7474 */
7475 SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(
7476   sqlite3*, 
7477   int(*)(void *,sqlite3*,const char*,int),
7478   void*
7479 );
7480
7481 /*
7482 ** CAPI3REF: Configure an auto-checkpoint
7483 **
7484 ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
7485 ** [sqlite3_wal_hook()] that causes any database on [database connection] D
7486 ** to automatically [checkpoint]
7487 ** after committing a transaction if there are N or
7488 ** more frames in the [write-ahead log] file.  ^Passing zero or 
7489 ** a negative value as the nFrame parameter disables automatic
7490 ** checkpoints entirely.
7491 **
7492 ** ^The callback registered by this function replaces any existing callback
7493 ** registered using [sqlite3_wal_hook()].  ^Likewise, registering a callback
7494 ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
7495 ** configured by this function.
7496 **
7497 ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
7498 ** from SQL.
7499 **
7500 ** ^Checkpoints initiated by this mechanism are
7501 ** [sqlite3_wal_checkpoint_v2|PASSIVE].
7502 **
7503 ** ^Every new [database connection] defaults to having the auto-checkpoint
7504 ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
7505 ** pages.  The use of this interface
7506 ** is only necessary if the default setting is found to be suboptimal
7507 ** for a particular application.
7508 */
7509 SQLITE_API int SQLITE_STDCALL sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
7510
7511 /*
7512 ** CAPI3REF: Checkpoint a database
7513 **
7514 ** ^(The sqlite3_wal_checkpoint(D,X) is equivalent to
7515 ** [sqlite3_wal_checkpoint_v2](D,X,[SQLITE_CHECKPOINT_PASSIVE],0,0).)^
7516 **
7517 ** In brief, sqlite3_wal_checkpoint(D,X) causes the content in the 
7518 ** [write-ahead log] for database X on [database connection] D to be
7519 ** transferred into the database file and for the write-ahead log to
7520 ** be reset.  See the [checkpointing] documentation for addition
7521 ** information.
7522 **
7523 ** This interface used to be the only way to cause a checkpoint to
7524 ** occur.  But then the newer and more powerful [sqlite3_wal_checkpoint_v2()]
7525 ** interface was added.  This interface is retained for backwards
7526 ** compatibility and as a convenience for applications that need to manually
7527 ** start a callback but which do not need the full power (and corresponding
7528 ** complication) of [sqlite3_wal_checkpoint_v2()].
7529 */
7530 SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
7531
7532 /*
7533 ** CAPI3REF: Checkpoint a database
7534 **
7535 ** ^(The sqlite3_wal_checkpoint_v2(D,X,M,L,C) interface runs a checkpoint
7536 ** operation on database X of [database connection] D in mode M.  Status
7537 ** information is written back into integers pointed to by L and C.)^
7538 ** ^(The M parameter must be a valid [checkpoint mode]:)^
7539 **
7540 ** <dl>
7541 ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
7542 **   ^Checkpoint as many frames as possible without waiting for any database 
7543 **   readers or writers to finish, then sync the database file if all frames 
7544 **   in the log were checkpointed. ^The [busy-handler callback]
7545 **   is never invoked in the SQLITE_CHECKPOINT_PASSIVE mode.  
7546 **   ^On the other hand, passive mode might leave the checkpoint unfinished
7547 **   if there are concurrent readers or writers.
7548 **
7549 ** <dt>SQLITE_CHECKPOINT_FULL<dd>
7550 **   ^This mode blocks (it invokes the
7551 **   [sqlite3_busy_handler|busy-handler callback]) until there is no
7552 **   database writer and all readers are reading from the most recent database
7553 **   snapshot. ^It then checkpoints all frames in the log file and syncs the
7554 **   database file. ^This mode blocks new database writers while it is pending,
7555 **   but new database readers are allowed to continue unimpeded.
7556 **
7557 ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
7558 **   ^This mode works the same way as SQLITE_CHECKPOINT_FULL with the addition
7559 **   that after checkpointing the log file it blocks (calls the 
7560 **   [busy-handler callback])
7561 **   until all readers are reading from the database file only. ^This ensures 
7562 **   that the next writer will restart the log file from the beginning.
7563 **   ^Like SQLITE_CHECKPOINT_FULL, this mode blocks new
7564 **   database writer attempts while it is pending, but does not impede readers.
7565 **
7566 ** <dt>SQLITE_CHECKPOINT_TRUNCATE<dd>
7567 **   ^This mode works the same way as SQLITE_CHECKPOINT_RESTART with the
7568 **   addition that it also truncates the log file to zero bytes just prior
7569 **   to a successful return.
7570 ** </dl>
7571 **
7572 ** ^If pnLog is not NULL, then *pnLog is set to the total number of frames in
7573 ** the log file or to -1 if the checkpoint could not run because
7574 ** of an error or because the database is not in [WAL mode]. ^If pnCkpt is not
7575 ** NULL,then *pnCkpt is set to the total number of checkpointed frames in the
7576 ** log file (including any that were already checkpointed before the function
7577 ** was called) or to -1 if the checkpoint could not run due to an error or
7578 ** because the database is not in WAL mode. ^Note that upon successful
7579 ** completion of an SQLITE_CHECKPOINT_TRUNCATE, the log file will have been
7580 ** truncated to zero bytes and so both *pnLog and *pnCkpt will be set to zero.
7581 **
7582 ** ^All calls obtain an exclusive "checkpoint" lock on the database file. ^If
7583 ** any other process is running a checkpoint operation at the same time, the 
7584 ** lock cannot be obtained and SQLITE_BUSY is returned. ^Even if there is a 
7585 ** busy-handler configured, it will not be invoked in this case.
7586 **
7587 ** ^The SQLITE_CHECKPOINT_FULL, RESTART and TRUNCATE modes also obtain the 
7588 ** exclusive "writer" lock on the database file. ^If the writer lock cannot be
7589 ** obtained immediately, and a busy-handler is configured, it is invoked and
7590 ** the writer lock retried until either the busy-handler returns 0 or the lock
7591 ** is successfully obtained. ^The busy-handler is also invoked while waiting for
7592 ** database readers as described above. ^If the busy-handler returns 0 before
7593 ** the writer lock is obtained or while waiting for database readers, the
7594 ** checkpoint operation proceeds from that point in the same way as 
7595 ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible 
7596 ** without blocking any further. ^SQLITE_BUSY is returned in this case.
7597 **
7598 ** ^If parameter zDb is NULL or points to a zero length string, then the
7599 ** specified operation is attempted on all WAL databases [attached] to 
7600 ** [database connection] db.  In this case the
7601 ** values written to output parameters *pnLog and *pnCkpt are undefined. ^If 
7602 ** an SQLITE_BUSY error is encountered when processing one or more of the 
7603 ** attached WAL databases, the operation is still attempted on any remaining 
7604 ** attached databases and SQLITE_BUSY is returned at the end. ^If any other 
7605 ** error occurs while processing an attached database, processing is abandoned 
7606 ** and the error code is returned to the caller immediately. ^If no error 
7607 ** (SQLITE_BUSY or otherwise) is encountered while processing the attached 
7608 ** databases, SQLITE_OK is returned.
7609 **
7610 ** ^If database zDb is the name of an attached database that is not in WAL
7611 ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. ^If
7612 ** zDb is not NULL (or a zero length string) and is not the name of any
7613 ** attached database, SQLITE_ERROR is returned to the caller.
7614 **
7615 ** ^Unless it returns SQLITE_MISUSE,
7616 ** the sqlite3_wal_checkpoint_v2() interface
7617 ** sets the error information that is queried by
7618 ** [sqlite3_errcode()] and [sqlite3_errmsg()].
7619 **
7620 ** ^The [PRAGMA wal_checkpoint] command can be used to invoke this interface
7621 ** from SQL.
7622 */
7623 SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint_v2(
7624   sqlite3 *db,                    /* Database handle */
7625   const char *zDb,                /* Name of attached database (or NULL) */
7626   int eMode,                      /* SQLITE_CHECKPOINT_* value */
7627   int *pnLog,                     /* OUT: Size of WAL log in frames */
7628   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
7629 );
7630
7631 /*
7632 ** CAPI3REF: Checkpoint Mode Values
7633 ** KEYWORDS: {checkpoint mode}
7634 **
7635 ** These constants define all valid values for the "checkpoint mode" passed
7636 ** as the third parameter to the [sqlite3_wal_checkpoint_v2()] interface.
7637 ** See the [sqlite3_wal_checkpoint_v2()] documentation for details on the
7638 ** meaning of each of these checkpoint modes.
7639 */
7640 #define SQLITE_CHECKPOINT_PASSIVE  0  /* Do as much as possible w/o blocking */
7641 #define SQLITE_CHECKPOINT_FULL     1  /* Wait for writers, then checkpoint */
7642 #define SQLITE_CHECKPOINT_RESTART  2  /* Like FULL but wait for for readers */
7643 #define SQLITE_CHECKPOINT_TRUNCATE 3  /* Like RESTART but also truncate WAL */
7644
7645 /*
7646 ** CAPI3REF: Virtual Table Interface Configuration
7647 **
7648 ** This function may be called by either the [xConnect] or [xCreate] method
7649 ** of a [virtual table] implementation to configure
7650 ** various facets of the virtual table interface.
7651 **
7652 ** If this interface is invoked outside the context of an xConnect or
7653 ** xCreate virtual table method then the behavior is undefined.
7654 **
7655 ** At present, there is only one option that may be configured using
7656 ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].)  Further options
7657 ** may be added in the future.
7658 */
7659 SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3*, int op, ...);
7660
7661 /*
7662 ** CAPI3REF: Virtual Table Configuration Options
7663 **
7664 ** These macros define the various options to the
7665 ** [sqlite3_vtab_config()] interface that [virtual table] implementations
7666 ** can use to customize and optimize their behavior.
7667 **
7668 ** <dl>
7669 ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
7670 ** <dd>Calls of the form
7671 ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
7672 ** where X is an integer.  If X is zero, then the [virtual table] whose
7673 ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
7674 ** support constraints.  In this configuration (which is the default) if
7675 ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
7676 ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
7677 ** specified as part of the users SQL statement, regardless of the actual
7678 ** ON CONFLICT mode specified.
7679 **
7680 ** If X is non-zero, then the virtual table implementation guarantees
7681 ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
7682 ** any modifications to internal or persistent data structures have been made.
7683 ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite 
7684 ** is able to roll back a statement or database transaction, and abandon
7685 ** or continue processing the current SQL statement as appropriate. 
7686 ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
7687 ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
7688 ** had been ABORT.
7689 **
7690 ** Virtual table implementations that are required to handle OR REPLACE
7691 ** must do so within the [xUpdate] method. If a call to the 
7692 ** [sqlite3_vtab_on_conflict()] function indicates that the current ON 
7693 ** CONFLICT policy is REPLACE, the virtual table implementation should 
7694 ** silently replace the appropriate rows within the xUpdate callback and
7695 ** return SQLITE_OK. Or, if this is not possible, it may return
7696 ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT 
7697 ** constraint handling.
7698 ** </dl>
7699 */
7700 #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
7701
7702 /*
7703 ** CAPI3REF: Determine The Virtual Table Conflict Policy
7704 **
7705 ** This function may only be called from within a call to the [xUpdate] method
7706 ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
7707 ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
7708 ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
7709 ** of the SQL statement that triggered the call to the [xUpdate] method of the
7710 ** [virtual table].
7711 */
7712 SQLITE_API int SQLITE_STDCALL sqlite3_vtab_on_conflict(sqlite3 *);
7713
7714 /*
7715 ** CAPI3REF: Conflict resolution modes
7716 ** KEYWORDS: {conflict resolution mode}
7717 **
7718 ** These constants are returned by [sqlite3_vtab_on_conflict()] to
7719 ** inform a [virtual table] implementation what the [ON CONFLICT] mode
7720 ** is for the SQL statement being evaluated.
7721 **
7722 ** Note that the [SQLITE_IGNORE] constant is also used as a potential
7723 ** return value from the [sqlite3_set_authorizer()] callback and that
7724 ** [SQLITE_ABORT] is also a [result code].
7725 */
7726 #define SQLITE_ROLLBACK 1
7727 /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
7728 #define SQLITE_FAIL     3
7729 /* #define SQLITE_ABORT 4  // Also an error code */
7730 #define SQLITE_REPLACE  5
7731
7732 /*
7733 ** CAPI3REF: Prepared Statement Scan Status Opcodes
7734 ** KEYWORDS: {scanstatus options}
7735 **
7736 ** The following constants can be used for the T parameter to the
7737 ** [sqlite3_stmt_scanstatus(S,X,T,V)] interface.  Each constant designates a
7738 ** different metric for sqlite3_stmt_scanstatus() to return.
7739 **
7740 ** When the value returned to V is a string, space to hold that string is
7741 ** managed by the prepared statement S and will be automatically freed when
7742 ** S is finalized.
7743 **
7744 ** <dl>
7745 ** [[SQLITE_SCANSTAT_NLOOP]] <dt>SQLITE_SCANSTAT_NLOOP</dt>
7746 ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be
7747 ** set to the total number of times that the X-th loop has run.</dd>
7748 **
7749 ** [[SQLITE_SCANSTAT_NVISIT]] <dt>SQLITE_SCANSTAT_NVISIT</dt>
7750 ** <dd>^The [sqlite3_int64] variable pointed to by the T parameter will be set
7751 ** to the total number of rows examined by all iterations of the X-th loop.</dd>
7752 **
7753 ** [[SQLITE_SCANSTAT_EST]] <dt>SQLITE_SCANSTAT_EST</dt>
7754 ** <dd>^The "double" variable pointed to by the T parameter will be set to the
7755 ** query planner's estimate for the average number of rows output from each
7756 ** iteration of the X-th loop.  If the query planner's estimates was accurate,
7757 ** then this value will approximate the quotient NVISIT/NLOOP and the
7758 ** product of this value for all prior loops with the same SELECTID will
7759 ** be the NLOOP value for the current loop.
7760 **
7761 ** [[SQLITE_SCANSTAT_NAME]] <dt>SQLITE_SCANSTAT_NAME</dt>
7762 ** <dd>^The "const char *" variable pointed to by the T parameter will be set
7763 ** to a zero-terminated UTF-8 string containing the name of the index or table
7764 ** used for the X-th loop.
7765 **
7766 ** [[SQLITE_SCANSTAT_EXPLAIN]] <dt>SQLITE_SCANSTAT_EXPLAIN</dt>
7767 ** <dd>^The "const char *" variable pointed to by the T parameter will be set
7768 ** to a zero-terminated UTF-8 string containing the [EXPLAIN QUERY PLAN]
7769 ** description for the X-th loop.
7770 **
7771 ** [[SQLITE_SCANSTAT_SELECTID]] <dt>SQLITE_SCANSTAT_SELECT</dt>
7772 ** <dd>^The "int" variable pointed to by the T parameter will be set to the
7773 ** "select-id" for the X-th loop.  The select-id identifies which query or
7774 ** subquery the loop is part of.  The main query has a select-id of zero.
7775 ** The select-id is the same value as is output in the first column
7776 ** of an [EXPLAIN QUERY PLAN] query.
7777 ** </dl>
7778 */
7779 #define SQLITE_SCANSTAT_NLOOP    0
7780 #define SQLITE_SCANSTAT_NVISIT   1
7781 #define SQLITE_SCANSTAT_EST      2
7782 #define SQLITE_SCANSTAT_NAME     3
7783 #define SQLITE_SCANSTAT_EXPLAIN  4
7784 #define SQLITE_SCANSTAT_SELECTID 5
7785
7786 /*
7787 ** CAPI3REF: Prepared Statement Scan Status
7788 **
7789 ** This interface returns information about the predicted and measured
7790 ** performance for pStmt.  Advanced applications can use this
7791 ** interface to compare the predicted and the measured performance and
7792 ** issue warnings and/or rerun [ANALYZE] if discrepancies are found.
7793 **
7794 ** Since this interface is expected to be rarely used, it is only
7795 ** available if SQLite is compiled using the [SQLITE_ENABLE_STMT_SCANSTATUS]
7796 ** compile-time option.
7797 **
7798 ** The "iScanStatusOp" parameter determines which status information to return.
7799 ** The "iScanStatusOp" must be one of the [scanstatus options] or the behavior
7800 ** of this interface is undefined.
7801 ** ^The requested measurement is written into a variable pointed to by
7802 ** the "pOut" parameter.
7803 ** Parameter "idx" identifies the specific loop to retrieve statistics for.
7804 ** Loops are numbered starting from zero. ^If idx is out of range - less than
7805 ** zero or greater than or equal to the total number of loops used to implement
7806 ** the statement - a non-zero value is returned and the variable that pOut
7807 ** points to is unchanged.
7808 **
7809 ** ^Statistics might not be available for all loops in all statements. ^In cases
7810 ** where there exist loops with no available statistics, this function behaves
7811 ** as if the loop did not exist - it returns non-zero and leave the variable
7812 ** that pOut points to unchanged.
7813 **
7814 ** See also: [sqlite3_stmt_scanstatus_reset()]
7815 */
7816 SQLITE_API SQLITE_EXPERIMENTAL int SQLITE_STDCALL sqlite3_stmt_scanstatus(
7817   sqlite3_stmt *pStmt,      /* Prepared statement for which info desired */
7818   int idx,                  /* Index of loop to report on */
7819   int iScanStatusOp,        /* Information desired.  SQLITE_SCANSTAT_* */
7820   void *pOut                /* Result written here */
7821 );     
7822
7823 /*
7824 ** CAPI3REF: Zero Scan-Status Counters
7825 **
7826 ** ^Zero all [sqlite3_stmt_scanstatus()] related event counters.
7827 **
7828 ** This API is only available if the library is built with pre-processor
7829 ** symbol [SQLITE_ENABLE_STMT_SCANSTATUS] defined.
7830 */
7831 SQLITE_API SQLITE_EXPERIMENTAL void SQLITE_STDCALL sqlite3_stmt_scanstatus_reset(sqlite3_stmt*);
7832
7833
7834 /*
7835 ** Undo the hack that converts floating point types to integer for
7836 ** builds on processors without floating point support.
7837 */
7838 #ifdef SQLITE_OMIT_FLOATING_POINT
7839 # undef double
7840 #endif
7841
7842 #if 0
7843 }  /* End of the 'extern "C"' block */
7844 #endif
7845 #endif /* _SQLITE3_H_ */
7846
7847 /*
7848 ** 2010 August 30
7849 **
7850 ** The author disclaims copyright to this source code.  In place of
7851 ** a legal notice, here is a blessing:
7852 **
7853 **    May you do good and not evil.
7854 **    May you find forgiveness for yourself and forgive others.
7855 **    May you share freely, never taking more than you give.
7856 **
7857 *************************************************************************
7858 */
7859
7860 #ifndef _SQLITE3RTREE_H_
7861 #define _SQLITE3RTREE_H_
7862
7863
7864 #if 0
7865 extern "C" {
7866 #endif
7867
7868 typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
7869 typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
7870
7871 /* The double-precision datatype used by RTree depends on the
7872 ** SQLITE_RTREE_INT_ONLY compile-time option.
7873 */
7874 #ifdef SQLITE_RTREE_INT_ONLY
7875   typedef sqlite3_int64 sqlite3_rtree_dbl;
7876 #else
7877   typedef double sqlite3_rtree_dbl;
7878 #endif
7879
7880 /*
7881 ** Register a geometry callback named zGeom that can be used as part of an
7882 ** R-Tree geometry query as follows:
7883 **
7884 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
7885 */
7886 SQLITE_API int SQLITE_STDCALL sqlite3_rtree_geometry_callback(
7887   sqlite3 *db,
7888   const char *zGeom,
7889   int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
7890   void *pContext
7891 );
7892
7893
7894 /*
7895 ** A pointer to a structure of the following type is passed as the first
7896 ** argument to callbacks registered using rtree_geometry_callback().
7897 */
7898 struct sqlite3_rtree_geometry {
7899   void *pContext;                 /* Copy of pContext passed to s_r_g_c() */
7900   int nParam;                     /* Size of array aParam[] */
7901   sqlite3_rtree_dbl *aParam;      /* Parameters passed to SQL geom function */
7902   void *pUser;                    /* Callback implementation user data */
7903   void (*xDelUser)(void *);       /* Called by SQLite to clean up pUser */
7904 };
7905
7906 /*
7907 ** Register a 2nd-generation geometry callback named zScore that can be 
7908 ** used as part of an R-Tree geometry query as follows:
7909 **
7910 **   SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
7911 */
7912 SQLITE_API int SQLITE_STDCALL sqlite3_rtree_query_callback(
7913   sqlite3 *db,
7914   const char *zQueryFunc,
7915   int (*xQueryFunc)(sqlite3_rtree_query_info*),
7916   void *pContext,
7917   void (*xDestructor)(void*)
7918 );
7919
7920
7921 /*
7922 ** A pointer to a structure of the following type is passed as the 
7923 ** argument to scored geometry callback registered using
7924 ** sqlite3_rtree_query_callback().
7925 **
7926 ** Note that the first 5 fields of this structure are identical to
7927 ** sqlite3_rtree_geometry.  This structure is a subclass of
7928 ** sqlite3_rtree_geometry.
7929 */
7930 struct sqlite3_rtree_query_info {
7931   void *pContext;                   /* pContext from when function registered */
7932   int nParam;                       /* Number of function parameters */
7933   sqlite3_rtree_dbl *aParam;        /* value of function parameters */
7934   void *pUser;                      /* callback can use this, if desired */
7935   void (*xDelUser)(void*);          /* function to free pUser */
7936   sqlite3_rtree_dbl *aCoord;        /* Coordinates of node or entry to check */
7937   unsigned int *anQueue;            /* Number of pending entries in the queue */
7938   int nCoord;                       /* Number of coordinates */
7939   int iLevel;                       /* Level of current node or entry */
7940   int mxLevel;                      /* The largest iLevel value in the tree */
7941   sqlite3_int64 iRowid;             /* Rowid for current entry */
7942   sqlite3_rtree_dbl rParentScore;   /* Score of parent node */
7943   int eParentWithin;                /* Visibility of parent node */
7944   int eWithin;                      /* OUT: Visiblity */
7945   sqlite3_rtree_dbl rScore;         /* OUT: Write the score here */
7946 };
7947
7948 /*
7949 ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
7950 */
7951 #define NOT_WITHIN       0   /* Object completely outside of query region */
7952 #define PARTLY_WITHIN    1   /* Object partially overlaps query region */
7953 #define FULLY_WITHIN     2   /* Object fully contained within query region */
7954
7955
7956 #if 0
7957 }  /* end of the 'extern "C"' block */
7958 #endif
7959
7960 #endif  /* ifndef _SQLITE3RTREE_H_ */
7961
7962
7963 /************** End of sqlite3.h *********************************************/
7964 /************** Continuing where we left off in sqliteInt.h ******************/
7965
7966 /*
7967 ** Include the configuration header output by 'configure' if we're using the
7968 ** autoconf-based build
7969 */
7970 #ifdef _HAVE_SQLITE_CONFIG_H
7971 #include "config.h"
7972 #endif
7973
7974 /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
7975 /************** Begin file sqliteLimit.h *************************************/
7976 /*
7977 ** 2007 May 7
7978 **
7979 ** The author disclaims copyright to this source code.  In place of
7980 ** a legal notice, here is a blessing:
7981 **
7982 **    May you do good and not evil.
7983 **    May you find forgiveness for yourself and forgive others.
7984 **    May you share freely, never taking more than you give.
7985 **
7986 *************************************************************************
7987 ** 
7988 ** This file defines various limits of what SQLite can process.
7989 */
7990
7991 /*
7992 ** The maximum length of a TEXT or BLOB in bytes.   This also
7993 ** limits the size of a row in a table or index.
7994 **
7995 ** The hard limit is the ability of a 32-bit signed integer
7996 ** to count the size: 2^31-1 or 2147483647.
7997 */
7998 #ifndef SQLITE_MAX_LENGTH
7999 # define SQLITE_MAX_LENGTH 1000000000
8000 #endif
8001
8002 /*
8003 ** This is the maximum number of
8004 **
8005 **    * Columns in a table
8006 **    * Columns in an index
8007 **    * Columns in a view
8008 **    * Terms in the SET clause of an UPDATE statement
8009 **    * Terms in the result set of a SELECT statement
8010 **    * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
8011 **    * Terms in the VALUES clause of an INSERT statement
8012 **
8013 ** The hard upper limit here is 32676.  Most database people will
8014 ** tell you that in a well-normalized database, you usually should
8015 ** not have more than a dozen or so columns in any table.  And if
8016 ** that is the case, there is no point in having more than a few
8017 ** dozen values in any of the other situations described above.
8018 */
8019 #ifndef SQLITE_MAX_COLUMN
8020 # define SQLITE_MAX_COLUMN 2000
8021 #endif
8022
8023 /*
8024 ** The maximum length of a single SQL statement in bytes.
8025 **
8026 ** It used to be the case that setting this value to zero would
8027 ** turn the limit off.  That is no longer true.  It is not possible
8028 ** to turn this limit off.
8029 */
8030 #ifndef SQLITE_MAX_SQL_LENGTH
8031 # define SQLITE_MAX_SQL_LENGTH 1000000000
8032 #endif
8033
8034 /*
8035 ** The maximum depth of an expression tree. This is limited to 
8036 ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might 
8037 ** want to place more severe limits on the complexity of an 
8038 ** expression.
8039 **
8040 ** A value of 0 used to mean that the limit was not enforced.
8041 ** But that is no longer true.  The limit is now strictly enforced
8042 ** at all times.
8043 */
8044 #ifndef SQLITE_MAX_EXPR_DEPTH
8045 # define SQLITE_MAX_EXPR_DEPTH 1000
8046 #endif
8047
8048 /*
8049 ** The maximum number of terms in a compound SELECT statement.
8050 ** The code generator for compound SELECT statements does one
8051 ** level of recursion for each term.  A stack overflow can result
8052 ** if the number of terms is too large.  In practice, most SQL
8053 ** never has more than 3 or 4 terms.  Use a value of 0 to disable
8054 ** any limit on the number of terms in a compount SELECT.
8055 */
8056 #ifndef SQLITE_MAX_COMPOUND_SELECT
8057 # define SQLITE_MAX_COMPOUND_SELECT 500
8058 #endif
8059
8060 /*
8061 ** The maximum number of opcodes in a VDBE program.
8062 ** Not currently enforced.
8063 */
8064 #ifndef SQLITE_MAX_VDBE_OP
8065 # define SQLITE_MAX_VDBE_OP 25000
8066 #endif
8067
8068 /*
8069 ** The maximum number of arguments to an SQL function.
8070 */
8071 #ifndef SQLITE_MAX_FUNCTION_ARG
8072 # define SQLITE_MAX_FUNCTION_ARG 127
8073 #endif
8074
8075 /*
8076 ** The suggested maximum number of in-memory pages to use for
8077 ** the main database table and for temporary tables.
8078 **
8079 ** IMPLEMENTATION-OF: R-31093-59126 The default suggested cache size
8080 ** is 2000 pages.
8081 ** IMPLEMENTATION-OF: R-48205-43578 The default suggested cache size can be
8082 ** altered using the SQLITE_DEFAULT_CACHE_SIZE compile-time options.
8083 */
8084 #ifndef SQLITE_DEFAULT_CACHE_SIZE
8085 # define SQLITE_DEFAULT_CACHE_SIZE  2000
8086 #endif
8087
8088 /*
8089 ** The default number of frames to accumulate in the log file before
8090 ** checkpointing the database in WAL mode.
8091 */
8092 #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
8093 # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT  1000
8094 #endif
8095
8096 /*
8097 ** The maximum number of attached databases.  This must be between 0
8098 ** and 62.  The upper bound on 62 is because a 64-bit integer bitmap
8099 ** is used internally to track attached databases.
8100 */
8101 #ifndef SQLITE_MAX_ATTACHED
8102 # define SQLITE_MAX_ATTACHED 10
8103 #endif
8104
8105
8106 /*
8107 ** The maximum value of a ?nnn wildcard that the parser will accept.
8108 */
8109 #ifndef SQLITE_MAX_VARIABLE_NUMBER
8110 # define SQLITE_MAX_VARIABLE_NUMBER 999
8111 #endif
8112
8113 /* Maximum page size.  The upper bound on this value is 65536.  This a limit
8114 ** imposed by the use of 16-bit offsets within each page.
8115 **
8116 ** Earlier versions of SQLite allowed the user to change this value at
8117 ** compile time. This is no longer permitted, on the grounds that it creates
8118 ** a library that is technically incompatible with an SQLite library 
8119 ** compiled with a different limit. If a process operating on a database 
8120 ** with a page-size of 65536 bytes crashes, then an instance of SQLite 
8121 ** compiled with the default page-size limit will not be able to rollback 
8122 ** the aborted transaction. This could lead to database corruption.
8123 */
8124 #ifdef SQLITE_MAX_PAGE_SIZE
8125 # undef SQLITE_MAX_PAGE_SIZE
8126 #endif
8127 #define SQLITE_MAX_PAGE_SIZE 65536
8128
8129
8130 /*
8131 ** The default size of a database page.
8132 */
8133 #ifndef SQLITE_DEFAULT_PAGE_SIZE
8134 # define SQLITE_DEFAULT_PAGE_SIZE 1024
8135 #endif
8136 #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
8137 # undef SQLITE_DEFAULT_PAGE_SIZE
8138 # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
8139 #endif
8140
8141 /*
8142 ** Ordinarily, if no value is explicitly provided, SQLite creates databases
8143 ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
8144 ** device characteristics (sector-size and atomic write() support),
8145 ** SQLite may choose a larger value. This constant is the maximum value
8146 ** SQLite will choose on its own.
8147 */
8148 #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
8149 # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
8150 #endif
8151 #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
8152 # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
8153 # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
8154 #endif
8155
8156
8157 /*
8158 ** Maximum number of pages in one database file.
8159 **
8160 ** This is really just the default value for the max_page_count pragma.
8161 ** This value can be lowered (or raised) at run-time using that the
8162 ** max_page_count macro.
8163 */
8164 #ifndef SQLITE_MAX_PAGE_COUNT
8165 # define SQLITE_MAX_PAGE_COUNT 1073741823
8166 #endif
8167
8168 /*
8169 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
8170 ** operator.
8171 */
8172 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
8173 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
8174 #endif
8175
8176 /*
8177 ** Maximum depth of recursion for triggers.
8178 **
8179 ** A value of 1 means that a trigger program will not be able to itself
8180 ** fire any triggers. A value of 0 means that no trigger programs at all 
8181 ** may be executed.
8182 */
8183 #ifndef SQLITE_MAX_TRIGGER_DEPTH
8184 # define SQLITE_MAX_TRIGGER_DEPTH 1000
8185 #endif
8186
8187 /************** End of sqliteLimit.h *****************************************/
8188 /************** Continuing where we left off in sqliteInt.h ******************/
8189
8190 /* Disable nuisance warnings on Borland compilers */
8191 #if defined(__BORLANDC__)
8192 #pragma warn -rch /* unreachable code */
8193 #pragma warn -ccc /* Condition is always true or false */
8194 #pragma warn -aus /* Assigned value is never used */
8195 #pragma warn -csu /* Comparing signed and unsigned */
8196 #pragma warn -spa /* Suspicious pointer arithmetic */
8197 #endif
8198
8199 /*
8200 ** Include standard header files as necessary
8201 */
8202 #ifdef HAVE_STDINT_H
8203 #include <stdint.h>
8204 #endif
8205 #ifdef HAVE_INTTYPES_H
8206 #include <inttypes.h>
8207 #endif
8208
8209 /*
8210 ** The following macros are used to cast pointers to integers and
8211 ** integers to pointers.  The way you do this varies from one compiler
8212 ** to the next, so we have developed the following set of #if statements
8213 ** to generate appropriate macros for a wide range of compilers.
8214 **
8215 ** The correct "ANSI" way to do this is to use the intptr_t type. 
8216 ** Unfortunately, that typedef is not available on all compilers, or
8217 ** if it is available, it requires an #include of specific headers
8218 ** that vary from one machine to the next.
8219 **
8220 ** Ticket #3860:  The llvm-gcc-4.2 compiler from Apple chokes on
8221 ** the ((void*)&((char*)0)[X]) construct.  But MSVC chokes on ((void*)(X)).
8222 ** So we have to define the macros in different ways depending on the
8223 ** compiler.
8224 */
8225 #if defined(__PTRDIFF_TYPE__)  /* This case should work for GCC */
8226 # define SQLITE_INT_TO_PTR(X)  ((void*)(__PTRDIFF_TYPE__)(X))
8227 # define SQLITE_PTR_TO_INT(X)  ((int)(__PTRDIFF_TYPE__)(X))
8228 #elif !defined(__GNUC__)       /* Works for compilers other than LLVM */
8229 # define SQLITE_INT_TO_PTR(X)  ((void*)&((char*)0)[X])
8230 # define SQLITE_PTR_TO_INT(X)  ((int)(((char*)X)-(char*)0))
8231 #elif defined(HAVE_STDINT_H)   /* Use this case if we have ANSI headers */
8232 # define SQLITE_INT_TO_PTR(X)  ((void*)(intptr_t)(X))
8233 # define SQLITE_PTR_TO_INT(X)  ((int)(intptr_t)(X))
8234 #else                          /* Generates a warning - but it always works */
8235 # define SQLITE_INT_TO_PTR(X)  ((void*)(X))
8236 # define SQLITE_PTR_TO_INT(X)  ((int)(X))
8237 #endif
8238
8239 /*
8240 ** A macro to hint to the compiler that a function should not be
8241 ** inlined.
8242 */
8243 #if defined(__GNUC__)
8244 #  define SQLITE_NOINLINE  __attribute__((noinline))
8245 #elif defined(_MSC_VER) && _MSC_VER>=1310
8246 #  define SQLITE_NOINLINE  __declspec(noinline)
8247 #else
8248 #  define SQLITE_NOINLINE
8249 #endif
8250
8251 /*
8252 ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
8253 ** 0 means mutexes are permanently disable and the library is never
8254 ** threadsafe.  1 means the library is serialized which is the highest
8255 ** level of threadsafety.  2 means the library is multithreaded - multiple
8256 ** threads can use SQLite as long as no two threads try to use the same
8257 ** database connection at the same time.
8258 **
8259 ** Older versions of SQLite used an optional THREADSAFE macro.
8260 ** We support that for legacy.
8261 */
8262 #if !defined(SQLITE_THREADSAFE)
8263 # if defined(THREADSAFE)
8264 #   define SQLITE_THREADSAFE THREADSAFE
8265 # else
8266 #   define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
8267 # endif
8268 #endif
8269
8270 /*
8271 ** Powersafe overwrite is on by default.  But can be turned off using
8272 ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
8273 */
8274 #ifndef SQLITE_POWERSAFE_OVERWRITE
8275 # define SQLITE_POWERSAFE_OVERWRITE 1
8276 #endif
8277
8278 /*
8279 ** EVIDENCE-OF: R-25715-37072 Memory allocation statistics are enabled by
8280 ** default unless SQLite is compiled with SQLITE_DEFAULT_MEMSTATUS=0 in
8281 ** which case memory allocation statistics are disabled by default.
8282 */
8283 #if !defined(SQLITE_DEFAULT_MEMSTATUS)
8284 # define SQLITE_DEFAULT_MEMSTATUS 1
8285 #endif
8286
8287 /*
8288 ** Exactly one of the following macros must be defined in order to
8289 ** specify which memory allocation subsystem to use.
8290 **
8291 **     SQLITE_SYSTEM_MALLOC          // Use normal system malloc()
8292 **     SQLITE_WIN32_MALLOC           // Use Win32 native heap API
8293 **     SQLITE_ZERO_MALLOC            // Use a stub allocator that always fails
8294 **     SQLITE_MEMDEBUG               // Debugging version of system malloc()
8295 **
8296 ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
8297 ** assert() macro is enabled, each call into the Win32 native heap subsystem
8298 ** will cause HeapValidate to be called.  If heap validation should fail, an
8299 ** assertion will be triggered.
8300 **
8301 ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
8302 ** the default.
8303 */
8304 #if defined(SQLITE_SYSTEM_MALLOC) \
8305   + defined(SQLITE_WIN32_MALLOC) \
8306   + defined(SQLITE_ZERO_MALLOC) \
8307   + defined(SQLITE_MEMDEBUG)>1
8308 # error "Two or more of the following compile-time configuration options\
8309  are defined but at most one is allowed:\
8310  SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
8311  SQLITE_ZERO_MALLOC"
8312 #endif
8313 #if defined(SQLITE_SYSTEM_MALLOC) \
8314   + defined(SQLITE_WIN32_MALLOC) \
8315   + defined(SQLITE_ZERO_MALLOC) \
8316   + defined(SQLITE_MEMDEBUG)==0
8317 # define SQLITE_SYSTEM_MALLOC 1
8318 #endif
8319
8320 /*
8321 ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
8322 ** sizes of memory allocations below this value where possible.
8323 */
8324 #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
8325 # define SQLITE_MALLOC_SOFT_LIMIT 1024
8326 #endif
8327
8328 /*
8329 ** We need to define _XOPEN_SOURCE as follows in order to enable
8330 ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
8331 ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
8332 ** it.
8333 */
8334 #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
8335 #  define _XOPEN_SOURCE 600
8336 #endif
8337
8338 /*
8339 ** NDEBUG and SQLITE_DEBUG are opposites.  It should always be true that
8340 ** defined(NDEBUG)==!defined(SQLITE_DEBUG).  If this is not currently true,
8341 ** make it true by defining or undefining NDEBUG.
8342 **
8343 ** Setting NDEBUG makes the code smaller and faster by disabling the
8344 ** assert() statements in the code.  So we want the default action
8345 ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
8346 ** is set.  Thus NDEBUG becomes an opt-in rather than an opt-out
8347 ** feature.
8348 */
8349 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
8350 # define NDEBUG 1
8351 #endif
8352 #if defined(NDEBUG) && defined(SQLITE_DEBUG)
8353 # undef NDEBUG
8354 #endif
8355
8356 /*
8357 ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
8358 */
8359 #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
8360 # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
8361 #endif
8362
8363 /*
8364 ** The testcase() macro is used to aid in coverage testing.  When 
8365 ** doing coverage testing, the condition inside the argument to
8366 ** testcase() must be evaluated both true and false in order to
8367 ** get full branch coverage.  The testcase() macro is inserted
8368 ** to help ensure adequate test coverage in places where simple
8369 ** condition/decision coverage is inadequate.  For example, testcase()
8370 ** can be used to make sure boundary values are tested.  For
8371 ** bitmask tests, testcase() can be used to make sure each bit
8372 ** is significant and used at least once.  On switch statements
8373 ** where multiple cases go to the same block of code, testcase()
8374 ** can insure that all cases are evaluated.
8375 **
8376 */
8377 #ifdef SQLITE_COVERAGE_TEST
8378 SQLITE_PRIVATE   void sqlite3Coverage(int);
8379 # define testcase(X)  if( X ){ sqlite3Coverage(__LINE__); }
8380 #else
8381 # define testcase(X)
8382 #endif
8383
8384 /*
8385 ** The TESTONLY macro is used to enclose variable declarations or
8386 ** other bits of code that are needed to support the arguments
8387 ** within testcase() and assert() macros.
8388 */
8389 #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
8390 # define TESTONLY(X)  X
8391 #else
8392 # define TESTONLY(X)
8393 #endif
8394
8395 /*
8396 ** Sometimes we need a small amount of code such as a variable initialization
8397 ** to setup for a later assert() statement.  We do not want this code to
8398 ** appear when assert() is disabled.  The following macro is therefore
8399 ** used to contain that setup code.  The "VVA" acronym stands for
8400 ** "Verification, Validation, and Accreditation".  In other words, the
8401 ** code within VVA_ONLY() will only run during verification processes.
8402 */
8403 #ifndef NDEBUG
8404 # define VVA_ONLY(X)  X
8405 #else
8406 # define VVA_ONLY(X)
8407 #endif
8408
8409 /*
8410 ** The ALWAYS and NEVER macros surround boolean expressions which 
8411 ** are intended to always be true or false, respectively.  Such
8412 ** expressions could be omitted from the code completely.  But they
8413 ** are included in a few cases in order to enhance the resilience
8414 ** of SQLite to unexpected behavior - to make the code "self-healing"
8415 ** or "ductile" rather than being "brittle" and crashing at the first
8416 ** hint of unplanned behavior.
8417 **
8418 ** In other words, ALWAYS and NEVER are added for defensive code.
8419 **
8420 ** When doing coverage testing ALWAYS and NEVER are hard-coded to
8421 ** be true and false so that the unreachable code they specify will
8422 ** not be counted as untested code.
8423 */
8424 #if defined(SQLITE_COVERAGE_TEST)
8425 # define ALWAYS(X)      (1)
8426 # define NEVER(X)       (0)
8427 #elif !defined(NDEBUG)
8428 # define ALWAYS(X)      ((X)?1:(assert(0),0))
8429 # define NEVER(X)       ((X)?(assert(0),1):0)
8430 #else
8431 # define ALWAYS(X)      (X)
8432 # define NEVER(X)       (X)
8433 #endif
8434
8435 /*
8436 ** Return true (non-zero) if the input is an integer that is too large
8437 ** to fit in 32-bits.  This macro is used inside of various testcase()
8438 ** macros to verify that we have tested SQLite for large-file support.
8439 */
8440 #define IS_BIG_INT(X)  (((X)&~(i64)0xffffffff)!=0)
8441
8442 /*
8443 ** The macro unlikely() is a hint that surrounds a boolean
8444 ** expression that is usually false.  Macro likely() surrounds
8445 ** a boolean expression that is usually true.  These hints could,
8446 ** in theory, be used by the compiler to generate better code, but
8447 ** currently they are just comments for human readers.
8448 */
8449 #define likely(X)    (X)
8450 #define unlikely(X)  (X)
8451
8452 /************** Include hash.h in the middle of sqliteInt.h ******************/
8453 /************** Begin file hash.h ********************************************/
8454 /*
8455 ** 2001 September 22
8456 **
8457 ** The author disclaims copyright to this source code.  In place of
8458 ** a legal notice, here is a blessing:
8459 **
8460 **    May you do good and not evil.
8461 **    May you find forgiveness for yourself and forgive others.
8462 **    May you share freely, never taking more than you give.
8463 **
8464 *************************************************************************
8465 ** This is the header file for the generic hash-table implementation
8466 ** used in SQLite.
8467 */
8468 #ifndef _SQLITE_HASH_H_
8469 #define _SQLITE_HASH_H_
8470
8471 /* Forward declarations of structures. */
8472 typedef struct Hash Hash;
8473 typedef struct HashElem HashElem;
8474
8475 /* A complete hash table is an instance of the following structure.
8476 ** The internals of this structure are intended to be opaque -- client
8477 ** code should not attempt to access or modify the fields of this structure
8478 ** directly.  Change this structure only by using the routines below.
8479 ** However, some of the "procedures" and "functions" for modifying and
8480 ** accessing this structure are really macros, so we can't really make
8481 ** this structure opaque.
8482 **
8483 ** All elements of the hash table are on a single doubly-linked list.
8484 ** Hash.first points to the head of this list.
8485 **
8486 ** There are Hash.htsize buckets.  Each bucket points to a spot in
8487 ** the global doubly-linked list.  The contents of the bucket are the
8488 ** element pointed to plus the next _ht.count-1 elements in the list.
8489 **
8490 ** Hash.htsize and Hash.ht may be zero.  In that case lookup is done
8491 ** by a linear search of the global list.  For small tables, the 
8492 ** Hash.ht table is never allocated because if there are few elements
8493 ** in the table, it is faster to do a linear search than to manage
8494 ** the hash table.
8495 */
8496 struct Hash {
8497   unsigned int htsize;      /* Number of buckets in the hash table */
8498   unsigned int count;       /* Number of entries in this table */
8499   HashElem *first;          /* The first element of the array */
8500   struct _ht {              /* the hash table */
8501     int count;                 /* Number of entries with this hash */
8502     HashElem *chain;           /* Pointer to first entry with this hash */
8503   } *ht;
8504 };
8505
8506 /* Each element in the hash table is an instance of the following 
8507 ** structure.  All elements are stored on a single doubly-linked list.
8508 **
8509 ** Again, this structure is intended to be opaque, but it can't really
8510 ** be opaque because it is used by macros.
8511 */
8512 struct HashElem {
8513   HashElem *next, *prev;       /* Next and previous elements in the table */
8514   void *data;                  /* Data associated with this element */
8515   const char *pKey;            /* Key associated with this element */
8516 };
8517
8518 /*
8519 ** Access routines.  To delete, insert a NULL pointer.
8520 */
8521 SQLITE_PRIVATE void sqlite3HashInit(Hash*);
8522 SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
8523 SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
8524 SQLITE_PRIVATE void sqlite3HashClear(Hash*);
8525
8526 /*
8527 ** Macros for looping over all elements of a hash table.  The idiom is
8528 ** like this:
8529 **
8530 **   Hash h;
8531 **   HashElem *p;
8532 **   ...
8533 **   for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
8534 **     SomeStructure *pData = sqliteHashData(p);
8535 **     // do something with pData
8536 **   }
8537 */
8538 #define sqliteHashFirst(H)  ((H)->first)
8539 #define sqliteHashNext(E)   ((E)->next)
8540 #define sqliteHashData(E)   ((E)->data)
8541 /* #define sqliteHashKey(E)    ((E)->pKey) // NOT USED */
8542 /* #define sqliteHashKeysize(E) ((E)->nKey)  // NOT USED */
8543
8544 /*
8545 ** Number of entries in a hash table
8546 */
8547 /* #define sqliteHashCount(H)  ((H)->count) // NOT USED */
8548
8549 #endif /* _SQLITE_HASH_H_ */
8550
8551 /************** End of hash.h ************************************************/
8552 /************** Continuing where we left off in sqliteInt.h ******************/
8553 /************** Include parse.h in the middle of sqliteInt.h *****************/
8554 /************** Begin file parse.h *******************************************/
8555 #define TK_SEMI                             1
8556 #define TK_EXPLAIN                          2
8557 #define TK_QUERY                            3
8558 #define TK_PLAN                             4
8559 #define TK_BEGIN                            5
8560 #define TK_TRANSACTION                      6
8561 #define TK_DEFERRED                         7
8562 #define TK_IMMEDIATE                        8
8563 #define TK_EXCLUSIVE                        9
8564 #define TK_COMMIT                          10
8565 #define TK_END                             11
8566 #define TK_ROLLBACK                        12
8567 #define TK_SAVEPOINT                       13
8568 #define TK_RELEASE                         14
8569 #define TK_TO                              15
8570 #define TK_TABLE                           16
8571 #define TK_CREATE                          17
8572 #define TK_IF                              18
8573 #define TK_NOT                             19
8574 #define TK_EXISTS                          20
8575 #define TK_TEMP                            21
8576 #define TK_LP                              22
8577 #define TK_RP                              23
8578 #define TK_AS                              24
8579 #define TK_WITHOUT                         25
8580 #define TK_COMMA                           26
8581 #define TK_ID                              27
8582 #define TK_INDEXED                         28
8583 #define TK_ABORT                           29
8584 #define TK_ACTION                          30
8585 #define TK_AFTER                           31
8586 #define TK_ANALYZE                         32
8587 #define TK_ASC                             33
8588 #define TK_ATTACH                          34
8589 #define TK_BEFORE                          35
8590 #define TK_BY                              36
8591 #define TK_CASCADE                         37
8592 #define TK_CAST                            38
8593 #define TK_COLUMNKW                        39
8594 #define TK_CONFLICT                        40
8595 #define TK_DATABASE                        41
8596 #define TK_DESC                            42
8597 #define TK_DETACH                          43
8598 #define TK_EACH                            44
8599 #define TK_FAIL                            45
8600 #define TK_FOR                             46
8601 #define TK_IGNORE                          47
8602 #define TK_INITIALLY                       48
8603 #define TK_INSTEAD                         49
8604 #define TK_LIKE_KW                         50
8605 #define TK_MATCH                           51
8606 #define TK_NO                              52
8607 #define TK_KEY                             53
8608 #define TK_OF                              54
8609 #define TK_OFFSET                          55
8610 #define TK_PRAGMA                          56
8611 #define TK_RAISE                           57
8612 #define TK_RECURSIVE                       58
8613 #define TK_REPLACE                         59
8614 #define TK_RESTRICT                        60
8615 #define TK_ROW                             61
8616 #define TK_TRIGGER                         62
8617 #define TK_VACUUM                          63
8618 #define TK_VIEW                            64
8619 #define TK_VIRTUAL                         65
8620 #define TK_WITH                            66
8621 #define TK_REINDEX                         67
8622 #define TK_RENAME                          68
8623 #define TK_CTIME_KW                        69
8624 #define TK_ANY                             70
8625 #define TK_OR                              71
8626 #define TK_AND                             72
8627 #define TK_IS                              73
8628 #define TK_BETWEEN                         74
8629 #define TK_IN                              75
8630 #define TK_ISNULL                          76
8631 #define TK_NOTNULL                         77
8632 #define TK_NE                              78
8633 #define TK_EQ                              79
8634 #define TK_GT                              80
8635 #define TK_LE                              81
8636 #define TK_LT                              82
8637 #define TK_GE                              83
8638 #define TK_ESCAPE                          84
8639 #define TK_BITAND                          85
8640 #define TK_BITOR                           86
8641 #define TK_LSHIFT                          87
8642 #define TK_RSHIFT                          88
8643 #define TK_PLUS                            89
8644 #define TK_MINUS                           90
8645 #define TK_STAR                            91
8646 #define TK_SLASH                           92
8647 #define TK_REM                             93
8648 #define TK_CONCAT                          94
8649 #define TK_COLLATE                         95
8650 #define TK_BITNOT                          96
8651 #define TK_STRING                          97
8652 #define TK_JOIN_KW                         98
8653 #define TK_CONSTRAINT                      99
8654 #define TK_DEFAULT                        100
8655 #define TK_NULL                           101
8656 #define TK_PRIMARY                        102
8657 #define TK_UNIQUE                         103
8658 #define TK_CHECK                          104
8659 #define TK_REFERENCES                     105
8660 #define TK_AUTOINCR                       106
8661 #define TK_ON                             107
8662 #define TK_INSERT                         108
8663 #define TK_DELETE                         109
8664 #define TK_UPDATE                         110
8665 #define TK_SET                            111
8666 #define TK_DEFERRABLE                     112
8667 #define TK_FOREIGN                        113
8668 #define TK_DROP                           114
8669 #define TK_UNION                          115
8670 #define TK_ALL                            116
8671 #define TK_EXCEPT                         117
8672 #define TK_INTERSECT                      118
8673 #define TK_SELECT                         119
8674 #define TK_VALUES                         120
8675 #define TK_DISTINCT                       121
8676 #define TK_DOT                            122
8677 #define TK_FROM                           123
8678 #define TK_JOIN                           124
8679 #define TK_USING                          125
8680 #define TK_ORDER                          126
8681 #define TK_GROUP                          127
8682 #define TK_HAVING                         128
8683 #define TK_LIMIT                          129
8684 #define TK_WHERE                          130
8685 #define TK_INTO                           131
8686 #define TK_INTEGER                        132
8687 #define TK_FLOAT                          133
8688 #define TK_BLOB                           134
8689 #define TK_VARIABLE                       135
8690 #define TK_CASE                           136
8691 #define TK_WHEN                           137
8692 #define TK_THEN                           138
8693 #define TK_ELSE                           139
8694 #define TK_INDEX                          140
8695 #define TK_ALTER                          141
8696 #define TK_ADD                            142
8697 #define TK_TO_TEXT                        143
8698 #define TK_TO_BLOB                        144
8699 #define TK_TO_NUMERIC                     145
8700 #define TK_TO_INT                         146
8701 #define TK_TO_REAL                        147
8702 #define TK_ISNOT                          148
8703 #define TK_END_OF_FILE                    149
8704 #define TK_ILLEGAL                        150
8705 #define TK_SPACE                          151
8706 #define TK_UNCLOSED_STRING                152
8707 #define TK_FUNCTION                       153
8708 #define TK_COLUMN                         154
8709 #define TK_AGG_FUNCTION                   155
8710 #define TK_AGG_COLUMN                     156
8711 #define TK_UMINUS                         157
8712 #define TK_UPLUS                          158
8713 #define TK_REGISTER                       159
8714
8715 /************** End of parse.h ***********************************************/
8716 /************** Continuing where we left off in sqliteInt.h ******************/
8717 #include <stdio.h>
8718 #include <stdlib.h>
8719 #include <string.h>
8720 #include <assert.h>
8721 #include <stddef.h>
8722
8723 /*
8724 ** If compiling for a processor that lacks floating point support,
8725 ** substitute integer for floating-point
8726 */
8727 #ifdef SQLITE_OMIT_FLOATING_POINT
8728 # define double sqlite_int64
8729 # define float sqlite_int64
8730 # define LONGDOUBLE_TYPE sqlite_int64
8731 # ifndef SQLITE_BIG_DBL
8732 #   define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
8733 # endif
8734 # define SQLITE_OMIT_DATETIME_FUNCS 1
8735 # define SQLITE_OMIT_TRACE 1
8736 # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
8737 # undef SQLITE_HAVE_ISNAN
8738 #endif
8739 #ifndef SQLITE_BIG_DBL
8740 # define SQLITE_BIG_DBL (1e99)
8741 #endif
8742
8743 /*
8744 ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
8745 ** afterward. Having this macro allows us to cause the C compiler 
8746 ** to omit code used by TEMP tables without messy #ifndef statements.
8747 */
8748 #ifdef SQLITE_OMIT_TEMPDB
8749 #define OMIT_TEMPDB 1
8750 #else
8751 #define OMIT_TEMPDB 0
8752 #endif
8753
8754 /*
8755 ** The "file format" number is an integer that is incremented whenever
8756 ** the VDBE-level file format changes.  The following macros define the
8757 ** the default file format for new databases and the maximum file format
8758 ** that the library can read.
8759 */
8760 #define SQLITE_MAX_FILE_FORMAT 4
8761 #ifndef SQLITE_DEFAULT_FILE_FORMAT
8762 # define SQLITE_DEFAULT_FILE_FORMAT 4
8763 #endif
8764
8765 /*
8766 ** Determine whether triggers are recursive by default.  This can be
8767 ** changed at run-time using a pragma.
8768 */
8769 #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
8770 # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
8771 #endif
8772
8773 /*
8774 ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
8775 ** on the command-line
8776 */
8777 #ifndef SQLITE_TEMP_STORE
8778 # define SQLITE_TEMP_STORE 1
8779 # define SQLITE_TEMP_STORE_xc 1  /* Exclude from ctime.c */
8780 #endif
8781
8782 /*
8783 ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
8784 ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it 
8785 ** to zero.
8786 */
8787 #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
8788 # undef SQLITE_MAX_WORKER_THREADS
8789 # define SQLITE_MAX_WORKER_THREADS 0
8790 #endif
8791 #ifndef SQLITE_MAX_WORKER_THREADS
8792 # define SQLITE_MAX_WORKER_THREADS 8
8793 #endif
8794 #ifndef SQLITE_DEFAULT_WORKER_THREADS
8795 # define SQLITE_DEFAULT_WORKER_THREADS 0
8796 #endif
8797 #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
8798 # undef SQLITE_MAX_WORKER_THREADS
8799 # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
8800 #endif
8801
8802
8803 /*
8804 ** GCC does not define the offsetof() macro so we'll have to do it
8805 ** ourselves.
8806 */
8807 #ifndef offsetof
8808 #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
8809 #endif
8810
8811 /*
8812 ** Macros to compute minimum and maximum of two numbers.
8813 */
8814 #define MIN(A,B) ((A)<(B)?(A):(B))
8815 #define MAX(A,B) ((A)>(B)?(A):(B))
8816
8817 /*
8818 ** Swap two objects of type TYPE.
8819 */
8820 #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
8821
8822 /*
8823 ** Check to see if this machine uses EBCDIC.  (Yes, believe it or
8824 ** not, there are still machines out there that use EBCDIC.)
8825 */
8826 #if 'A' == '\301'
8827 # define SQLITE_EBCDIC 1
8828 #else
8829 # define SQLITE_ASCII 1
8830 #endif
8831
8832 /*
8833 ** Integers of known sizes.  These typedefs might change for architectures
8834 ** where the sizes very.  Preprocessor macros are available so that the
8835 ** types can be conveniently redefined at compile-type.  Like this:
8836 **
8837 **         cc '-DUINTPTR_TYPE=long long int' ...
8838 */
8839 #ifndef UINT32_TYPE
8840 # ifdef HAVE_UINT32_T
8841 #  define UINT32_TYPE uint32_t
8842 # else
8843 #  define UINT32_TYPE unsigned int
8844 # endif
8845 #endif
8846 #ifndef UINT16_TYPE
8847 # ifdef HAVE_UINT16_T
8848 #  define UINT16_TYPE uint16_t
8849 # else
8850 #  define UINT16_TYPE unsigned short int
8851 # endif
8852 #endif
8853 #ifndef INT16_TYPE
8854 # ifdef HAVE_INT16_T
8855 #  define INT16_TYPE int16_t
8856 # else
8857 #  define INT16_TYPE short int
8858 # endif
8859 #endif
8860 #ifndef UINT8_TYPE
8861 # ifdef HAVE_UINT8_T
8862 #  define UINT8_TYPE uint8_t
8863 # else
8864 #  define UINT8_TYPE unsigned char
8865 # endif
8866 #endif
8867 #ifndef INT8_TYPE
8868 # ifdef HAVE_INT8_T
8869 #  define INT8_TYPE int8_t
8870 # else
8871 #  define INT8_TYPE signed char
8872 # endif
8873 #endif
8874 #ifndef LONGDOUBLE_TYPE
8875 # define LONGDOUBLE_TYPE long double
8876 #endif
8877 typedef sqlite_int64 i64;          /* 8-byte signed integer */
8878 typedef sqlite_uint64 u64;         /* 8-byte unsigned integer */
8879 typedef UINT32_TYPE u32;           /* 4-byte unsigned integer */
8880 typedef UINT16_TYPE u16;           /* 2-byte unsigned integer */
8881 typedef INT16_TYPE i16;            /* 2-byte signed integer */
8882 typedef UINT8_TYPE u8;             /* 1-byte unsigned integer */
8883 typedef INT8_TYPE i8;              /* 1-byte signed integer */
8884
8885 /*
8886 ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
8887 ** that can be stored in a u32 without loss of data.  The value
8888 ** is 0x00000000ffffffff.  But because of quirks of some compilers, we
8889 ** have to specify the value in the less intuitive manner shown:
8890 */
8891 #define SQLITE_MAX_U32  ((((u64)1)<<32)-1)
8892
8893 /*
8894 ** The datatype used to store estimates of the number of rows in a
8895 ** table or index.  This is an unsigned integer type.  For 99.9% of
8896 ** the world, a 32-bit integer is sufficient.  But a 64-bit integer
8897 ** can be used at compile-time if desired.
8898 */
8899 #ifdef SQLITE_64BIT_STATS
8900  typedef u64 tRowcnt;    /* 64-bit only if requested at compile-time */
8901 #else
8902  typedef u32 tRowcnt;    /* 32-bit is the default */
8903 #endif
8904
8905 /*
8906 ** Estimated quantities used for query planning are stored as 16-bit
8907 ** logarithms.  For quantity X, the value stored is 10*log2(X).  This
8908 ** gives a possible range of values of approximately 1.0e986 to 1e-986.
8909 ** But the allowed values are "grainy".  Not every value is representable.
8910 ** For example, quantities 16 and 17 are both represented by a LogEst
8911 ** of 40.  However, since LogEst quantities are suppose to be estimates,
8912 ** not exact values, this imprecision is not a problem.
8913 **
8914 ** "LogEst" is short for "Logarithmic Estimate".
8915 **
8916 ** Examples:
8917 **      1 -> 0              20 -> 43          10000 -> 132
8918 **      2 -> 10             25 -> 46          25000 -> 146
8919 **      3 -> 16            100 -> 66        1000000 -> 199
8920 **      4 -> 20           1000 -> 99        1048576 -> 200
8921 **     10 -> 33           1024 -> 100    4294967296 -> 320
8922 **
8923 ** The LogEst can be negative to indicate fractional values. 
8924 ** Examples:
8925 **
8926 **    0.5 -> -10           0.1 -> -33        0.0625 -> -40
8927 */
8928 typedef INT16_TYPE LogEst;
8929
8930 /*
8931 ** Set the SQLITE_PTRSIZE macro to the number of bytes in a pointer
8932 */
8933 #ifndef SQLITE_PTRSIZE
8934 # if defined(__SIZEOF_POINTER__)
8935 #   define SQLITE_PTRSIZE __SIZEOF_POINTER__
8936 # elif defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
8937        defined(_M_ARM)   || defined(__arm__)    || defined(__x86)
8938 #   define SQLITE_PTRSIZE 4
8939 # else
8940 #   define SQLITE_PTRSIZE 8
8941 # endif
8942 #endif
8943
8944 /*
8945 ** Macros to determine whether the machine is big or little endian,
8946 ** and whether or not that determination is run-time or compile-time.
8947 **
8948 ** For best performance, an attempt is made to guess at the byte-order
8949 ** using C-preprocessor macros.  If that is unsuccessful, or if
8950 ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
8951 ** at run-time.
8952 */
8953 #ifdef SQLITE_AMALGAMATION
8954 SQLITE_PRIVATE const int sqlite3one = 1;
8955 #else
8956 SQLITE_PRIVATE const int sqlite3one;
8957 #endif
8958 #if (defined(i386)     || defined(__i386__)   || defined(_M_IX86) ||    \
8959      defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)  ||    \
8960      defined(_M_AMD64) || defined(_M_ARM)     || defined(__x86)   ||    \
8961      defined(__arm__)) && !defined(SQLITE_RUNTIME_BYTEORDER)
8962 # define SQLITE_BYTEORDER    1234
8963 # define SQLITE_BIGENDIAN    0
8964 # define SQLITE_LITTLEENDIAN 1
8965 # define SQLITE_UTF16NATIVE  SQLITE_UTF16LE
8966 #endif
8967 #if (defined(sparc)    || defined(__ppc__))  \
8968     && !defined(SQLITE_RUNTIME_BYTEORDER)
8969 # define SQLITE_BYTEORDER    4321
8970 # define SQLITE_BIGENDIAN    1
8971 # define SQLITE_LITTLEENDIAN 0
8972 # define SQLITE_UTF16NATIVE  SQLITE_UTF16BE
8973 #endif
8974 #if !defined(SQLITE_BYTEORDER)
8975 # define SQLITE_BYTEORDER    0     /* 0 means "unknown at compile-time" */
8976 # define SQLITE_BIGENDIAN    (*(char *)(&sqlite3one)==0)
8977 # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
8978 # define SQLITE_UTF16NATIVE  (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
8979 #endif
8980
8981 /*
8982 ** Constants for the largest and smallest possible 64-bit signed integers.
8983 ** These macros are designed to work correctly on both 32-bit and 64-bit
8984 ** compilers.
8985 */
8986 #define LARGEST_INT64  (0xffffffff|(((i64)0x7fffffff)<<32))
8987 #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
8988
8989 /* 
8990 ** Round up a number to the next larger multiple of 8.  This is used
8991 ** to force 8-byte alignment on 64-bit architectures.
8992 */
8993 #define ROUND8(x)     (((x)+7)&~7)
8994
8995 /*
8996 ** Round down to the nearest multiple of 8
8997 */
8998 #define ROUNDDOWN8(x) ((x)&~7)
8999
9000 /*
9001 ** Assert that the pointer X is aligned to an 8-byte boundary.  This
9002 ** macro is used only within assert() to verify that the code gets
9003 ** all alignment restrictions correct.
9004 **
9005 ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
9006 ** underlying malloc() implementation might return us 4-byte aligned
9007 ** pointers.  In that case, only verify 4-byte alignment.
9008 */
9009 #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
9010 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&3)==0)
9011 #else
9012 # define EIGHT_BYTE_ALIGNMENT(X)   ((((char*)(X) - (char*)0)&7)==0)
9013 #endif
9014
9015 /*
9016 ** Disable MMAP on platforms where it is known to not work
9017 */
9018 #if defined(__OpenBSD__) || defined(__QNXNTO__)
9019 # undef SQLITE_MAX_MMAP_SIZE
9020 # define SQLITE_MAX_MMAP_SIZE 0
9021 #endif
9022
9023 /*
9024 ** Default maximum size of memory used by memory-mapped I/O in the VFS
9025 */
9026 #ifdef __APPLE__
9027 # include <TargetConditionals.h>
9028 # if TARGET_OS_IPHONE
9029 #   undef SQLITE_MAX_MMAP_SIZE
9030 #   define SQLITE_MAX_MMAP_SIZE 0
9031 # endif
9032 #endif
9033 #ifndef SQLITE_MAX_MMAP_SIZE
9034 # if defined(__linux__) \
9035   || defined(_WIN32) \
9036   || (defined(__APPLE__) && defined(__MACH__)) \
9037   || defined(__sun)
9038 #   define SQLITE_MAX_MMAP_SIZE 0x7fff0000  /* 2147418112 */
9039 # else
9040 #   define SQLITE_MAX_MMAP_SIZE 0
9041 # endif
9042 # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
9043 #endif
9044
9045 /*
9046 ** The default MMAP_SIZE is zero on all platforms.  Or, even if a larger
9047 ** default MMAP_SIZE is specified at compile-time, make sure that it does
9048 ** not exceed the maximum mmap size.
9049 */
9050 #ifndef SQLITE_DEFAULT_MMAP_SIZE
9051 # define SQLITE_DEFAULT_MMAP_SIZE 0
9052 # define SQLITE_DEFAULT_MMAP_SIZE_xc 1  /* Exclude from ctime.c */
9053 #endif
9054 #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
9055 # undef SQLITE_DEFAULT_MMAP_SIZE
9056 # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
9057 #endif
9058
9059 /*
9060 ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
9061 ** Priority is given to SQLITE_ENABLE_STAT4.  If either are defined, also
9062 ** define SQLITE_ENABLE_STAT3_OR_STAT4
9063 */
9064 #ifdef SQLITE_ENABLE_STAT4
9065 # undef SQLITE_ENABLE_STAT3
9066 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
9067 #elif SQLITE_ENABLE_STAT3
9068 # define SQLITE_ENABLE_STAT3_OR_STAT4 1
9069 #elif SQLITE_ENABLE_STAT3_OR_STAT4
9070 # undef SQLITE_ENABLE_STAT3_OR_STAT4
9071 #endif
9072
9073 /*
9074 ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
9075 ** the Select query generator tracing logic is turned on.
9076 */
9077 #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE)
9078 # define SELECTTRACE_ENABLED 1
9079 #else
9080 # define SELECTTRACE_ENABLED 0
9081 #endif
9082
9083 /*
9084 ** An instance of the following structure is used to store the busy-handler
9085 ** callback for a given sqlite handle. 
9086 **
9087 ** The sqlite.busyHandler member of the sqlite struct contains the busy
9088 ** callback for the database handle. Each pager opened via the sqlite
9089 ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
9090 ** callback is currently invoked only from within pager.c.
9091 */
9092 typedef struct BusyHandler BusyHandler;
9093 struct BusyHandler {
9094   int (*xFunc)(void *,int);  /* The busy callback */
9095   void *pArg;                /* First arg to busy callback */
9096   int nBusy;                 /* Incremented with each busy call */
9097 };
9098
9099 /*
9100 ** Name of the master database table.  The master database table
9101 ** is a special table that holds the names and attributes of all
9102 ** user tables and indices.
9103 */
9104 #define MASTER_NAME       "sqlite_master"
9105 #define TEMP_MASTER_NAME  "sqlite_temp_master"
9106
9107 /*
9108 ** The root-page of the master database table.
9109 */
9110 #define MASTER_ROOT       1
9111
9112 /*
9113 ** The name of the schema table.
9114 */
9115 #define SCHEMA_TABLE(x)  ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
9116
9117 /*
9118 ** A convenience macro that returns the number of elements in
9119 ** an array.
9120 */
9121 #define ArraySize(X)    ((int)(sizeof(X)/sizeof(X[0])))
9122
9123 /*
9124 ** Determine if the argument is a power of two
9125 */
9126 #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
9127
9128 /*
9129 ** The following value as a destructor means to use sqlite3DbFree().
9130 ** The sqlite3DbFree() routine requires two parameters instead of the 
9131 ** one parameter that destructors normally want.  So we have to introduce 
9132 ** this magic value that the code knows to handle differently.  Any 
9133 ** pointer will work here as long as it is distinct from SQLITE_STATIC
9134 ** and SQLITE_TRANSIENT.
9135 */
9136 #define SQLITE_DYNAMIC   ((sqlite3_destructor_type)sqlite3MallocSize)
9137
9138 /*
9139 ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
9140 ** not support Writable Static Data (WSD) such as global and static variables.
9141 ** All variables must either be on the stack or dynamically allocated from
9142 ** the heap.  When WSD is unsupported, the variable declarations scattered
9143 ** throughout the SQLite code must become constants instead.  The SQLITE_WSD
9144 ** macro is used for this purpose.  And instead of referencing the variable
9145 ** directly, we use its constant as a key to lookup the run-time allocated
9146 ** buffer that holds real variable.  The constant is also the initializer
9147 ** for the run-time allocated buffer.
9148 **
9149 ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
9150 ** macros become no-ops and have zero performance impact.
9151 */
9152 #ifdef SQLITE_OMIT_WSD
9153   #define SQLITE_WSD const
9154   #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
9155   #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
9156 SQLITE_API int SQLITE_STDCALL sqlite3_wsd_init(int N, int J);
9157 SQLITE_API void *SQLITE_STDCALL sqlite3_wsd_find(void *K, int L);
9158 #else
9159   #define SQLITE_WSD 
9160   #define GLOBAL(t,v) v
9161   #define sqlite3GlobalConfig sqlite3Config
9162 #endif
9163
9164 /*
9165 ** The following macros are used to suppress compiler warnings and to
9166 ** make it clear to human readers when a function parameter is deliberately 
9167 ** left unused within the body of a function. This usually happens when
9168 ** a function is called via a function pointer. For example the 
9169 ** implementation of an SQL aggregate step callback may not use the
9170 ** parameter indicating the number of arguments passed to the aggregate,
9171 ** if it knows that this is enforced elsewhere.
9172 **
9173 ** When a function parameter is not used at all within the body of a function,
9174 ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
9175 ** However, these macros may also be used to suppress warnings related to
9176 ** parameters that may or may not be used depending on compilation options.
9177 ** For example those parameters only used in assert() statements. In these
9178 ** cases the parameters are named as per the usual conventions.
9179 */
9180 #define UNUSED_PARAMETER(x) (void)(x)
9181 #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
9182
9183 /*
9184 ** Forward references to structures
9185 */
9186 typedef struct AggInfo AggInfo;
9187 typedef struct AuthContext AuthContext;
9188 typedef struct AutoincInfo AutoincInfo;
9189 typedef struct Bitvec Bitvec;
9190 typedef struct CollSeq CollSeq;
9191 typedef struct Column Column;
9192 typedef struct Db Db;
9193 typedef struct Schema Schema;
9194 typedef struct Expr Expr;
9195 typedef struct ExprList ExprList;
9196 typedef struct ExprSpan ExprSpan;
9197 typedef struct FKey FKey;
9198 typedef struct FuncDestructor FuncDestructor;
9199 typedef struct FuncDef FuncDef;
9200 typedef struct FuncDefHash FuncDefHash;
9201 typedef struct IdList IdList;
9202 typedef struct Index Index;
9203 typedef struct IndexSample IndexSample;
9204 typedef struct KeyClass KeyClass;
9205 typedef struct KeyInfo KeyInfo;
9206 typedef struct Lookaside Lookaside;
9207 typedef struct LookasideSlot LookasideSlot;
9208 typedef struct Module Module;
9209 typedef struct NameContext NameContext;
9210 typedef struct Parse Parse;
9211 typedef struct PrintfArguments PrintfArguments;
9212 typedef struct RowSet RowSet;
9213 typedef struct Savepoint Savepoint;
9214 typedef struct Select Select;
9215 typedef struct SQLiteThread SQLiteThread;
9216 typedef struct SelectDest SelectDest;
9217 typedef struct SrcList SrcList;
9218 typedef struct StrAccum StrAccum;
9219 typedef struct Table Table;
9220 typedef struct TableLock TableLock;
9221 typedef struct Token Token;
9222 typedef struct TreeView TreeView;
9223 typedef struct Trigger Trigger;
9224 typedef struct TriggerPrg TriggerPrg;
9225 typedef struct TriggerStep TriggerStep;
9226 typedef struct UnpackedRecord UnpackedRecord;
9227 typedef struct VTable VTable;
9228 typedef struct VtabCtx VtabCtx;
9229 typedef struct Walker Walker;
9230 typedef struct WhereInfo WhereInfo;
9231 typedef struct With With;
9232
9233 /*
9234 ** Defer sourcing vdbe.h and btree.h until after the "u8" and 
9235 ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
9236 ** pointer types (i.e. FuncDef) defined above.
9237 */
9238 /************** Include btree.h in the middle of sqliteInt.h *****************/
9239 /************** Begin file btree.h *******************************************/
9240 /*
9241 ** 2001 September 15
9242 **
9243 ** The author disclaims copyright to this source code.  In place of
9244 ** a legal notice, here is a blessing:
9245 **
9246 **    May you do good and not evil.
9247 **    May you find forgiveness for yourself and forgive others.
9248 **    May you share freely, never taking more than you give.
9249 **
9250 *************************************************************************
9251 ** This header file defines the interface that the sqlite B-Tree file
9252 ** subsystem.  See comments in the source code for a detailed description
9253 ** of what each interface routine does.
9254 */
9255 #ifndef _BTREE_H_
9256 #define _BTREE_H_
9257
9258 /* TODO: This definition is just included so other modules compile. It
9259 ** needs to be revisited.
9260 */
9261 #define SQLITE_N_BTREE_META 16
9262
9263 /*
9264 ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
9265 ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
9266 */
9267 #ifndef SQLITE_DEFAULT_AUTOVACUUM
9268   #define SQLITE_DEFAULT_AUTOVACUUM 0
9269 #endif
9270
9271 #define BTREE_AUTOVACUUM_NONE 0        /* Do not do auto-vacuum */
9272 #define BTREE_AUTOVACUUM_FULL 1        /* Do full auto-vacuum */
9273 #define BTREE_AUTOVACUUM_INCR 2        /* Incremental vacuum */
9274
9275 /*
9276 ** Forward declarations of structure
9277 */
9278 typedef struct Btree Btree;
9279 typedef struct BtCursor BtCursor;
9280 typedef struct BtShared BtShared;
9281
9282
9283 SQLITE_PRIVATE int sqlite3BtreeOpen(
9284   sqlite3_vfs *pVfs,       /* VFS to use with this b-tree */
9285   const char *zFilename,   /* Name of database file to open */
9286   sqlite3 *db,             /* Associated database connection */
9287   Btree **ppBtree,         /* Return open Btree* here */
9288   int flags,               /* Flags */
9289   int vfsFlags             /* Flags passed through to VFS open */
9290 );
9291
9292 /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
9293 ** following values.
9294 **
9295 ** NOTE:  These values must match the corresponding PAGER_ values in
9296 ** pager.h.
9297 */
9298 #define BTREE_OMIT_JOURNAL  1  /* Do not create or use a rollback journal */
9299 #define BTREE_MEMORY        2  /* This is an in-memory DB */
9300 #define BTREE_SINGLE        4  /* The file contains at most 1 b-tree */
9301 #define BTREE_UNORDERED     8  /* Use of a hash implementation is OK */
9302
9303 SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
9304 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
9305 #if SQLITE_MAX_MMAP_SIZE>0
9306 SQLITE_PRIVATE   int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
9307 #endif
9308 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
9309 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
9310 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
9311 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
9312 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
9313 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
9314 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
9315 SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree*);
9316 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
9317 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
9318 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
9319 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
9320 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
9321 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
9322 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
9323 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
9324 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
9325 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
9326 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
9327 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
9328 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
9329 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
9330 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
9331 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
9332 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
9333
9334 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
9335 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
9336 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
9337
9338 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
9339
9340 /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
9341 ** of the flags shown below.
9342 **
9343 ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
9344 ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
9345 ** is stored in the leaves.  (BTREE_INTKEY is used for SQL tables.)  With
9346 ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
9347 ** anywhere - the key is the content.  (BTREE_BLOBKEY is used for SQL
9348 ** indices.)
9349 */
9350 #define BTREE_INTKEY     1    /* Table has only 64-bit signed integer keys */
9351 #define BTREE_BLOBKEY    2    /* Table has keys only - no data */
9352
9353 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
9354 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
9355 SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
9356 SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
9357
9358 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
9359 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
9360
9361 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
9362
9363 /*
9364 ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
9365 ** should be one of the following values. The integer values are assigned 
9366 ** to constants so that the offset of the corresponding field in an
9367 ** SQLite database header may be found using the following formula:
9368 **
9369 **   offset = 36 + (idx * 4)
9370 **
9371 ** For example, the free-page-count field is located at byte offset 36 of
9372 ** the database file header. The incr-vacuum-flag field is located at
9373 ** byte offset 64 (== 36+4*7).
9374 **
9375 ** The BTREE_DATA_VERSION value is not really a value stored in the header.
9376 ** It is a read-only number computed by the pager.  But we merge it with
9377 ** the header value access routines since its access pattern is the same.
9378 ** Call it a "virtual meta value".
9379 */
9380 #define BTREE_FREE_PAGE_COUNT     0
9381 #define BTREE_SCHEMA_VERSION      1
9382 #define BTREE_FILE_FORMAT         2
9383 #define BTREE_DEFAULT_CACHE_SIZE  3
9384 #define BTREE_LARGEST_ROOT_PAGE   4
9385 #define BTREE_TEXT_ENCODING       5
9386 #define BTREE_USER_VERSION        6
9387 #define BTREE_INCR_VACUUM         7
9388 #define BTREE_APPLICATION_ID      8
9389 #define BTREE_DATA_VERSION        15  /* A virtual meta-value */
9390
9391 /*
9392 ** Values that may be OR'd together to form the second argument of an
9393 ** sqlite3BtreeCursorHints() call.
9394 **
9395 ** The BTREE_BULKLOAD flag is set on index cursors when the index is going
9396 ** to be filled with content that is already in sorted order.
9397 **
9398 ** The BTREE_SEEK_EQ flag is set on cursors that will get OP_SeekGE or
9399 ** OP_SeekLE opcodes for a range search, but where the range of entries
9400 ** selected will all have the same key.  In other words, the cursor will
9401 ** be used only for equality key searches.
9402 **
9403 */
9404 #define BTREE_BULKLOAD 0x00000001  /* Used to full index in sorted order */
9405 #define BTREE_SEEK_EQ  0x00000002  /* EQ seeks only - no range seeks */
9406
9407 SQLITE_PRIVATE int sqlite3BtreeCursor(
9408   Btree*,                              /* BTree containing table to open */
9409   int iTable,                          /* Index of root page */
9410   int wrFlag,                          /* 1 for writing.  0 for read-only */
9411   struct KeyInfo*,                     /* First argument to compare function */
9412   BtCursor *pCursor                    /* Space to write cursor structure */
9413 );
9414 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
9415 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
9416
9417 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
9418 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
9419   BtCursor*,
9420   UnpackedRecord *pUnKey,
9421   i64 intKey,
9422   int bias,
9423   int *pRes
9424 );
9425 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
9426 SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
9427 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
9428 SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
9429                                   const void *pData, int nData,
9430                                   int nZero, int bias, int seekResult);
9431 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
9432 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
9433 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
9434 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
9435 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
9436 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
9437 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
9438 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, u32 *pAmt);
9439 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, u32 *pAmt);
9440 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
9441 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
9442
9443 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
9444 SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
9445
9446 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
9447 SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
9448 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
9449 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
9450 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
9451 #ifdef SQLITE_DEBUG
9452 SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor*, unsigned int mask);
9453 #endif
9454 SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
9455 SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void);
9456
9457 #ifndef NDEBUG
9458 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
9459 #endif
9460
9461 #ifndef SQLITE_OMIT_BTREECOUNT
9462 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
9463 #endif
9464
9465 #ifdef SQLITE_TEST
9466 SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
9467 SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
9468 #endif
9469
9470 #ifndef SQLITE_OMIT_WAL
9471 SQLITE_PRIVATE   int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
9472 #endif
9473
9474 /*
9475 ** If we are not using shared cache, then there is no need to
9476 ** use mutexes to access the BtShared structures.  So make the
9477 ** Enter and Leave procedures no-ops.
9478 */
9479 #ifndef SQLITE_OMIT_SHARED_CACHE
9480 SQLITE_PRIVATE   void sqlite3BtreeEnter(Btree*);
9481 SQLITE_PRIVATE   void sqlite3BtreeEnterAll(sqlite3*);
9482 #else
9483 # define sqlite3BtreeEnter(X) 
9484 # define sqlite3BtreeEnterAll(X)
9485 #endif
9486
9487 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
9488 SQLITE_PRIVATE   int sqlite3BtreeSharable(Btree*);
9489 SQLITE_PRIVATE   void sqlite3BtreeLeave(Btree*);
9490 SQLITE_PRIVATE   void sqlite3BtreeEnterCursor(BtCursor*);
9491 SQLITE_PRIVATE   void sqlite3BtreeLeaveCursor(BtCursor*);
9492 SQLITE_PRIVATE   void sqlite3BtreeLeaveAll(sqlite3*);
9493 #ifndef NDEBUG
9494   /* These routines are used inside assert() statements only. */
9495 SQLITE_PRIVATE   int sqlite3BtreeHoldsMutex(Btree*);
9496 SQLITE_PRIVATE   int sqlite3BtreeHoldsAllMutexes(sqlite3*);
9497 SQLITE_PRIVATE   int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
9498 #endif
9499 #else
9500
9501 # define sqlite3BtreeSharable(X) 0
9502 # define sqlite3BtreeLeave(X)
9503 # define sqlite3BtreeEnterCursor(X)
9504 # define sqlite3BtreeLeaveCursor(X)
9505 # define sqlite3BtreeLeaveAll(X)
9506
9507 # define sqlite3BtreeHoldsMutex(X) 1
9508 # define sqlite3BtreeHoldsAllMutexes(X) 1
9509 # define sqlite3SchemaMutexHeld(X,Y,Z) 1
9510 #endif
9511
9512
9513 #endif /* _BTREE_H_ */
9514
9515 /************** End of btree.h ***********************************************/
9516 /************** Continuing where we left off in sqliteInt.h ******************/
9517 /************** Include vdbe.h in the middle of sqliteInt.h ******************/
9518 /************** Begin file vdbe.h ********************************************/
9519 /*
9520 ** 2001 September 15
9521 **
9522 ** The author disclaims copyright to this source code.  In place of
9523 ** a legal notice, here is a blessing:
9524 **
9525 **    May you do good and not evil.
9526 **    May you find forgiveness for yourself and forgive others.
9527 **    May you share freely, never taking more than you give.
9528 **
9529 *************************************************************************
9530 ** Header file for the Virtual DataBase Engine (VDBE)
9531 **
9532 ** This header defines the interface to the virtual database engine
9533 ** or VDBE.  The VDBE implements an abstract machine that runs a
9534 ** simple program to access and modify the underlying database.
9535 */
9536 #ifndef _SQLITE_VDBE_H_
9537 #define _SQLITE_VDBE_H_
9538 /* #include <stdio.h> */
9539
9540 /*
9541 ** A single VDBE is an opaque structure named "Vdbe".  Only routines
9542 ** in the source file sqliteVdbe.c are allowed to see the insides
9543 ** of this structure.
9544 */
9545 typedef struct Vdbe Vdbe;
9546
9547 /*
9548 ** The names of the following types declared in vdbeInt.h are required
9549 ** for the VdbeOp definition.
9550 */
9551 typedef struct Mem Mem;
9552 typedef struct SubProgram SubProgram;
9553
9554 /*
9555 ** A single instruction of the virtual machine has an opcode
9556 ** and as many as three operands.  The instruction is recorded
9557 ** as an instance of the following structure:
9558 */
9559 struct VdbeOp {
9560   u8 opcode;          /* What operation to perform */
9561   signed char p4type; /* One of the P4_xxx constants for p4 */
9562   u8 opflags;         /* Mask of the OPFLG_* flags in opcodes.h */
9563   u8 p5;              /* Fifth parameter is an unsigned character */
9564   int p1;             /* First operand */
9565   int p2;             /* Second parameter (often the jump destination) */
9566   int p3;             /* The third parameter */
9567   union {             /* fourth parameter */
9568     int i;                 /* Integer value if p4type==P4_INT32 */
9569     void *p;               /* Generic pointer */
9570     char *z;               /* Pointer to data for string (char array) types */
9571     i64 *pI64;             /* Used when p4type is P4_INT64 */
9572     double *pReal;         /* Used when p4type is P4_REAL */
9573     FuncDef *pFunc;        /* Used when p4type is P4_FUNCDEF */
9574     CollSeq *pColl;        /* Used when p4type is P4_COLLSEQ */
9575     Mem *pMem;             /* Used when p4type is P4_MEM */
9576     VTable *pVtab;         /* Used when p4type is P4_VTAB */
9577     KeyInfo *pKeyInfo;     /* Used when p4type is P4_KEYINFO */
9578     int *ai;               /* Used when p4type is P4_INTARRAY */
9579     SubProgram *pProgram;  /* Used when p4type is P4_SUBPROGRAM */
9580     int (*xAdvance)(BtCursor *, int *);
9581   } p4;
9582 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
9583   char *zComment;          /* Comment to improve readability */
9584 #endif
9585 #ifdef VDBE_PROFILE
9586   u32 cnt;                 /* Number of times this instruction was executed */
9587   u64 cycles;              /* Total time spent executing this instruction */
9588 #endif
9589 #ifdef SQLITE_VDBE_COVERAGE
9590   int iSrcLine;            /* Source-code line that generated this opcode */
9591 #endif
9592 };
9593 typedef struct VdbeOp VdbeOp;
9594
9595
9596 /*
9597 ** A sub-routine used to implement a trigger program.
9598 */
9599 struct SubProgram {
9600   VdbeOp *aOp;                  /* Array of opcodes for sub-program */
9601   int nOp;                      /* Elements in aOp[] */
9602   int nMem;                     /* Number of memory cells required */
9603   int nCsr;                     /* Number of cursors required */
9604   int nOnce;                    /* Number of OP_Once instructions */
9605   void *token;                  /* id that may be used to recursive triggers */
9606   SubProgram *pNext;            /* Next sub-program already visited */
9607 };
9608
9609 /*
9610 ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
9611 ** it takes up less space.
9612 */
9613 struct VdbeOpList {
9614   u8 opcode;          /* What operation to perform */
9615   signed char p1;     /* First operand */
9616   signed char p2;     /* Second parameter (often the jump destination) */
9617   signed char p3;     /* Third parameter */
9618 };
9619 typedef struct VdbeOpList VdbeOpList;
9620
9621 /*
9622 ** Allowed values of VdbeOp.p4type
9623 */
9624 #define P4_NOTUSED    0   /* The P4 parameter is not used */
9625 #define P4_DYNAMIC  (-1)  /* Pointer to a string obtained from sqliteMalloc() */
9626 #define P4_STATIC   (-2)  /* Pointer to a static string */
9627 #define P4_COLLSEQ  (-4)  /* P4 is a pointer to a CollSeq structure */
9628 #define P4_FUNCDEF  (-5)  /* P4 is a pointer to a FuncDef structure */
9629 #define P4_KEYINFO  (-6)  /* P4 is a pointer to a KeyInfo structure */
9630 #define P4_MEM      (-8)  /* P4 is a pointer to a Mem*    structure */
9631 #define P4_TRANSIENT  0   /* P4 is a pointer to a transient string */
9632 #define P4_VTAB     (-10) /* P4 is a pointer to an sqlite3_vtab structure */
9633 #define P4_MPRINTF  (-11) /* P4 is a string obtained from sqlite3_mprintf() */
9634 #define P4_REAL     (-12) /* P4 is a 64-bit floating point value */
9635 #define P4_INT64    (-13) /* P4 is a 64-bit signed integer */
9636 #define P4_INT32    (-14) /* P4 is a 32-bit signed integer */
9637 #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
9638 #define P4_SUBPROGRAM  (-18) /* P4 is a pointer to a SubProgram structure */
9639 #define P4_ADVANCE  (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
9640
9641 /* Error message codes for OP_Halt */
9642 #define P5_ConstraintNotNull 1
9643 #define P5_ConstraintUnique  2
9644 #define P5_ConstraintCheck   3
9645 #define P5_ConstraintFK      4
9646
9647 /*
9648 ** The Vdbe.aColName array contains 5n Mem structures, where n is the 
9649 ** number of columns of data returned by the statement.
9650 */
9651 #define COLNAME_NAME     0
9652 #define COLNAME_DECLTYPE 1
9653 #define COLNAME_DATABASE 2
9654 #define COLNAME_TABLE    3
9655 #define COLNAME_COLUMN   4
9656 #ifdef SQLITE_ENABLE_COLUMN_METADATA
9657 # define COLNAME_N        5      /* Number of COLNAME_xxx symbols */
9658 #else
9659 # ifdef SQLITE_OMIT_DECLTYPE
9660 #   define COLNAME_N      1      /* Store only the name */
9661 # else
9662 #   define COLNAME_N      2      /* Store the name and decltype */
9663 # endif
9664 #endif
9665
9666 /*
9667 ** The following macro converts a relative address in the p2 field
9668 ** of a VdbeOp structure into a negative number so that 
9669 ** sqlite3VdbeAddOpList() knows that the address is relative.  Calling
9670 ** the macro again restores the address.
9671 */
9672 #define ADDR(X)  (-1-(X))
9673
9674 /*
9675 ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
9676 ** header file that defines a number for each opcode used by the VDBE.
9677 */
9678 /************** Include opcodes.h in the middle of vdbe.h ********************/
9679 /************** Begin file opcodes.h *****************************************/
9680 /* Automatically generated.  Do not edit */
9681 /* See the mkopcodeh.awk script for details */
9682 #define OP_Function        1 /* synopsis: r[P3]=func(r[P2@P5])             */
9683 #define OP_Savepoint       2
9684 #define OP_AutoCommit      3
9685 #define OP_Transaction     4
9686 #define OP_SorterNext      5
9687 #define OP_PrevIfOpen      6
9688 #define OP_NextIfOpen      7
9689 #define OP_Prev            8
9690 #define OP_Next            9
9691 #define OP_AggStep        10 /* synopsis: accum=r[P3] step(r[P2@P5])       */
9692 #define OP_Checkpoint     11
9693 #define OP_JournalMode    12
9694 #define OP_Vacuum         13
9695 #define OP_VFilter        14 /* synopsis: iplan=r[P3] zplan='P4'           */
9696 #define OP_VUpdate        15 /* synopsis: data=r[P3@P2]                    */
9697 #define OP_Goto           16
9698 #define OP_Gosub          17
9699 #define OP_Return         18
9700 #define OP_Not            19 /* same as TK_NOT, synopsis: r[P2]= !r[P1]    */
9701 #define OP_InitCoroutine  20
9702 #define OP_EndCoroutine   21
9703 #define OP_Yield          22
9704 #define OP_HaltIfNull     23 /* synopsis: if r[P3]=null halt               */
9705 #define OP_Halt           24
9706 #define OP_Integer        25 /* synopsis: r[P2]=P1                         */
9707 #define OP_Int64          26 /* synopsis: r[P2]=P4                         */
9708 #define OP_String         27 /* synopsis: r[P2]='P4' (len=P1)              */
9709 #define OP_Null           28 /* synopsis: r[P2..P3]=NULL                   */
9710 #define OP_SoftNull       29 /* synopsis: r[P1]=NULL                       */
9711 #define OP_Blob           30 /* synopsis: r[P2]=P4 (len=P1)                */
9712 #define OP_Variable       31 /* synopsis: r[P2]=parameter(P1,P4)           */
9713 #define OP_Move           32 /* synopsis: r[P2@P3]=r[P1@P3]                */
9714 #define OP_Copy           33 /* synopsis: r[P2@P3+1]=r[P1@P3+1]            */
9715 #define OP_SCopy          34 /* synopsis: r[P2]=r[P1]                      */
9716 #define OP_ResultRow      35 /* synopsis: output=r[P1@P2]                  */
9717 #define OP_CollSeq        36
9718 #define OP_AddImm         37 /* synopsis: r[P1]=r[P1]+P2                   */
9719 #define OP_MustBeInt      38
9720 #define OP_RealAffinity   39
9721 #define OP_Cast           40 /* synopsis: affinity(r[P1])                  */
9722 #define OP_Permutation    41
9723 #define OP_Compare        42 /* synopsis: r[P1@P3] <-> r[P2@P3]            */
9724 #define OP_Jump           43
9725 #define OP_Once           44
9726 #define OP_If             45
9727 #define OP_IfNot          46
9728 #define OP_Column         47 /* synopsis: r[P3]=PX                         */
9729 #define OP_Affinity       48 /* synopsis: affinity(r[P1@P2])               */
9730 #define OP_MakeRecord     49 /* synopsis: r[P3]=mkrec(r[P1@P2])            */
9731 #define OP_Count          50 /* synopsis: r[P2]=count()                    */
9732 #define OP_ReadCookie     51
9733 #define OP_SetCookie      52
9734 #define OP_ReopenIdx      53 /* synopsis: root=P2 iDb=P3                   */
9735 #define OP_OpenRead       54 /* synopsis: root=P2 iDb=P3                   */
9736 #define OP_OpenWrite      55 /* synopsis: root=P2 iDb=P3                   */
9737 #define OP_OpenAutoindex  56 /* synopsis: nColumn=P2                       */
9738 #define OP_OpenEphemeral  57 /* synopsis: nColumn=P2                       */
9739 #define OP_SorterOpen     58
9740 #define OP_SequenceTest   59 /* synopsis: if( cursor[P1].ctr++ ) pc = P2   */
9741 #define OP_OpenPseudo     60 /* synopsis: P3 columns in r[P2]              */
9742 #define OP_Close          61
9743 #define OP_SeekLT         62 /* synopsis: key=r[P3@P4]                     */
9744 #define OP_SeekLE         63 /* synopsis: key=r[P3@P4]                     */
9745 #define OP_SeekGE         64 /* synopsis: key=r[P3@P4]                     */
9746 #define OP_SeekGT         65 /* synopsis: key=r[P3@P4]                     */
9747 #define OP_Seek           66 /* synopsis: intkey=r[P2]                     */
9748 #define OP_NoConflict     67 /* synopsis: key=r[P3@P4]                     */
9749 #define OP_NotFound       68 /* synopsis: key=r[P3@P4]                     */
9750 #define OP_Found          69 /* synopsis: key=r[P3@P4]                     */
9751 #define OP_NotExists      70 /* synopsis: intkey=r[P3]                     */
9752 #define OP_Or             71 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
9753 #define OP_And            72 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
9754 #define OP_Sequence       73 /* synopsis: r[P2]=cursor[P1].ctr++           */
9755 #define OP_NewRowid       74 /* synopsis: r[P2]=rowid                      */
9756 #define OP_Insert         75 /* synopsis: intkey=r[P3] data=r[P2]          */
9757 #define OP_IsNull         76 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
9758 #define OP_NotNull        77 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
9759 #define OP_Ne             78 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
9760 #define OP_Eq             79 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
9761 #define OP_Gt             80 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
9762 #define OP_Le             81 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
9763 #define OP_Lt             82 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
9764 #define OP_Ge             83 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
9765 #define OP_InsertInt      84 /* synopsis: intkey=P3 data=r[P2]             */
9766 #define OP_BitAnd         85 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
9767 #define OP_BitOr          86 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
9768 #define OP_ShiftLeft      87 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
9769 #define OP_ShiftRight     88 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
9770 #define OP_Add            89 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
9771 #define OP_Subtract       90 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
9772 #define OP_Multiply       91 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
9773 #define OP_Divide         92 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
9774 #define OP_Remainder      93 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
9775 #define OP_Concat         94 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
9776 #define OP_Delete         95
9777 #define OP_BitNot         96 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
9778 #define OP_String8        97 /* same as TK_STRING, synopsis: r[P2]='P4'    */
9779 #define OP_ResetCount     98
9780 #define OP_SorterCompare  99 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
9781 #define OP_SorterData    100 /* synopsis: r[P2]=data                       */
9782 #define OP_RowKey        101 /* synopsis: r[P2]=key                        */
9783 #define OP_RowData       102 /* synopsis: r[P2]=data                       */
9784 #define OP_Rowid         103 /* synopsis: r[P2]=rowid                      */
9785 #define OP_NullRow       104
9786 #define OP_Last          105
9787 #define OP_SorterSort    106
9788 #define OP_Sort          107
9789 #define OP_Rewind        108
9790 #define OP_SorterInsert  109
9791 #define OP_IdxInsert     110 /* synopsis: key=r[P2]                        */
9792 #define OP_IdxDelete     111 /* synopsis: key=r[P2@P3]                     */
9793 #define OP_IdxRowid      112 /* synopsis: r[P2]=rowid                      */
9794 #define OP_IdxLE         113 /* synopsis: key=r[P3@P4]                     */
9795 #define OP_IdxGT         114 /* synopsis: key=r[P3@P4]                     */
9796 #define OP_IdxLT         115 /* synopsis: key=r[P3@P4]                     */
9797 #define OP_IdxGE         116 /* synopsis: key=r[P3@P4]                     */
9798 #define OP_Destroy       117
9799 #define OP_Clear         118
9800 #define OP_ResetSorter   119
9801 #define OP_CreateIndex   120 /* synopsis: r[P2]=root iDb=P1                */
9802 #define OP_CreateTable   121 /* synopsis: r[P2]=root iDb=P1                */
9803 #define OP_ParseSchema   122
9804 #define OP_LoadAnalysis  123
9805 #define OP_DropTable     124
9806 #define OP_DropIndex     125
9807 #define OP_DropTrigger   126
9808 #define OP_IntegrityCk   127
9809 #define OP_RowSetAdd     128 /* synopsis: rowset(P1)=r[P2]                 */
9810 #define OP_RowSetRead    129 /* synopsis: r[P3]=rowset(P1)                 */
9811 #define OP_RowSetTest    130 /* synopsis: if r[P3] in rowset(P1) goto P2   */
9812 #define OP_Program       131
9813 #define OP_Param         132
9814 #define OP_Real          133 /* same as TK_FLOAT, synopsis: r[P2]=P4       */
9815 #define OP_FkCounter     134 /* synopsis: fkctr[P1]+=P2                    */
9816 #define OP_FkIfZero      135 /* synopsis: if fkctr[P1]==0 goto P2          */
9817 #define OP_MemMax        136 /* synopsis: r[P1]=max(r[P1],r[P2])           */
9818 #define OP_IfPos         137 /* synopsis: if r[P1]>0 goto P2               */
9819 #define OP_IfNeg         138 /* synopsis: r[P1]+=P3, if r[P1]<0 goto P2    */
9820 #define OP_IfNotZero     139 /* synopsis: if r[P1]!=0 then r[P1]+=P3, goto P2 */
9821 #define OP_DecrJumpZero  140 /* synopsis: if (--r[P1])==0 goto P2          */
9822 #define OP_JumpZeroIncr  141 /* synopsis: if (r[P1]++)==0 ) goto P2        */
9823 #define OP_AggFinal      142 /* synopsis: accum=r[P1] N=P2                 */
9824 #define OP_IncrVacuum    143
9825 #define OP_Expire        144
9826 #define OP_TableLock     145 /* synopsis: iDb=P1 root=P2 write=P3          */
9827 #define OP_VBegin        146
9828 #define OP_VCreate       147
9829 #define OP_VDestroy      148
9830 #define OP_VOpen         149
9831 #define OP_VColumn       150 /* synopsis: r[P3]=vcolumn(P2)                */
9832 #define OP_VNext         151
9833 #define OP_VRename       152
9834 #define OP_Pagecount     153
9835 #define OP_MaxPgcnt      154
9836 #define OP_Init          155 /* synopsis: Start at P2                      */
9837 #define OP_Noop          156
9838 #define OP_Explain       157
9839
9840
9841 /* Properties such as "out2" or "jump" that are specified in
9842 ** comments following the "case" for each opcode in the vdbe.c
9843 ** are encoded into bitvectors as follows:
9844 */
9845 #define OPFLG_JUMP            0x0001  /* jump:  P2 holds jmp target */
9846 #define OPFLG_OUT2_PRERELEASE 0x0002  /* out2-prerelease: */
9847 #define OPFLG_IN1             0x0004  /* in1:   P1 is an input */
9848 #define OPFLG_IN2             0x0008  /* in2:   P2 is an input */
9849 #define OPFLG_IN3             0x0010  /* in3:   P3 is an input */
9850 #define OPFLG_OUT2            0x0020  /* out2:  P2 is an output */
9851 #define OPFLG_OUT3            0x0040  /* out3:  P3 is an output */
9852 #define OPFLG_INITIALIZER {\
9853 /*   0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01,\
9854 /*   8 */ 0x01, 0x01, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00,\
9855 /*  16 */ 0x01, 0x01, 0x04, 0x24, 0x01, 0x04, 0x05, 0x10,\
9856 /*  24 */ 0x00, 0x02, 0x02, 0x02, 0x02, 0x00, 0x02, 0x02,\
9857 /*  32 */ 0x00, 0x00, 0x20, 0x00, 0x00, 0x04, 0x05, 0x04,\
9858 /*  40 */ 0x04, 0x00, 0x00, 0x01, 0x01, 0x05, 0x05, 0x00,\
9859 /*  48 */ 0x00, 0x00, 0x02, 0x02, 0x10, 0x00, 0x00, 0x00,\
9860 /*  56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\
9861 /*  64 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x4c,\
9862 /*  72 */ 0x4c, 0x02, 0x02, 0x00, 0x05, 0x05, 0x15, 0x15,\
9863 /*  80 */ 0x15, 0x15, 0x15, 0x15, 0x00, 0x4c, 0x4c, 0x4c,\
9864 /*  88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x00,\
9865 /*  96 */ 0x24, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,\
9866 /* 104 */ 0x00, 0x01, 0x01, 0x01, 0x01, 0x08, 0x08, 0x00,\
9867 /* 112 */ 0x02, 0x01, 0x01, 0x01, 0x01, 0x02, 0x00, 0x00,\
9868 /* 120 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
9869 /* 128 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x02, 0x00, 0x01,\
9870 /* 136 */ 0x08, 0x05, 0x05, 0x05, 0x05, 0x05, 0x00, 0x01,\
9871 /* 144 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01,\
9872 /* 152 */ 0x00, 0x02, 0x02, 0x01, 0x00, 0x00,}
9873
9874 /************** End of opcodes.h *********************************************/
9875 /************** Continuing where we left off in vdbe.h ***********************/
9876
9877 /*
9878 ** Prototypes for the VDBE interface.  See comments on the implementation
9879 ** for a description of what each of these routines does.
9880 */
9881 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
9882 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
9883 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
9884 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
9885 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
9886 SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
9887 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
9888 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
9889 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
9890 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
9891 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
9892 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
9893 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
9894 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
9895 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
9896 SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
9897 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
9898 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
9899 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
9900 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
9901 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
9902 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
9903 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
9904 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
9905 SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
9906 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
9907 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
9908 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
9909 #ifdef SQLITE_DEBUG
9910 SQLITE_PRIVATE   int sqlite3VdbeAssertMayAbort(Vdbe *, int);
9911 #endif
9912 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
9913 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
9914 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
9915 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
9916 SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
9917 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
9918 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
9919 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
9920 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
9921 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
9922 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
9923 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
9924 #ifndef SQLITE_OMIT_TRACE
9925 SQLITE_PRIVATE   char *sqlite3VdbeExpandSql(Vdbe*, const char*);
9926 #endif
9927 SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
9928
9929 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
9930 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
9931 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
9932
9933 typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
9934 SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
9935
9936 #ifndef SQLITE_OMIT_TRIGGER
9937 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
9938 #endif
9939
9940 /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
9941 ** each VDBE opcode.
9942 **
9943 ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
9944 ** comments in VDBE programs that show key decision points in the code
9945 ** generator.
9946 */
9947 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
9948 SQLITE_PRIVATE   void sqlite3VdbeComment(Vdbe*, const char*, ...);
9949 # define VdbeComment(X)  sqlite3VdbeComment X
9950 SQLITE_PRIVATE   void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
9951 # define VdbeNoopComment(X)  sqlite3VdbeNoopComment X
9952 # ifdef SQLITE_ENABLE_MODULE_COMMENTS
9953 #   define VdbeModuleComment(X)  sqlite3VdbeNoopComment X
9954 # else
9955 #   define VdbeModuleComment(X)
9956 # endif
9957 #else
9958 # define VdbeComment(X)
9959 # define VdbeNoopComment(X)
9960 # define VdbeModuleComment(X)
9961 #endif
9962
9963 /*
9964 ** The VdbeCoverage macros are used to set a coverage testing point
9965 ** for VDBE branch instructions.  The coverage testing points are line
9966 ** numbers in the sqlite3.c source file.  VDBE branch coverage testing
9967 ** only works with an amalagmation build.  That's ok since a VDBE branch
9968 ** coverage build designed for testing the test suite only.  No application
9969 ** should ever ship with VDBE branch coverage measuring turned on.
9970 **
9971 **    VdbeCoverage(v)                  // Mark the previously coded instruction
9972 **                                     // as a branch
9973 **
9974 **    VdbeCoverageIf(v, conditional)   // Mark previous if conditional true
9975 **
9976 **    VdbeCoverageAlwaysTaken(v)       // Previous branch is always taken
9977 **
9978 **    VdbeCoverageNeverTaken(v)        // Previous branch is never taken
9979 **
9980 ** Every VDBE branch operation must be tagged with one of the macros above.
9981 ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
9982 ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
9983 ** routine in vdbe.c, alerting the developer to the missed tag.
9984 */
9985 #ifdef SQLITE_VDBE_COVERAGE
9986 SQLITE_PRIVATE   void sqlite3VdbeSetLineNumber(Vdbe*,int);
9987 # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
9988 # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
9989 # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
9990 # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
9991 # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
9992 #else
9993 # define VdbeCoverage(v)
9994 # define VdbeCoverageIf(v,x)
9995 # define VdbeCoverageAlwaysTaken(v)
9996 # define VdbeCoverageNeverTaken(v)
9997 # define VDBE_OFFSET_LINENO(x) 0
9998 #endif
9999
10000 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
10001 SQLITE_PRIVATE void sqlite3VdbeScanStatus(Vdbe*, int, int, int, LogEst, const char*);
10002 #else
10003 # define sqlite3VdbeScanStatus(a,b,c,d,e)
10004 #endif
10005
10006 #endif
10007
10008 /************** End of vdbe.h ************************************************/
10009 /************** Continuing where we left off in sqliteInt.h ******************/
10010 /************** Include pager.h in the middle of sqliteInt.h *****************/
10011 /************** Begin file pager.h *******************************************/
10012 /*
10013 ** 2001 September 15
10014 **
10015 ** The author disclaims copyright to this source code.  In place of
10016 ** a legal notice, here is a blessing:
10017 **
10018 **    May you do good and not evil.
10019 **    May you find forgiveness for yourself and forgive others.
10020 **    May you share freely, never taking more than you give.
10021 **
10022 *************************************************************************
10023 ** This header file defines the interface that the sqlite page cache
10024 ** subsystem.  The page cache subsystem reads and writes a file a page
10025 ** at a time and provides a journal for rollback.
10026 */
10027
10028 #ifndef _PAGER_H_
10029 #define _PAGER_H_
10030
10031 /*
10032 ** Default maximum size for persistent journal files. A negative 
10033 ** value means no limit. This value may be overridden using the 
10034 ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
10035 */
10036 #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
10037   #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
10038 #endif
10039
10040 /*
10041 ** The type used to represent a page number.  The first page in a file
10042 ** is called page 1.  0 is used to represent "not a page".
10043 */
10044 typedef u32 Pgno;
10045
10046 /*
10047 ** Each open file is managed by a separate instance of the "Pager" structure.
10048 */
10049 typedef struct Pager Pager;
10050
10051 /*
10052 ** Handle type for pages.
10053 */
10054 typedef struct PgHdr DbPage;
10055
10056 /*
10057 ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
10058 ** reserved for working around a windows/posix incompatibility). It is
10059 ** used in the journal to signify that the remainder of the journal file 
10060 ** is devoted to storing a master journal name - there are no more pages to
10061 ** roll back. See comments for function writeMasterJournal() in pager.c 
10062 ** for details.
10063 */
10064 #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
10065
10066 /*
10067 ** Allowed values for the flags parameter to sqlite3PagerOpen().
10068 **
10069 ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
10070 */
10071 #define PAGER_OMIT_JOURNAL  0x0001    /* Do not use a rollback journal */
10072 #define PAGER_MEMORY        0x0002    /* In-memory database */
10073
10074 /*
10075 ** Valid values for the second argument to sqlite3PagerLockingMode().
10076 */
10077 #define PAGER_LOCKINGMODE_QUERY      -1
10078 #define PAGER_LOCKINGMODE_NORMAL      0
10079 #define PAGER_LOCKINGMODE_EXCLUSIVE   1
10080
10081 /*
10082 ** Numeric constants that encode the journalmode.  
10083 */
10084 #define PAGER_JOURNALMODE_QUERY     (-1)  /* Query the value of journalmode */
10085 #define PAGER_JOURNALMODE_DELETE      0   /* Commit by deleting journal file */
10086 #define PAGER_JOURNALMODE_PERSIST     1   /* Commit by zeroing journal header */
10087 #define PAGER_JOURNALMODE_OFF         2   /* Journal omitted.  */
10088 #define PAGER_JOURNALMODE_TRUNCATE    3   /* Commit by truncating journal */
10089 #define PAGER_JOURNALMODE_MEMORY      4   /* In-memory journal file */
10090 #define PAGER_JOURNALMODE_WAL         5   /* Use write-ahead logging */
10091
10092 /*
10093 ** Flags that make up the mask passed to sqlite3PagerAcquire().
10094 */
10095 #define PAGER_GET_NOCONTENT     0x01  /* Do not load data from disk */
10096 #define PAGER_GET_READONLY      0x02  /* Read-only page is acceptable */
10097
10098 /*
10099 ** Flags for sqlite3PagerSetFlags()
10100 */
10101 #define PAGER_SYNCHRONOUS_OFF       0x01  /* PRAGMA synchronous=OFF */
10102 #define PAGER_SYNCHRONOUS_NORMAL    0x02  /* PRAGMA synchronous=NORMAL */
10103 #define PAGER_SYNCHRONOUS_FULL      0x03  /* PRAGMA synchronous=FULL */
10104 #define PAGER_SYNCHRONOUS_MASK      0x03  /* Mask for three values above */
10105 #define PAGER_FULLFSYNC             0x04  /* PRAGMA fullfsync=ON */
10106 #define PAGER_CKPT_FULLFSYNC        0x08  /* PRAGMA checkpoint_fullfsync=ON */
10107 #define PAGER_CACHESPILL            0x10  /* PRAGMA cache_spill=ON */
10108 #define PAGER_FLAGS_MASK            0x1c  /* All above except SYNCHRONOUS */
10109
10110 /*
10111 ** The remainder of this file contains the declarations of the functions
10112 ** that make up the Pager sub-system API. See source code comments for 
10113 ** a detailed description of each routine.
10114 */
10115
10116 /* Open and close a Pager connection. */ 
10117 SQLITE_PRIVATE int sqlite3PagerOpen(
10118   sqlite3_vfs*,
10119   Pager **ppPager,
10120   const char*,
10121   int,
10122   int,
10123   int,
10124   void(*)(DbPage*)
10125 );
10126 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
10127 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
10128
10129 /* Functions used to configure a Pager object. */
10130 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
10131 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
10132 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
10133 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
10134 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
10135 SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
10136 SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
10137 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
10138 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
10139 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
10140 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
10141 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
10142 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
10143
10144 /* Functions used to obtain and release page references. */ 
10145 SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
10146 #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
10147 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
10148 SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
10149 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
10150 SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
10151
10152 /* Operations on page references. */
10153 SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
10154 SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
10155 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
10156 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
10157 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *); 
10158 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *); 
10159
10160 /* Functions used to manage pager transactions and savepoints. */
10161 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
10162 SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
10163 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
10164 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
10165 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
10166 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
10167 SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
10168 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
10169 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
10170 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
10171
10172 #ifndef SQLITE_OMIT_WAL
10173 SQLITE_PRIVATE   int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
10174 SQLITE_PRIVATE   int sqlite3PagerWalSupported(Pager *pPager);
10175 SQLITE_PRIVATE   int sqlite3PagerWalCallback(Pager *pPager);
10176 SQLITE_PRIVATE   int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
10177 SQLITE_PRIVATE   int sqlite3PagerCloseWal(Pager *pPager);
10178 #endif
10179
10180 #ifdef SQLITE_ENABLE_ZIPVFS
10181 SQLITE_PRIVATE   int sqlite3PagerWalFramesize(Pager *pPager);
10182 #endif
10183
10184 /* Functions used to query pager state and configuration. */
10185 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
10186 SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager*);
10187 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
10188 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
10189 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
10190 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
10191 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
10192 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
10193 SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
10194 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
10195 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
10196 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
10197 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
10198 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
10199
10200 /* Functions used to truncate the database file. */
10201 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
10202
10203 SQLITE_PRIVATE void sqlite3PagerRekey(DbPage*, Pgno, u16);
10204
10205 #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
10206 SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
10207 #endif
10208
10209 /* Functions to support testing and debugging. */
10210 #if !defined(NDEBUG) || defined(SQLITE_TEST)
10211 SQLITE_PRIVATE   Pgno sqlite3PagerPagenumber(DbPage*);
10212 SQLITE_PRIVATE   int sqlite3PagerIswriteable(DbPage*);
10213 #endif
10214 #ifdef SQLITE_TEST
10215 SQLITE_PRIVATE   int *sqlite3PagerStats(Pager*);
10216 SQLITE_PRIVATE   void sqlite3PagerRefdump(Pager*);
10217   void disable_simulated_io_errors(void);
10218   void enable_simulated_io_errors(void);
10219 #else
10220 # define disable_simulated_io_errors()
10221 # define enable_simulated_io_errors()
10222 #endif
10223
10224 #endif /* _PAGER_H_ */
10225
10226 /************** End of pager.h ***********************************************/
10227 /************** Continuing where we left off in sqliteInt.h ******************/
10228 /************** Include pcache.h in the middle of sqliteInt.h ****************/
10229 /************** Begin file pcache.h ******************************************/
10230 /*
10231 ** 2008 August 05
10232 **
10233 ** The author disclaims copyright to this source code.  In place of
10234 ** a legal notice, here is a blessing:
10235 **
10236 **    May you do good and not evil.
10237 **    May you find forgiveness for yourself and forgive others.
10238 **    May you share freely, never taking more than you give.
10239 **
10240 *************************************************************************
10241 ** This header file defines the interface that the sqlite page cache
10242 ** subsystem. 
10243 */
10244
10245 #ifndef _PCACHE_H_
10246
10247 typedef struct PgHdr PgHdr;
10248 typedef struct PCache PCache;
10249
10250 /*
10251 ** Every page in the cache is controlled by an instance of the following
10252 ** structure.
10253 */
10254 struct PgHdr {
10255   sqlite3_pcache_page *pPage;    /* Pcache object page handle */
10256   void *pData;                   /* Page data */
10257   void *pExtra;                  /* Extra content */
10258   PgHdr *pDirty;                 /* Transient list of dirty pages */
10259   Pager *pPager;                 /* The pager this page is part of */
10260   Pgno pgno;                     /* Page number for this page */
10261 #ifdef SQLITE_CHECK_PAGES
10262   u32 pageHash;                  /* Hash of page content */
10263 #endif
10264   u16 flags;                     /* PGHDR flags defined below */
10265
10266   /**********************************************************************
10267   ** Elements above are public.  All that follows is private to pcache.c
10268   ** and should not be accessed by other modules.
10269   */
10270   i16 nRef;                      /* Number of users of this page */
10271   PCache *pCache;                /* Cache that owns this page */
10272
10273   PgHdr *pDirtyNext;             /* Next element in list of dirty pages */
10274   PgHdr *pDirtyPrev;             /* Previous element in list of dirty pages */
10275 };
10276
10277 /* Bit values for PgHdr.flags */
10278 #define PGHDR_DIRTY             0x002  /* Page has changed */
10279 #define PGHDR_NEED_SYNC         0x004  /* Fsync the rollback journal before
10280                                        ** writing this page to the database */
10281 #define PGHDR_NEED_READ         0x008  /* Content is unread */
10282 #define PGHDR_REUSE_UNLIKELY    0x010  /* A hint that reuse is unlikely */
10283 #define PGHDR_DONT_WRITE        0x020  /* Do not write content to disk */
10284
10285 #define PGHDR_MMAP              0x040  /* This is an mmap page object */
10286
10287 /* Initialize and shutdown the page cache subsystem */
10288 SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
10289 SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
10290
10291 /* Page cache buffer management:
10292 ** These routines implement SQLITE_CONFIG_PAGECACHE.
10293 */
10294 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
10295
10296 /* Create a new pager cache.
10297 ** Under memory stress, invoke xStress to try to make pages clean.
10298 ** Only clean and unpinned pages can be reclaimed.
10299 */
10300 SQLITE_PRIVATE int sqlite3PcacheOpen(
10301   int szPage,                    /* Size of every page */
10302   int szExtra,                   /* Extra space associated with each page */
10303   int bPurgeable,                /* True if pages are on backing store */
10304   int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
10305   void *pStress,                 /* Argument to xStress */
10306   PCache *pToInit                /* Preallocated space for the PCache */
10307 );
10308
10309 /* Modify the page-size after the cache has been created. */
10310 SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
10311
10312 /* Return the size in bytes of a PCache object.  Used to preallocate
10313 ** storage space.
10314 */
10315 SQLITE_PRIVATE int sqlite3PcacheSize(void);
10316
10317 /* One release per successful fetch.  Page is pinned until released.
10318 ** Reference counted. 
10319 */
10320 SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
10321 SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
10322 SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
10323 SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
10324
10325 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*);         /* Remove page from cache */
10326 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*);    /* Make sure page is marked dirty */
10327 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*);    /* Mark a single page as clean */
10328 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*);    /* Mark all dirty list pages as clean */
10329
10330 /* Change a page number.  Used by incr-vacuum. */
10331 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
10332
10333 /* Remove all pages with pgno>x.  Reset the cache if x==0 */
10334 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
10335
10336 /* Get a list of all dirty pages in the cache, sorted by page number */
10337 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
10338
10339 /* Reset and close the cache object */
10340 SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
10341
10342 /* Clear flags from pages of the page cache */
10343 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
10344
10345 /* Discard the contents of the cache */
10346 SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
10347
10348 /* Return the total number of outstanding page references */
10349 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
10350
10351 /* Increment the reference count of an existing page */
10352 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
10353
10354 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
10355
10356 /* Return the total number of pages stored in the cache */
10357 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
10358
10359 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
10360 /* Iterate through all dirty pages currently stored in the cache. This
10361 ** interface is only available if SQLITE_CHECK_PAGES is defined when the 
10362 ** library is built.
10363 */
10364 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
10365 #endif
10366
10367 /* Set and get the suggested cache-size for the specified pager-cache.
10368 **
10369 ** If no global maximum is configured, then the system attempts to limit
10370 ** the total number of pages cached by purgeable pager-caches to the sum
10371 ** of the suggested cache-sizes.
10372 */
10373 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
10374 #ifdef SQLITE_TEST
10375 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
10376 #endif
10377
10378 /* Free up as much memory as possible from the page cache */
10379 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
10380
10381 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
10382 /* Try to return memory used by the pcache module to the main memory heap */
10383 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
10384 #endif
10385
10386 #ifdef SQLITE_TEST
10387 SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
10388 #endif
10389
10390 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
10391
10392 /* Return the header size */
10393 SQLITE_PRIVATE int sqlite3HeaderSizePcache(void);
10394 SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void);
10395
10396 #endif /* _PCACHE_H_ */
10397
10398 /************** End of pcache.h **********************************************/
10399 /************** Continuing where we left off in sqliteInt.h ******************/
10400
10401 /************** Include os.h in the middle of sqliteInt.h ********************/
10402 /************** Begin file os.h **********************************************/
10403 /*
10404 ** 2001 September 16
10405 **
10406 ** The author disclaims copyright to this source code.  In place of
10407 ** a legal notice, here is a blessing:
10408 **
10409 **    May you do good and not evil.
10410 **    May you find forgiveness for yourself and forgive others.
10411 **    May you share freely, never taking more than you give.
10412 **
10413 ******************************************************************************
10414 **
10415 ** This header file (together with is companion C source-code file
10416 ** "os.c") attempt to abstract the underlying operating system so that
10417 ** the SQLite library will work on both POSIX and windows systems.
10418 **
10419 ** This header file is #include-ed by sqliteInt.h and thus ends up
10420 ** being included by every source file.
10421 */
10422 #ifndef _SQLITE_OS_H_
10423 #define _SQLITE_OS_H_
10424
10425 /*
10426 ** Attempt to automatically detect the operating system and setup the
10427 ** necessary pre-processor macros for it.
10428 */
10429 /************** Include os_setup.h in the middle of os.h *********************/
10430 /************** Begin file os_setup.h ****************************************/
10431 /*
10432 ** 2013 November 25
10433 **
10434 ** The author disclaims copyright to this source code.  In place of
10435 ** a legal notice, here is a blessing:
10436 **
10437 **    May you do good and not evil.
10438 **    May you find forgiveness for yourself and forgive others.
10439 **    May you share freely, never taking more than you give.
10440 **
10441 ******************************************************************************
10442 **
10443 ** This file contains pre-processor directives related to operating system
10444 ** detection and/or setup.
10445 */
10446 #ifndef _OS_SETUP_H_
10447 #define _OS_SETUP_H_
10448
10449 /*
10450 ** Figure out if we are dealing with Unix, Windows, or some other operating
10451 ** system.
10452 **
10453 ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
10454 ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0.  One of
10455 ** the three will be 1.  The other two will be 0.
10456 */
10457 #if defined(SQLITE_OS_OTHER)
10458 #  if SQLITE_OS_OTHER==1
10459 #    undef SQLITE_OS_UNIX
10460 #    define SQLITE_OS_UNIX 0
10461 #    undef SQLITE_OS_WIN
10462 #    define SQLITE_OS_WIN 0
10463 #  else
10464 #    undef SQLITE_OS_OTHER
10465 #  endif
10466 #endif
10467 #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
10468 #  define SQLITE_OS_OTHER 0
10469 #  ifndef SQLITE_OS_WIN
10470 #    if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
10471         defined(__MINGW32__) || defined(__BORLANDC__)
10472 #      define SQLITE_OS_WIN 1
10473 #      define SQLITE_OS_UNIX 0
10474 #    else
10475 #      define SQLITE_OS_WIN 0
10476 #      define SQLITE_OS_UNIX 1
10477 #    endif
10478 #  else
10479 #    define SQLITE_OS_UNIX 0
10480 #  endif
10481 #else
10482 #  ifndef SQLITE_OS_WIN
10483 #    define SQLITE_OS_WIN 0
10484 #  endif
10485 #endif
10486
10487 #endif /* _OS_SETUP_H_ */
10488
10489 /************** End of os_setup.h ********************************************/
10490 /************** Continuing where we left off in os.h *************************/
10491
10492 /* If the SET_FULLSYNC macro is not defined above, then make it
10493 ** a no-op
10494 */
10495 #ifndef SET_FULLSYNC
10496 # define SET_FULLSYNC(x,y)
10497 #endif
10498
10499 /*
10500 ** The default size of a disk sector
10501 */
10502 #ifndef SQLITE_DEFAULT_SECTOR_SIZE
10503 # define SQLITE_DEFAULT_SECTOR_SIZE 4096
10504 #endif
10505
10506 /*
10507 ** Temporary files are named starting with this prefix followed by 16 random
10508 ** alphanumeric characters, and no file extension. They are stored in the
10509 ** OS's standard temporary file directory, and are deleted prior to exit.
10510 ** If sqlite is being embedded in another program, you may wish to change the
10511 ** prefix to reflect your program's name, so that if your program exits
10512 ** prematurely, old temporary files can be easily identified. This can be done
10513 ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
10514 **
10515 ** 2006-10-31:  The default prefix used to be "sqlite_".  But then
10516 ** Mcafee started using SQLite in their anti-virus product and it
10517 ** started putting files with the "sqlite" name in the c:/temp folder.
10518 ** This annoyed many windows users.  Those users would then do a 
10519 ** Google search for "sqlite", find the telephone numbers of the
10520 ** developers and call to wake them up at night and complain.
10521 ** For this reason, the default name prefix is changed to be "sqlite" 
10522 ** spelled backwards.  So the temp files are still identified, but
10523 ** anybody smart enough to figure out the code is also likely smart
10524 ** enough to know that calling the developer will not help get rid
10525 ** of the file.
10526 */
10527 #ifndef SQLITE_TEMP_FILE_PREFIX
10528 # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
10529 #endif
10530
10531 /*
10532 ** The following values may be passed as the second argument to
10533 ** sqlite3OsLock(). The various locks exhibit the following semantics:
10534 **
10535 ** SHARED:    Any number of processes may hold a SHARED lock simultaneously.
10536 ** RESERVED:  A single process may hold a RESERVED lock on a file at
10537 **            any time. Other processes may hold and obtain new SHARED locks.
10538 ** PENDING:   A single process may hold a PENDING lock on a file at
10539 **            any one time. Existing SHARED locks may persist, but no new
10540 **            SHARED locks may be obtained by other processes.
10541 ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
10542 **
10543 ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
10544 ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
10545 ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
10546 ** sqlite3OsLock().
10547 */
10548 #define NO_LOCK         0
10549 #define SHARED_LOCK     1
10550 #define RESERVED_LOCK   2
10551 #define PENDING_LOCK    3
10552 #define EXCLUSIVE_LOCK  4
10553
10554 /*
10555 ** File Locking Notes:  (Mostly about windows but also some info for Unix)
10556 **
10557 ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
10558 ** those functions are not available.  So we use only LockFile() and
10559 ** UnlockFile().
10560 **
10561 ** LockFile() prevents not just writing but also reading by other processes.
10562 ** A SHARED_LOCK is obtained by locking a single randomly-chosen 
10563 ** byte out of a specific range of bytes. The lock byte is obtained at 
10564 ** random so two separate readers can probably access the file at the 
10565 ** same time, unless they are unlucky and choose the same lock byte.
10566 ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
10567 ** There can only be one writer.  A RESERVED_LOCK is obtained by locking
10568 ** a single byte of the file that is designated as the reserved lock byte.
10569 ** A PENDING_LOCK is obtained by locking a designated byte different from
10570 ** the RESERVED_LOCK byte.
10571 **
10572 ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
10573 ** which means we can use reader/writer locks.  When reader/writer locks
10574 ** are used, the lock is placed on the same range of bytes that is used
10575 ** for probabilistic locking in Win95/98/ME.  Hence, the locking scheme
10576 ** will support two or more Win95 readers or two or more WinNT readers.
10577 ** But a single Win95 reader will lock out all WinNT readers and a single
10578 ** WinNT reader will lock out all other Win95 readers.
10579 **
10580 ** The following #defines specify the range of bytes used for locking.
10581 ** SHARED_SIZE is the number of bytes available in the pool from which
10582 ** a random byte is selected for a shared lock.  The pool of bytes for
10583 ** shared locks begins at SHARED_FIRST. 
10584 **
10585 ** The same locking strategy and
10586 ** byte ranges are used for Unix.  This leaves open the possibility of having
10587 ** clients on win95, winNT, and unix all talking to the same shared file
10588 ** and all locking correctly.  To do so would require that samba (or whatever
10589 ** tool is being used for file sharing) implements locks correctly between
10590 ** windows and unix.  I'm guessing that isn't likely to happen, but by
10591 ** using the same locking range we are at least open to the possibility.
10592 **
10593 ** Locking in windows is manditory.  For this reason, we cannot store
10594 ** actual data in the bytes used for locking.  The pager never allocates
10595 ** the pages involved in locking therefore.  SHARED_SIZE is selected so
10596 ** that all locks will fit on a single page even at the minimum page size.
10597 ** PENDING_BYTE defines the beginning of the locks.  By default PENDING_BYTE
10598 ** is set high so that we don't have to allocate an unused page except
10599 ** for very large databases.  But one should test the page skipping logic 
10600 ** by setting PENDING_BYTE low and running the entire regression suite.
10601 **
10602 ** Changing the value of PENDING_BYTE results in a subtly incompatible
10603 ** file format.  Depending on how it is changed, you might not notice
10604 ** the incompatibility right away, even running a full regression test.
10605 ** The default location of PENDING_BYTE is the first byte past the
10606 ** 1GB boundary.
10607 **
10608 */
10609 #ifdef SQLITE_OMIT_WSD
10610 # define PENDING_BYTE     (0x40000000)
10611 #else
10612 # define PENDING_BYTE      sqlite3PendingByte
10613 #endif
10614 #define RESERVED_BYTE     (PENDING_BYTE+1)
10615 #define SHARED_FIRST      (PENDING_BYTE+2)
10616 #define SHARED_SIZE       510
10617
10618 /*
10619 ** Wrapper around OS specific sqlite3_os_init() function.
10620 */
10621 SQLITE_PRIVATE int sqlite3OsInit(void);
10622
10623 /* 
10624 ** Functions for accessing sqlite3_file methods 
10625 */
10626 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
10627 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
10628 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
10629 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
10630 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
10631 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
10632 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
10633 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
10634 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
10635 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
10636 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
10637 #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
10638 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
10639 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
10640 SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
10641 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
10642 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
10643 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
10644 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
10645 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
10646
10647
10648 /* 
10649 ** Functions for accessing sqlite3_vfs methods 
10650 */
10651 SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
10652 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
10653 SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
10654 SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
10655 #ifndef SQLITE_OMIT_LOAD_EXTENSION
10656 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
10657 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
10658 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
10659 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
10660 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
10661 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
10662 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
10663 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
10664
10665 /*
10666 ** Convenience functions for opening and closing files using 
10667 ** sqlite3_malloc() to obtain space for the file-handle structure.
10668 */
10669 SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
10670 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
10671
10672 #endif /* _SQLITE_OS_H_ */
10673
10674 /************** End of os.h **************************************************/
10675 /************** Continuing where we left off in sqliteInt.h ******************/
10676 /************** Include mutex.h in the middle of sqliteInt.h *****************/
10677 /************** Begin file mutex.h *******************************************/
10678 /*
10679 ** 2007 August 28
10680 **
10681 ** The author disclaims copyright to this source code.  In place of
10682 ** a legal notice, here is a blessing:
10683 **
10684 **    May you do good and not evil.
10685 **    May you find forgiveness for yourself and forgive others.
10686 **    May you share freely, never taking more than you give.
10687 **
10688 *************************************************************************
10689 **
10690 ** This file contains the common header for all mutex implementations.
10691 ** The sqliteInt.h header #includes this file so that it is available
10692 ** to all source files.  We break it out in an effort to keep the code
10693 ** better organized.
10694 **
10695 ** NOTE:  source files should *not* #include this header file directly.
10696 ** Source files should #include the sqliteInt.h file and let that file
10697 ** include this one indirectly.
10698 */
10699
10700
10701 /*
10702 ** Figure out what version of the code to use.  The choices are
10703 **
10704 **   SQLITE_MUTEX_OMIT         No mutex logic.  Not even stubs.  The
10705 **                             mutexes implementation cannot be overridden
10706 **                             at start-time.
10707 **
10708 **   SQLITE_MUTEX_NOOP         For single-threaded applications.  No
10709 **                             mutual exclusion is provided.  But this
10710 **                             implementation can be overridden at
10711 **                             start-time.
10712 **
10713 **   SQLITE_MUTEX_PTHREADS     For multi-threaded applications on Unix.
10714 **
10715 **   SQLITE_MUTEX_W32          For multi-threaded applications on Win32.
10716 */
10717 #if !SQLITE_THREADSAFE
10718 # define SQLITE_MUTEX_OMIT
10719 #endif
10720 #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
10721 #  if SQLITE_OS_UNIX
10722 #    define SQLITE_MUTEX_PTHREADS
10723 #  elif SQLITE_OS_WIN
10724 #    define SQLITE_MUTEX_W32
10725 #  else
10726 #    define SQLITE_MUTEX_NOOP
10727 #  endif
10728 #endif
10729
10730 #ifdef SQLITE_MUTEX_OMIT
10731 /*
10732 ** If this is a no-op implementation, implement everything as macros.
10733 */
10734 #define sqlite3_mutex_alloc(X)    ((sqlite3_mutex*)8)
10735 #define sqlite3_mutex_free(X)
10736 #define sqlite3_mutex_enter(X)    
10737 #define sqlite3_mutex_try(X)      SQLITE_OK
10738 #define sqlite3_mutex_leave(X)    
10739 #define sqlite3_mutex_held(X)     ((void)(X),1)
10740 #define sqlite3_mutex_notheld(X)  ((void)(X),1)
10741 #define sqlite3MutexAlloc(X)      ((sqlite3_mutex*)8)
10742 #define sqlite3MutexInit()        SQLITE_OK
10743 #define sqlite3MutexEnd()
10744 #define MUTEX_LOGIC(X)
10745 #else
10746 #define MUTEX_LOGIC(X)            X
10747 #endif /* defined(SQLITE_MUTEX_OMIT) */
10748
10749 /************** End of mutex.h ***********************************************/
10750 /************** Continuing where we left off in sqliteInt.h ******************/
10751
10752
10753 /*
10754 ** Each database file to be accessed by the system is an instance
10755 ** of the following structure.  There are normally two of these structures
10756 ** in the sqlite.aDb[] array.  aDb[0] is the main database file and
10757 ** aDb[1] is the database file used to hold temporary tables.  Additional
10758 ** databases may be attached.
10759 */
10760 struct Db {
10761   char *zName;         /* Name of this database */
10762   Btree *pBt;          /* The B*Tree structure for this database file */
10763   u8 safety_level;     /* How aggressive at syncing data to disk */
10764   Schema *pSchema;     /* Pointer to database schema (possibly shared) */
10765 };
10766
10767 /*
10768 ** An instance of the following structure stores a database schema.
10769 **
10770 ** Most Schema objects are associated with a Btree.  The exception is
10771 ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
10772 ** In shared cache mode, a single Schema object can be shared by multiple
10773 ** Btrees that refer to the same underlying BtShared object.
10774 ** 
10775 ** Schema objects are automatically deallocated when the last Btree that
10776 ** references them is destroyed.   The TEMP Schema is manually freed by
10777 ** sqlite3_close().
10778 *
10779 ** A thread must be holding a mutex on the corresponding Btree in order
10780 ** to access Schema content.  This implies that the thread must also be
10781 ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
10782 ** For a TEMP Schema, only the connection mutex is required.
10783 */
10784 struct Schema {
10785   int schema_cookie;   /* Database schema version number for this file */
10786   int iGeneration;     /* Generation counter.  Incremented with each change */
10787   Hash tblHash;        /* All tables indexed by name */
10788   Hash idxHash;        /* All (named) indices indexed by name */
10789   Hash trigHash;       /* All triggers indexed by name */
10790   Hash fkeyHash;       /* All foreign keys by referenced table name */
10791   Table *pSeqTab;      /* The sqlite_sequence table used by AUTOINCREMENT */
10792   u8 file_format;      /* Schema format version for this file */
10793   u8 enc;              /* Text encoding used by this database */
10794   u16 schemaFlags;     /* Flags associated with this schema */
10795   int cache_size;      /* Number of pages to use in the cache */
10796 };
10797
10798 /*
10799 ** These macros can be used to test, set, or clear bits in the 
10800 ** Db.pSchema->flags field.
10801 */
10802 #define DbHasProperty(D,I,P)     (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
10803 #define DbHasAnyProperty(D,I,P)  (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
10804 #define DbSetProperty(D,I,P)     (D)->aDb[I].pSchema->schemaFlags|=(P)
10805 #define DbClearProperty(D,I,P)   (D)->aDb[I].pSchema->schemaFlags&=~(P)
10806
10807 /*
10808 ** Allowed values for the DB.pSchema->flags field.
10809 **
10810 ** The DB_SchemaLoaded flag is set after the database schema has been
10811 ** read into internal hash tables.
10812 **
10813 ** DB_UnresetViews means that one or more views have column names that
10814 ** have been filled out.  If the schema changes, these column names might
10815 ** changes and so the view will need to be reset.
10816 */
10817 #define DB_SchemaLoaded    0x0001  /* The schema has been loaded */
10818 #define DB_UnresetViews    0x0002  /* Some views have defined column names */
10819 #define DB_Empty           0x0004  /* The file is empty (length 0 bytes) */
10820
10821 /*
10822 ** The number of different kinds of things that can be limited
10823 ** using the sqlite3_limit() interface.
10824 */
10825 #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
10826
10827 /*
10828 ** Lookaside malloc is a set of fixed-size buffers that can be used
10829 ** to satisfy small transient memory allocation requests for objects
10830 ** associated with a particular database connection.  The use of
10831 ** lookaside malloc provides a significant performance enhancement
10832 ** (approx 10%) by avoiding numerous malloc/free requests while parsing
10833 ** SQL statements.
10834 **
10835 ** The Lookaside structure holds configuration information about the
10836 ** lookaside malloc subsystem.  Each available memory allocation in
10837 ** the lookaside subsystem is stored on a linked list of LookasideSlot
10838 ** objects.
10839 **
10840 ** Lookaside allocations are only allowed for objects that are associated
10841 ** with a particular database connection.  Hence, schema information cannot
10842 ** be stored in lookaside because in shared cache mode the schema information
10843 ** is shared by multiple database connections.  Therefore, while parsing
10844 ** schema information, the Lookaside.bEnabled flag is cleared so that
10845 ** lookaside allocations are not used to construct the schema objects.
10846 */
10847 struct Lookaside {
10848   u16 sz;                 /* Size of each buffer in bytes */
10849   u8 bEnabled;            /* False to disable new lookaside allocations */
10850   u8 bMalloced;           /* True if pStart obtained from sqlite3_malloc() */
10851   int nOut;               /* Number of buffers currently checked out */
10852   int mxOut;              /* Highwater mark for nOut */
10853   int anStat[3];          /* 0: hits.  1: size misses.  2: full misses */
10854   LookasideSlot *pFree;   /* List of available buffers */
10855   void *pStart;           /* First byte of available memory space */
10856   void *pEnd;             /* First byte past end of available space */
10857 };
10858 struct LookasideSlot {
10859   LookasideSlot *pNext;    /* Next buffer in the list of free buffers */
10860 };
10861
10862 /*
10863 ** A hash table for function definitions.
10864 **
10865 ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
10866 ** Collisions are on the FuncDef.pHash chain.
10867 */
10868 struct FuncDefHash {
10869   FuncDef *a[23];       /* Hash table for functions */
10870 };
10871
10872 #ifdef SQLITE_USER_AUTHENTICATION
10873 /*
10874 ** Information held in the "sqlite3" database connection object and used
10875 ** to manage user authentication.
10876 */
10877 typedef struct sqlite3_userauth sqlite3_userauth;
10878 struct sqlite3_userauth {
10879   u8 authLevel;                 /* Current authentication level */
10880   int nAuthPW;                  /* Size of the zAuthPW in bytes */
10881   char *zAuthPW;                /* Password used to authenticate */
10882   char *zAuthUser;              /* User name used to authenticate */
10883 };
10884
10885 /* Allowed values for sqlite3_userauth.authLevel */
10886 #define UAUTH_Unknown     0     /* Authentication not yet checked */
10887 #define UAUTH_Fail        1     /* User authentication failed */
10888 #define UAUTH_User        2     /* Authenticated as a normal user */
10889 #define UAUTH_Admin       3     /* Authenticated as an administrator */
10890
10891 /* Functions used only by user authorization logic */
10892 SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
10893 SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
10894 SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
10895 SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
10896
10897 #endif /* SQLITE_USER_AUTHENTICATION */
10898
10899 /*
10900 ** typedef for the authorization callback function.
10901 */
10902 #ifdef SQLITE_USER_AUTHENTICATION
10903   typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
10904                                const char*, const char*);
10905 #else
10906   typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
10907                                const char*);
10908 #endif
10909
10910
10911 /*
10912 ** Each database connection is an instance of the following structure.
10913 */
10914 struct sqlite3 {
10915   sqlite3_vfs *pVfs;            /* OS Interface */
10916   struct Vdbe *pVdbe;           /* List of active virtual machines */
10917   CollSeq *pDfltColl;           /* The default collating sequence (BINARY) */
10918   sqlite3_mutex *mutex;         /* Connection mutex */
10919   Db *aDb;                      /* All backends */
10920   int nDb;                      /* Number of backends currently in use */
10921   int flags;                    /* Miscellaneous flags. See below */
10922   i64 lastRowid;                /* ROWID of most recent insert (see above) */
10923   i64 szMmap;                   /* Default mmap_size setting */
10924   unsigned int openFlags;       /* Flags passed to sqlite3_vfs.xOpen() */
10925   int errCode;                  /* Most recent error code (SQLITE_*) */
10926   int errMask;                  /* & result codes with this before returning */
10927   u16 dbOptFlags;               /* Flags to enable/disable optimizations */
10928   u8 enc;                       /* Text encoding */
10929   u8 autoCommit;                /* The auto-commit flag. */
10930   u8 temp_store;                /* 1: file 2: memory 0: default */
10931   u8 mallocFailed;              /* True if we have seen a malloc failure */
10932   u8 dfltLockMode;              /* Default locking-mode for attached dbs */
10933   signed char nextAutovac;      /* Autovac setting after VACUUM if >=0 */
10934   u8 suppressErr;               /* Do not issue error messages if true */
10935   u8 vtabOnConflict;            /* Value to return for s3_vtab_on_conflict() */
10936   u8 isTransactionSavepoint;    /* True if the outermost savepoint is a TS */
10937   int nextPagesize;             /* Pagesize after VACUUM if >0 */
10938   u32 magic;                    /* Magic number for detect library misuse */
10939   int nChange;                  /* Value returned by sqlite3_changes() */
10940   int nTotalChange;             /* Value returned by sqlite3_total_changes() */
10941   int aLimit[SQLITE_N_LIMIT];   /* Limits */
10942   int nMaxSorterMmap;           /* Maximum size of regions mapped by sorter */
10943   struct sqlite3InitInfo {      /* Information used during initialization */
10944     int newTnum;                /* Rootpage of table being initialized */
10945     u8 iDb;                     /* Which db file is being initialized */
10946     u8 busy;                    /* TRUE if currently initializing */
10947     u8 orphanTrigger;           /* Last statement is orphaned TEMP trigger */
10948     u8 imposterTable;           /* Building an imposter table */
10949   } init;
10950   int nVdbeActive;              /* Number of VDBEs currently running */
10951   int nVdbeRead;                /* Number of active VDBEs that read or write */
10952   int nVdbeWrite;               /* Number of active VDBEs that read and write */
10953   int nVdbeExec;                /* Number of nested calls to VdbeExec() */
10954   int nVDestroy;                /* Number of active OP_VDestroy operations */
10955   int nExtension;               /* Number of loaded extensions */
10956   void **aExtension;            /* Array of shared library handles */
10957   void (*xTrace)(void*,const char*);        /* Trace function */
10958   void *pTraceArg;                          /* Argument to the trace function */
10959   void (*xProfile)(void*,const char*,u64);  /* Profiling function */
10960   void *pProfileArg;                        /* Argument to profile function */
10961   void *pCommitArg;                 /* Argument to xCommitCallback() */   
10962   int (*xCommitCallback)(void*);    /* Invoked at every commit. */
10963   void *pRollbackArg;               /* Argument to xRollbackCallback() */   
10964   void (*xRollbackCallback)(void*); /* Invoked at every commit. */
10965   void *pUpdateArg;
10966   void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
10967 #ifndef SQLITE_OMIT_WAL
10968   int (*xWalCallback)(void *, sqlite3 *, const char *, int);
10969   void *pWalArg;
10970 #endif
10971   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
10972   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
10973   void *pCollNeededArg;
10974   sqlite3_value *pErr;          /* Most recent error message */
10975   union {
10976     volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
10977     double notUsed1;            /* Spacer */
10978   } u1;
10979   Lookaside lookaside;          /* Lookaside malloc configuration */
10980 #ifndef SQLITE_OMIT_AUTHORIZATION
10981   sqlite3_xauth xAuth;          /* Access authorization function */
10982   void *pAuthArg;               /* 1st argument to the access auth function */
10983 #endif
10984 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
10985   int (*xProgress)(void *);     /* The progress callback */
10986   void *pProgressArg;           /* Argument to the progress callback */
10987   unsigned nProgressOps;        /* Number of opcodes for progress callback */
10988 #endif
10989 #ifndef SQLITE_OMIT_VIRTUALTABLE
10990   int nVTrans;                  /* Allocated size of aVTrans */
10991   Hash aModule;                 /* populated by sqlite3_create_module() */
10992   VtabCtx *pVtabCtx;            /* Context for active vtab connect/create */
10993   VTable **aVTrans;             /* Virtual tables with open transactions */
10994   VTable *pDisconnect;    /* Disconnect these in next sqlite3_prepare() */
10995 #endif
10996   FuncDefHash aFunc;            /* Hash table of connection functions */
10997   Hash aCollSeq;                /* All collating sequences */
10998   BusyHandler busyHandler;      /* Busy callback */
10999   Db aDbStatic[2];              /* Static space for the 2 default backends */
11000   Savepoint *pSavepoint;        /* List of active savepoints */
11001   int busyTimeout;              /* Busy handler timeout, in msec */
11002   int nSavepoint;               /* Number of non-transaction savepoints */
11003   int nStatement;               /* Number of nested statement-transactions  */
11004   i64 nDeferredCons;            /* Net deferred constraints this transaction. */
11005   i64 nDeferredImmCons;         /* Net deferred immediate constraints */
11006   int *pnBytesFreed;            /* If not NULL, increment this in DbFree() */
11007 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
11008   /* The following variables are all protected by the STATIC_MASTER 
11009   ** mutex, not by sqlite3.mutex. They are used by code in notify.c. 
11010   **
11011   ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
11012   ** unlock so that it can proceed.
11013   **
11014   ** When X.pBlockingConnection==Y, that means that something that X tried
11015   ** tried to do recently failed with an SQLITE_LOCKED error due to locks
11016   ** held by Y.
11017   */
11018   sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
11019   sqlite3 *pUnlockConnection;           /* Connection to watch for unlock */
11020   void *pUnlockArg;                     /* Argument to xUnlockNotify */
11021   void (*xUnlockNotify)(void **, int);  /* Unlock notify callback */
11022   sqlite3 *pNextBlocked;        /* Next in list of all blocked connections */
11023 #endif
11024 #ifdef SQLITE_USER_AUTHENTICATION
11025   sqlite3_userauth auth;        /* User authentication information */
11026 #endif
11027 };
11028
11029 /*
11030 ** A macro to discover the encoding of a database.
11031 */
11032 #define SCHEMA_ENC(db) ((db)->aDb[0].pSchema->enc)
11033 #define ENC(db)        ((db)->enc)
11034
11035 /*
11036 ** Possible values for the sqlite3.flags.
11037 */
11038 #define SQLITE_VdbeTrace      0x00000001  /* True to trace VDBE execution */
11039 #define SQLITE_InternChanges  0x00000002  /* Uncommitted Hash table changes */
11040 #define SQLITE_FullFSync      0x00000004  /* Use full fsync on the backend */
11041 #define SQLITE_CkptFullFSync  0x00000008  /* Use full fsync for checkpoint */
11042 #define SQLITE_CacheSpill     0x00000010  /* OK to spill pager cache */
11043 #define SQLITE_FullColNames   0x00000020  /* Show full column names on SELECT */
11044 #define SQLITE_ShortColNames  0x00000040  /* Show short columns names */
11045 #define SQLITE_CountRows      0x00000080  /* Count rows changed by INSERT, */
11046                                           /*   DELETE, or UPDATE and return */
11047                                           /*   the count using a callback. */
11048 #define SQLITE_NullCallback   0x00000100  /* Invoke the callback once if the */
11049                                           /*   result set is empty */
11050 #define SQLITE_SqlTrace       0x00000200  /* Debug print SQL as it executes */
11051 #define SQLITE_VdbeListing    0x00000400  /* Debug listings of VDBE programs */
11052 #define SQLITE_WriteSchema    0x00000800  /* OK to update SQLITE_MASTER */
11053 #define SQLITE_VdbeAddopTrace 0x00001000  /* Trace sqlite3VdbeAddOp() calls */
11054 #define SQLITE_IgnoreChecks   0x00002000  /* Do not enforce check constraints */
11055 #define SQLITE_ReadUncommitted 0x0004000  /* For shared-cache mode */
11056 #define SQLITE_LegacyFileFmt  0x00008000  /* Create new databases in format 1 */
11057 #define SQLITE_RecoveryMode   0x00010000  /* Ignore schema errors */
11058 #define SQLITE_ReverseOrder   0x00020000  /* Reverse unordered SELECTs */
11059 #define SQLITE_RecTriggers    0x00040000  /* Enable recursive triggers */
11060 #define SQLITE_ForeignKeys    0x00080000  /* Enforce foreign key constraints  */
11061 #define SQLITE_AutoIndex      0x00100000  /* Enable automatic indexes */
11062 #define SQLITE_PreferBuiltin  0x00200000  /* Preference to built-in funcs */
11063 #define SQLITE_LoadExtension  0x00400000  /* Enable load_extension */
11064 #define SQLITE_EnableTrigger  0x00800000  /* True to enable triggers */
11065 #define SQLITE_DeferFKs       0x01000000  /* Defer all FK constraints */
11066 #define SQLITE_QueryOnly      0x02000000  /* Disable database changes */
11067 #define SQLITE_VdbeEQP        0x04000000  /* Debug EXPLAIN QUERY PLAN */
11068
11069
11070 /*
11071 ** Bits of the sqlite3.dbOptFlags field that are used by the
11072 ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
11073 ** selectively disable various optimizations.
11074 */
11075 #define SQLITE_QueryFlattener 0x0001   /* Query flattening */
11076 #define SQLITE_ColumnCache    0x0002   /* Column cache */
11077 #define SQLITE_GroupByOrder   0x0004   /* GROUPBY cover of ORDERBY */
11078 #define SQLITE_FactorOutConst 0x0008   /* Constant factoring */
11079 /*                not used    0x0010   // Was: SQLITE_IdxRealAsInt */
11080 #define SQLITE_DistinctOpt    0x0020   /* DISTINCT using indexes */
11081 #define SQLITE_CoverIdxScan   0x0040   /* Covering index scans */
11082 #define SQLITE_OrderByIdxJoin 0x0080   /* ORDER BY of joins via index */
11083 #define SQLITE_SubqCoroutine  0x0100   /* Evaluate subqueries as coroutines */
11084 #define SQLITE_Transitive     0x0200   /* Transitive constraints */
11085 #define SQLITE_OmitNoopJoin   0x0400   /* Omit unused tables in joins */
11086 #define SQLITE_Stat34         0x0800   /* Use STAT3 or STAT4 data */
11087 #define SQLITE_AllOpts        0xffff   /* All optimizations */
11088
11089 /*
11090 ** Macros for testing whether or not optimizations are enabled or disabled.
11091 */
11092 #ifndef SQLITE_OMIT_BUILTIN_TEST
11093 #define OptimizationDisabled(db, mask)  (((db)->dbOptFlags&(mask))!=0)
11094 #define OptimizationEnabled(db, mask)   (((db)->dbOptFlags&(mask))==0)
11095 #else
11096 #define OptimizationDisabled(db, mask)  0
11097 #define OptimizationEnabled(db, mask)   1
11098 #endif
11099
11100 /*
11101 ** Return true if it OK to factor constant expressions into the initialization
11102 ** code. The argument is a Parse object for the code generator.
11103 */
11104 #define ConstFactorOk(P) ((P)->okConstFactor)
11105
11106 /*
11107 ** Possible values for the sqlite.magic field.
11108 ** The numbers are obtained at random and have no special meaning, other
11109 ** than being distinct from one another.
11110 */
11111 #define SQLITE_MAGIC_OPEN     0xa029a697  /* Database is open */
11112 #define SQLITE_MAGIC_CLOSED   0x9f3c2d33  /* Database is closed */
11113 #define SQLITE_MAGIC_SICK     0x4b771290  /* Error and awaiting close */
11114 #define SQLITE_MAGIC_BUSY     0xf03b7906  /* Database currently in use */
11115 #define SQLITE_MAGIC_ERROR    0xb5357930  /* An SQLITE_MISUSE error occurred */
11116 #define SQLITE_MAGIC_ZOMBIE   0x64cffc7f  /* Close with last statement close */
11117
11118 /*
11119 ** Each SQL function is defined by an instance of the following
11120 ** structure.  A pointer to this structure is stored in the sqlite.aFunc
11121 ** hash table.  When multiple functions have the same name, the hash table
11122 ** points to a linked list of these structures.
11123 */
11124 struct FuncDef {
11125   i16 nArg;            /* Number of arguments.  -1 means unlimited */
11126   u16 funcFlags;       /* Some combination of SQLITE_FUNC_* */
11127   void *pUserData;     /* User data parameter */
11128   FuncDef *pNext;      /* Next function with same name */
11129   void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
11130   void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
11131   void (*xFinalize)(sqlite3_context*);                /* Aggregate finalizer */
11132   char *zName;         /* SQL name of the function. */
11133   FuncDef *pHash;      /* Next with a different name but the same hash */
11134   FuncDestructor *pDestructor;   /* Reference counted destructor function */
11135 };
11136
11137 /*
11138 ** This structure encapsulates a user-function destructor callback (as
11139 ** configured using create_function_v2()) and a reference counter. When
11140 ** create_function_v2() is called to create a function with a destructor,
11141 ** a single object of this type is allocated. FuncDestructor.nRef is set to 
11142 ** the number of FuncDef objects created (either 1 or 3, depending on whether
11143 ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
11144 ** member of each of the new FuncDef objects is set to point to the allocated
11145 ** FuncDestructor.
11146 **
11147 ** Thereafter, when one of the FuncDef objects is deleted, the reference
11148 ** count on this object is decremented. When it reaches 0, the destructor
11149 ** is invoked and the FuncDestructor structure freed.
11150 */
11151 struct FuncDestructor {
11152   int nRef;
11153   void (*xDestroy)(void *);
11154   void *pUserData;
11155 };
11156
11157 /*
11158 ** Possible values for FuncDef.flags.  Note that the _LENGTH and _TYPEOF
11159 ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG.  There
11160 ** are assert() statements in the code to verify this.
11161 */
11162 #define SQLITE_FUNC_ENCMASK  0x003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
11163 #define SQLITE_FUNC_LIKE     0x004 /* Candidate for the LIKE optimization */
11164 #define SQLITE_FUNC_CASE     0x008 /* Case-sensitive LIKE-type function */
11165 #define SQLITE_FUNC_EPHEM    0x010 /* Ephemeral.  Delete with VDBE */
11166 #define SQLITE_FUNC_NEEDCOLL 0x020 /* sqlite3GetFuncCollSeq() might be called */
11167 #define SQLITE_FUNC_LENGTH   0x040 /* Built-in length() function */
11168 #define SQLITE_FUNC_TYPEOF   0x080 /* Built-in typeof() function */
11169 #define SQLITE_FUNC_COUNT    0x100 /* Built-in count(*) aggregate */
11170 #define SQLITE_FUNC_COALESCE 0x200 /* Built-in coalesce() or ifnull() */
11171 #define SQLITE_FUNC_UNLIKELY 0x400 /* Built-in unlikely() function */
11172 #define SQLITE_FUNC_CONSTANT 0x800 /* Constant inputs give a constant output */
11173 #define SQLITE_FUNC_MINMAX  0x1000 /* True for min() and max() aggregates */
11174
11175 /*
11176 ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
11177 ** used to create the initializers for the FuncDef structures.
11178 **
11179 **   FUNCTION(zName, nArg, iArg, bNC, xFunc)
11180 **     Used to create a scalar function definition of a function zName 
11181 **     implemented by C function xFunc that accepts nArg arguments. The
11182 **     value passed as iArg is cast to a (void*) and made available
11183 **     as the user-data (sqlite3_user_data()) for the function. If 
11184 **     argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
11185 **
11186 **   VFUNCTION(zName, nArg, iArg, bNC, xFunc)
11187 **     Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
11188 **
11189 **   AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
11190 **     Used to create an aggregate function definition implemented by
11191 **     the C functions xStep and xFinal. The first four parameters
11192 **     are interpreted in the same way as the first 4 parameters to
11193 **     FUNCTION().
11194 **
11195 **   LIKEFUNC(zName, nArg, pArg, flags)
11196 **     Used to create a scalar function definition of a function zName 
11197 **     that accepts nArg arguments and is implemented by a call to C 
11198 **     function likeFunc. Argument pArg is cast to a (void *) and made
11199 **     available as the function user-data (sqlite3_user_data()). The
11200 **     FuncDef.flags variable is set to the value passed as the flags
11201 **     parameter.
11202 */
11203 #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
11204   {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
11205    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
11206 #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
11207   {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
11208    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
11209 #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
11210   {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
11211    SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
11212 #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
11213   {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
11214    pArg, 0, xFunc, 0, 0, #zName, 0, 0}
11215 #define LIKEFUNC(zName, nArg, arg, flags) \
11216   {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
11217    (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
11218 #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
11219   {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
11220    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
11221 #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
11222   {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
11223    SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
11224
11225 /*
11226 ** All current savepoints are stored in a linked list starting at
11227 ** sqlite3.pSavepoint. The first element in the list is the most recently
11228 ** opened savepoint. Savepoints are added to the list by the vdbe
11229 ** OP_Savepoint instruction.
11230 */
11231 struct Savepoint {
11232   char *zName;                        /* Savepoint name (nul-terminated) */
11233   i64 nDeferredCons;                  /* Number of deferred fk violations */
11234   i64 nDeferredImmCons;               /* Number of deferred imm fk. */
11235   Savepoint *pNext;                   /* Parent savepoint (if any) */
11236 };
11237
11238 /*
11239 ** The following are used as the second parameter to sqlite3Savepoint(),
11240 ** and as the P1 argument to the OP_Savepoint instruction.
11241 */
11242 #define SAVEPOINT_BEGIN      0
11243 #define SAVEPOINT_RELEASE    1
11244 #define SAVEPOINT_ROLLBACK   2
11245
11246
11247 /*
11248 ** Each SQLite module (virtual table definition) is defined by an
11249 ** instance of the following structure, stored in the sqlite3.aModule
11250 ** hash table.
11251 */
11252 struct Module {
11253   const sqlite3_module *pModule;       /* Callback pointers */
11254   const char *zName;                   /* Name passed to create_module() */
11255   void *pAux;                          /* pAux passed to create_module() */
11256   void (*xDestroy)(void *);            /* Module destructor function */
11257 };
11258
11259 /*
11260 ** information about each column of an SQL table is held in an instance
11261 ** of this structure.
11262 */
11263 struct Column {
11264   char *zName;     /* Name of this column */
11265   Expr *pDflt;     /* Default value of this column */
11266   char *zDflt;     /* Original text of the default value */
11267   char *zType;     /* Data type for this column */
11268   char *zColl;     /* Collating sequence.  If NULL, use the default */
11269   u8 notNull;      /* An OE_ code for handling a NOT NULL constraint */
11270   char affinity;   /* One of the SQLITE_AFF_... values */
11271   u8 szEst;        /* Estimated size of this column.  INT==1 */
11272   u8 colFlags;     /* Boolean properties.  See COLFLAG_ defines below */
11273 };
11274
11275 /* Allowed values for Column.colFlags:
11276 */
11277 #define COLFLAG_PRIMKEY  0x0001    /* Column is part of the primary key */
11278 #define COLFLAG_HIDDEN   0x0002    /* A hidden column in a virtual table */
11279
11280 /*
11281 ** A "Collating Sequence" is defined by an instance of the following
11282 ** structure. Conceptually, a collating sequence consists of a name and
11283 ** a comparison routine that defines the order of that sequence.
11284 **
11285 ** If CollSeq.xCmp is NULL, it means that the
11286 ** collating sequence is undefined.  Indices built on an undefined
11287 ** collating sequence may not be read or written.
11288 */
11289 struct CollSeq {
11290   char *zName;          /* Name of the collating sequence, UTF-8 encoded */
11291   u8 enc;               /* Text encoding handled by xCmp() */
11292   void *pUser;          /* First argument to xCmp() */
11293   int (*xCmp)(void*,int, const void*, int, const void*);
11294   void (*xDel)(void*);  /* Destructor for pUser */
11295 };
11296
11297 /*
11298 ** A sort order can be either ASC or DESC.
11299 */
11300 #define SQLITE_SO_ASC       0  /* Sort in ascending order */
11301 #define SQLITE_SO_DESC      1  /* Sort in ascending order */
11302
11303 /*
11304 ** Column affinity types.
11305 **
11306 ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
11307 ** 't' for SQLITE_AFF_TEXT.  But we can save a little space and improve
11308 ** the speed a little by numbering the values consecutively.  
11309 **
11310 ** But rather than start with 0 or 1, we begin with 'A'.  That way,
11311 ** when multiple affinity types are concatenated into a string and
11312 ** used as the P4 operand, they will be more readable.
11313 **
11314 ** Note also that the numeric types are grouped together so that testing
11315 ** for a numeric type is a single comparison.  And the NONE type is first.
11316 */
11317 #define SQLITE_AFF_NONE     'A'
11318 #define SQLITE_AFF_TEXT     'B'
11319 #define SQLITE_AFF_NUMERIC  'C'
11320 #define SQLITE_AFF_INTEGER  'D'
11321 #define SQLITE_AFF_REAL     'E'
11322
11323 #define sqlite3IsNumericAffinity(X)  ((X)>=SQLITE_AFF_NUMERIC)
11324
11325 /*
11326 ** The SQLITE_AFF_MASK values masks off the significant bits of an
11327 ** affinity value. 
11328 */
11329 #define SQLITE_AFF_MASK     0x47
11330
11331 /*
11332 ** Additional bit values that can be ORed with an affinity without
11333 ** changing the affinity.
11334 **
11335 ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
11336 ** It causes an assert() to fire if either operand to a comparison
11337 ** operator is NULL.  It is added to certain comparison operators to
11338 ** prove that the operands are always NOT NULL.
11339 */
11340 #define SQLITE_JUMPIFNULL   0x10  /* jumps if either operand is NULL */
11341 #define SQLITE_STOREP2      0x20  /* Store result in reg[P2] rather than jump */
11342 #define SQLITE_NULLEQ       0x80  /* NULL=NULL */
11343 #define SQLITE_NOTNULL      0x90  /* Assert that operands are never NULL */
11344
11345 /*
11346 ** An object of this type is created for each virtual table present in
11347 ** the database schema. 
11348 **
11349 ** If the database schema is shared, then there is one instance of this
11350 ** structure for each database connection (sqlite3*) that uses the shared
11351 ** schema. This is because each database connection requires its own unique
11352 ** instance of the sqlite3_vtab* handle used to access the virtual table 
11353 ** implementation. sqlite3_vtab* handles can not be shared between 
11354 ** database connections, even when the rest of the in-memory database 
11355 ** schema is shared, as the implementation often stores the database
11356 ** connection handle passed to it via the xConnect() or xCreate() method
11357 ** during initialization internally. This database connection handle may
11358 ** then be used by the virtual table implementation to access real tables 
11359 ** within the database. So that they appear as part of the callers 
11360 ** transaction, these accesses need to be made via the same database 
11361 ** connection as that used to execute SQL operations on the virtual table.
11362 **
11363 ** All VTable objects that correspond to a single table in a shared
11364 ** database schema are initially stored in a linked-list pointed to by
11365 ** the Table.pVTable member variable of the corresponding Table object.
11366 ** When an sqlite3_prepare() operation is required to access the virtual
11367 ** table, it searches the list for the VTable that corresponds to the
11368 ** database connection doing the preparing so as to use the correct
11369 ** sqlite3_vtab* handle in the compiled query.
11370 **
11371 ** When an in-memory Table object is deleted (for example when the
11372 ** schema is being reloaded for some reason), the VTable objects are not 
11373 ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed 
11374 ** immediately. Instead, they are moved from the Table.pVTable list to
11375 ** another linked list headed by the sqlite3.pDisconnect member of the
11376 ** corresponding sqlite3 structure. They are then deleted/xDisconnected 
11377 ** next time a statement is prepared using said sqlite3*. This is done
11378 ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
11379 ** Refer to comments above function sqlite3VtabUnlockList() for an
11380 ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
11381 ** list without holding the corresponding sqlite3.mutex mutex.
11382 **
11383 ** The memory for objects of this type is always allocated by 
11384 ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as 
11385 ** the first argument.
11386 */
11387 struct VTable {
11388   sqlite3 *db;              /* Database connection associated with this table */
11389   Module *pMod;             /* Pointer to module implementation */
11390   sqlite3_vtab *pVtab;      /* Pointer to vtab instance */
11391   int nRef;                 /* Number of pointers to this structure */
11392   u8 bConstraint;           /* True if constraints are supported */
11393   int iSavepoint;           /* Depth of the SAVEPOINT stack */
11394   VTable *pNext;            /* Next in linked list (see above) */
11395 };
11396
11397 /*
11398 ** Each SQL table is represented in memory by an instance of the
11399 ** following structure.
11400 **
11401 ** Table.zName is the name of the table.  The case of the original
11402 ** CREATE TABLE statement is stored, but case is not significant for
11403 ** comparisons.
11404 **
11405 ** Table.nCol is the number of columns in this table.  Table.aCol is a
11406 ** pointer to an array of Column structures, one for each column.
11407 **
11408 ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
11409 ** the column that is that key.   Otherwise Table.iPKey is negative.  Note
11410 ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
11411 ** be set.  An INTEGER PRIMARY KEY is used as the rowid for each row of
11412 ** the table.  If a table has no INTEGER PRIMARY KEY, then a random rowid
11413 ** is generated for each row of the table.  TF_HasPrimaryKey is set if
11414 ** the table has any PRIMARY KEY, INTEGER or otherwise.
11415 **
11416 ** Table.tnum is the page number for the root BTree page of the table in the
11417 ** database file.  If Table.iDb is the index of the database table backend
11418 ** in sqlite.aDb[].  0 is for the main database and 1 is for the file that
11419 ** holds temporary tables and indices.  If TF_Ephemeral is set
11420 ** then the table is stored in a file that is automatically deleted
11421 ** when the VDBE cursor to the table is closed.  In this case Table.tnum 
11422 ** refers VDBE cursor number that holds the table open, not to the root
11423 ** page number.  Transient tables are used to hold the results of a
11424 ** sub-query that appears instead of a real table name in the FROM clause 
11425 ** of a SELECT statement.
11426 */
11427 struct Table {
11428   char *zName;         /* Name of the table or view */
11429   Column *aCol;        /* Information about each column */
11430   Index *pIndex;       /* List of SQL indexes on this table. */
11431   Select *pSelect;     /* NULL for tables.  Points to definition if a view. */
11432   FKey *pFKey;         /* Linked list of all foreign keys in this table */
11433   char *zColAff;       /* String defining the affinity of each column */
11434 #ifndef SQLITE_OMIT_CHECK
11435   ExprList *pCheck;    /* All CHECK constraints */
11436 #endif
11437   LogEst nRowLogEst;   /* Estimated rows in table - from sqlite_stat1 table */
11438   int tnum;            /* Root BTree node for this table (see note above) */
11439   i16 iPKey;           /* If not negative, use aCol[iPKey] as the primary key */
11440   i16 nCol;            /* Number of columns in this table */
11441   u16 nRef;            /* Number of pointers to this Table */
11442   LogEst szTabRow;     /* Estimated size of each table row in bytes */
11443 #ifdef SQLITE_ENABLE_COSTMULT
11444   LogEst costMult;     /* Cost multiplier for using this table */
11445 #endif
11446   u8 tabFlags;         /* Mask of TF_* values */
11447   u8 keyConf;          /* What to do in case of uniqueness conflict on iPKey */
11448 #ifndef SQLITE_OMIT_ALTERTABLE
11449   int addColOffset;    /* Offset in CREATE TABLE stmt to add a new column */
11450 #endif
11451 #ifndef SQLITE_OMIT_VIRTUALTABLE
11452   int nModuleArg;      /* Number of arguments to the module */
11453   char **azModuleArg;  /* Text of all module args. [0] is module name */
11454   VTable *pVTable;     /* List of VTable objects. */
11455 #endif
11456   Trigger *pTrigger;   /* List of triggers stored in pSchema */
11457   Schema *pSchema;     /* Schema that contains this table */
11458   Table *pNextZombie;  /* Next on the Parse.pZombieTab list */
11459 };
11460
11461 /*
11462 ** Allowed values for Table.tabFlags.
11463 */
11464 #define TF_Readonly        0x01    /* Read-only system table */
11465 #define TF_Ephemeral       0x02    /* An ephemeral table */
11466 #define TF_HasPrimaryKey   0x04    /* Table has a primary key */
11467 #define TF_Autoincrement   0x08    /* Integer primary key is autoincrement */
11468 #define TF_Virtual         0x10    /* Is a virtual table */
11469 #define TF_WithoutRowid    0x20    /* No rowid used. PRIMARY KEY is the key */
11470
11471
11472 /*
11473 ** Test to see whether or not a table is a virtual table.  This is
11474 ** done as a macro so that it will be optimized out when virtual
11475 ** table support is omitted from the build.
11476 */
11477 #ifndef SQLITE_OMIT_VIRTUALTABLE
11478 #  define IsVirtual(X)      (((X)->tabFlags & TF_Virtual)!=0)
11479 #  define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
11480 #else
11481 #  define IsVirtual(X)      0
11482 #  define IsHiddenColumn(X) 0
11483 #endif
11484
11485 /* Does the table have a rowid */
11486 #define HasRowid(X)     (((X)->tabFlags & TF_WithoutRowid)==0)
11487
11488 /*
11489 ** Each foreign key constraint is an instance of the following structure.
11490 **
11491 ** A foreign key is associated with two tables.  The "from" table is
11492 ** the table that contains the REFERENCES clause that creates the foreign
11493 ** key.  The "to" table is the table that is named in the REFERENCES clause.
11494 ** Consider this example:
11495 **
11496 **     CREATE TABLE ex1(
11497 **       a INTEGER PRIMARY KEY,
11498 **       b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
11499 **     );
11500 **
11501 ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
11502 ** Equivalent names:
11503 **
11504 **     from-table == child-table
11505 **       to-table == parent-table
11506 **
11507 ** Each REFERENCES clause generates an instance of the following structure
11508 ** which is attached to the from-table.  The to-table need not exist when
11509 ** the from-table is created.  The existence of the to-table is not checked.
11510 **
11511 ** The list of all parents for child Table X is held at X.pFKey.
11512 **
11513 ** A list of all children for a table named Z (which might not even exist)
11514 ** is held in Schema.fkeyHash with a hash key of Z.
11515 */
11516 struct FKey {
11517   Table *pFrom;     /* Table containing the REFERENCES clause (aka: Child) */
11518   FKey *pNextFrom;  /* Next FKey with the same in pFrom. Next parent of pFrom */
11519   char *zTo;        /* Name of table that the key points to (aka: Parent) */
11520   FKey *pNextTo;    /* Next with the same zTo. Next child of zTo. */
11521   FKey *pPrevTo;    /* Previous with the same zTo */
11522   int nCol;         /* Number of columns in this key */
11523   /* EV: R-30323-21917 */
11524   u8 isDeferred;       /* True if constraint checking is deferred till COMMIT */
11525   u8 aAction[2];        /* ON DELETE and ON UPDATE actions, respectively */
11526   Trigger *apTrigger[2];/* Triggers for aAction[] actions */
11527   struct sColMap {      /* Mapping of columns in pFrom to columns in zTo */
11528     int iFrom;            /* Index of column in pFrom */
11529     char *zCol;           /* Name of column in zTo.  If NULL use PRIMARY KEY */
11530   } aCol[1];            /* One entry for each of nCol columns */
11531 };
11532
11533 /*
11534 ** SQLite supports many different ways to resolve a constraint
11535 ** error.  ROLLBACK processing means that a constraint violation
11536 ** causes the operation in process to fail and for the current transaction
11537 ** to be rolled back.  ABORT processing means the operation in process
11538 ** fails and any prior changes from that one operation are backed out,
11539 ** but the transaction is not rolled back.  FAIL processing means that
11540 ** the operation in progress stops and returns an error code.  But prior
11541 ** changes due to the same operation are not backed out and no rollback
11542 ** occurs.  IGNORE means that the particular row that caused the constraint
11543 ** error is not inserted or updated.  Processing continues and no error
11544 ** is returned.  REPLACE means that preexisting database rows that caused
11545 ** a UNIQUE constraint violation are removed so that the new insert or
11546 ** update can proceed.  Processing continues and no error is reported.
11547 **
11548 ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
11549 ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
11550 ** same as ROLLBACK for DEFERRED keys.  SETNULL means that the foreign
11551 ** key is set to NULL.  CASCADE means that a DELETE or UPDATE of the
11552 ** referenced table row is propagated into the row that holds the
11553 ** foreign key.
11554 ** 
11555 ** The following symbolic values are used to record which type
11556 ** of action to take.
11557 */
11558 #define OE_None     0   /* There is no constraint to check */
11559 #define OE_Rollback 1   /* Fail the operation and rollback the transaction */
11560 #define OE_Abort    2   /* Back out changes but do no rollback transaction */
11561 #define OE_Fail     3   /* Stop the operation but leave all prior changes */
11562 #define OE_Ignore   4   /* Ignore the error. Do not do the INSERT or UPDATE */
11563 #define OE_Replace  5   /* Delete existing record, then do INSERT or UPDATE */
11564
11565 #define OE_Restrict 6   /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
11566 #define OE_SetNull  7   /* Set the foreign key value to NULL */
11567 #define OE_SetDflt  8   /* Set the foreign key value to its default */
11568 #define OE_Cascade  9   /* Cascade the changes */
11569
11570 #define OE_Default  10  /* Do whatever the default action is */
11571
11572
11573 /*
11574 ** An instance of the following structure is passed as the first
11575 ** argument to sqlite3VdbeKeyCompare and is used to control the 
11576 ** comparison of the two index keys.
11577 **
11578 ** Note that aSortOrder[] and aColl[] have nField+1 slots.  There
11579 ** are nField slots for the columns of an index then one extra slot
11580 ** for the rowid at the end.
11581 */
11582 struct KeyInfo {
11583   u32 nRef;           /* Number of references to this KeyInfo object */
11584   u8 enc;             /* Text encoding - one of the SQLITE_UTF* values */
11585   u16 nField;         /* Number of key columns in the index */
11586   u16 nXField;        /* Number of columns beyond the key columns */
11587   sqlite3 *db;        /* The database connection */
11588   u8 *aSortOrder;     /* Sort order for each column. */
11589   CollSeq *aColl[1];  /* Collating sequence for each term of the key */
11590 };
11591
11592 /*
11593 ** An instance of the following structure holds information about a
11594 ** single index record that has already been parsed out into individual
11595 ** values.
11596 **
11597 ** A record is an object that contains one or more fields of data.
11598 ** Records are used to store the content of a table row and to store
11599 ** the key of an index.  A blob encoding of a record is created by
11600 ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
11601 ** OP_Column opcode.
11602 **
11603 ** This structure holds a record that has already been disassembled
11604 ** into its constituent fields.
11605 **
11606 ** The r1 and r2 member variables are only used by the optimized comparison
11607 ** functions vdbeRecordCompareInt() and vdbeRecordCompareString().
11608 */
11609 struct UnpackedRecord {
11610   KeyInfo *pKeyInfo;  /* Collation and sort-order information */
11611   u16 nField;         /* Number of entries in apMem[] */
11612   i8 default_rc;      /* Comparison result if keys are equal */
11613   u8 errCode;         /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
11614   Mem *aMem;          /* Values */
11615   int r1;             /* Value to return if (lhs > rhs) */
11616   int r2;             /* Value to return if (rhs < lhs) */
11617 };
11618
11619
11620 /*
11621 ** Each SQL index is represented in memory by an
11622 ** instance of the following structure.
11623 **
11624 ** The columns of the table that are to be indexed are described
11625 ** by the aiColumn[] field of this structure.  For example, suppose
11626 ** we have the following table and index:
11627 **
11628 **     CREATE TABLE Ex1(c1 int, c2 int, c3 text);
11629 **     CREATE INDEX Ex2 ON Ex1(c3,c1);
11630 **
11631 ** In the Table structure describing Ex1, nCol==3 because there are
11632 ** three columns in the table.  In the Index structure describing
11633 ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
11634 ** The value of aiColumn is {2, 0}.  aiColumn[0]==2 because the 
11635 ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
11636 ** The second column to be indexed (c1) has an index of 0 in
11637 ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
11638 **
11639 ** The Index.onError field determines whether or not the indexed columns
11640 ** must be unique and what to do if they are not.  When Index.onError=OE_None,
11641 ** it means this is not a unique index.  Otherwise it is a unique index
11642 ** and the value of Index.onError indicate the which conflict resolution 
11643 ** algorithm to employ whenever an attempt is made to insert a non-unique
11644 ** element.
11645 */
11646 struct Index {
11647   char *zName;             /* Name of this index */
11648   i16 *aiColumn;           /* Which columns are used by this index.  1st is 0 */
11649   LogEst *aiRowLogEst;     /* From ANALYZE: Est. rows selected by each column */
11650   Table *pTable;           /* The SQL table being indexed */
11651   char *zColAff;           /* String defining the affinity of each column */
11652   Index *pNext;            /* The next index associated with the same table */
11653   Schema *pSchema;         /* Schema containing this index */
11654   u8 *aSortOrder;          /* for each column: True==DESC, False==ASC */
11655   char **azColl;           /* Array of collation sequence names for index */
11656   Expr *pPartIdxWhere;     /* WHERE clause for partial indices */
11657   int tnum;                /* DB Page containing root of this index */
11658   LogEst szIdxRow;         /* Estimated average row size in bytes */
11659   u16 nKeyCol;             /* Number of columns forming the key */
11660   u16 nColumn;             /* Number of columns stored in the index */
11661   u8 onError;              /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
11662   unsigned idxType:2;      /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
11663   unsigned bUnordered:1;   /* Use this index for == or IN queries only */
11664   unsigned uniqNotNull:1;  /* True if UNIQUE and NOT NULL for all columns */
11665   unsigned isResized:1;    /* True if resizeIndexObject() has been called */
11666   unsigned isCovering:1;   /* True if this is a covering index */
11667   unsigned noSkipScan:1;   /* Do not try to use skip-scan if true */
11668 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
11669   int nSample;             /* Number of elements in aSample[] */
11670   int nSampleCol;          /* Size of IndexSample.anEq[] and so on */
11671   tRowcnt *aAvgEq;         /* Average nEq values for keys not in aSample */
11672   IndexSample *aSample;    /* Samples of the left-most key */
11673   tRowcnt *aiRowEst;       /* Non-logarithmic stat1 data for this index */
11674   tRowcnt nRowEst0;        /* Non-logarithmic number of rows in the index */
11675 #endif
11676 };
11677
11678 /*
11679 ** Allowed values for Index.idxType
11680 */
11681 #define SQLITE_IDXTYPE_APPDEF      0   /* Created using CREATE INDEX */
11682 #define SQLITE_IDXTYPE_UNIQUE      1   /* Implements a UNIQUE constraint */
11683 #define SQLITE_IDXTYPE_PRIMARYKEY  2   /* Is the PRIMARY KEY for the table */
11684
11685 /* Return true if index X is a PRIMARY KEY index */
11686 #define IsPrimaryKeyIndex(X)  ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
11687
11688 /* Return true if index X is a UNIQUE index */
11689 #define IsUniqueIndex(X)      ((X)->onError!=OE_None)
11690
11691 /*
11692 ** Each sample stored in the sqlite_stat3 table is represented in memory 
11693 ** using a structure of this type.  See documentation at the top of the
11694 ** analyze.c source file for additional information.
11695 */
11696 struct IndexSample {
11697   void *p;          /* Pointer to sampled record */
11698   int n;            /* Size of record in bytes */
11699   tRowcnt *anEq;    /* Est. number of rows where the key equals this sample */
11700   tRowcnt *anLt;    /* Est. number of rows where key is less than this sample */
11701   tRowcnt *anDLt;   /* Est. number of distinct keys less than this sample */
11702 };
11703
11704 /*
11705 ** Each token coming out of the lexer is an instance of
11706 ** this structure.  Tokens are also used as part of an expression.
11707 **
11708 ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
11709 ** may contain random values.  Do not make any assumptions about Token.dyn
11710 ** and Token.n when Token.z==0.
11711 */
11712 struct Token {
11713   const char *z;     /* Text of the token.  Not NULL-terminated! */
11714   unsigned int n;    /* Number of characters in this token */
11715 };
11716
11717 /*
11718 ** An instance of this structure contains information needed to generate
11719 ** code for a SELECT that contains aggregate functions.
11720 **
11721 ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
11722 ** pointer to this structure.  The Expr.iColumn field is the index in
11723 ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
11724 ** code for that node.
11725 **
11726 ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
11727 ** original Select structure that describes the SELECT statement.  These
11728 ** fields do not need to be freed when deallocating the AggInfo structure.
11729 */
11730 struct AggInfo {
11731   u8 directMode;          /* Direct rendering mode means take data directly
11732                           ** from source tables rather than from accumulators */
11733   u8 useSortingIdx;       /* In direct mode, reference the sorting index rather
11734                           ** than the source table */
11735   int sortingIdx;         /* Cursor number of the sorting index */
11736   int sortingIdxPTab;     /* Cursor number of pseudo-table */
11737   int nSortingColumn;     /* Number of columns in the sorting index */
11738   int mnReg, mxReg;       /* Range of registers allocated for aCol and aFunc */
11739   ExprList *pGroupBy;     /* The group by clause */
11740   struct AggInfo_col {    /* For each column used in source tables */
11741     Table *pTab;             /* Source table */
11742     int iTable;              /* Cursor number of the source table */
11743     int iColumn;             /* Column number within the source table */
11744     int iSorterColumn;       /* Column number in the sorting index */
11745     int iMem;                /* Memory location that acts as accumulator */
11746     Expr *pExpr;             /* The original expression */
11747   } *aCol;
11748   int nColumn;            /* Number of used entries in aCol[] */
11749   int nAccumulator;       /* Number of columns that show through to the output.
11750                           ** Additional columns are used only as parameters to
11751                           ** aggregate functions */
11752   struct AggInfo_func {   /* For each aggregate function */
11753     Expr *pExpr;             /* Expression encoding the function */
11754     FuncDef *pFunc;          /* The aggregate function implementation */
11755     int iMem;                /* Memory location that acts as accumulator */
11756     int iDistinct;           /* Ephemeral table used to enforce DISTINCT */
11757   } *aFunc;
11758   int nFunc;              /* Number of entries in aFunc[] */
11759 };
11760
11761 /*
11762 ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
11763 ** Usually it is 16-bits.  But if SQLITE_MAX_VARIABLE_NUMBER is greater
11764 ** than 32767 we have to make it 32-bit.  16-bit is preferred because
11765 ** it uses less memory in the Expr object, which is a big memory user
11766 ** in systems with lots of prepared statements.  And few applications
11767 ** need more than about 10 or 20 variables.  But some extreme users want
11768 ** to have prepared statements with over 32767 variables, and for them
11769 ** the option is available (at compile-time).
11770 */
11771 #if SQLITE_MAX_VARIABLE_NUMBER<=32767
11772 typedef i16 ynVar;
11773 #else
11774 typedef int ynVar;
11775 #endif
11776
11777 /*
11778 ** Each node of an expression in the parse tree is an instance
11779 ** of this structure.
11780 **
11781 ** Expr.op is the opcode. The integer parser token codes are reused
11782 ** as opcodes here. For example, the parser defines TK_GE to be an integer
11783 ** code representing the ">=" operator. This same integer code is reused
11784 ** to represent the greater-than-or-equal-to operator in the expression
11785 ** tree.
11786 **
11787 ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB, 
11788 ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
11789 ** the expression is a variable (TK_VARIABLE), then Expr.token contains the 
11790 ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
11791 ** then Expr.token contains the name of the function.
11792 **
11793 ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
11794 ** binary operator. Either or both may be NULL.
11795 **
11796 ** Expr.x.pList is a list of arguments if the expression is an SQL function,
11797 ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
11798 ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
11799 ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
11800 ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is 
11801 ** valid.
11802 **
11803 ** An expression of the form ID or ID.ID refers to a column in a table.
11804 ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
11805 ** the integer cursor number of a VDBE cursor pointing to that table and
11806 ** Expr.iColumn is the column number for the specific column.  If the
11807 ** expression is used as a result in an aggregate SELECT, then the
11808 ** value is also stored in the Expr.iAgg column in the aggregate so that
11809 ** it can be accessed after all aggregates are computed.
11810 **
11811 ** If the expression is an unbound variable marker (a question mark 
11812 ** character '?' in the original SQL) then the Expr.iTable holds the index 
11813 ** number for that variable.
11814 **
11815 ** If the expression is a subquery then Expr.iColumn holds an integer
11816 ** register number containing the result of the subquery.  If the
11817 ** subquery gives a constant result, then iTable is -1.  If the subquery
11818 ** gives a different answer at different times during statement processing
11819 ** then iTable is the address of a subroutine that computes the subquery.
11820 **
11821 ** If the Expr is of type OP_Column, and the table it is selecting from
11822 ** is a disk table or the "old.*" pseudo-table, then pTab points to the
11823 ** corresponding table definition.
11824 **
11825 ** ALLOCATION NOTES:
11826 **
11827 ** Expr objects can use a lot of memory space in database schema.  To
11828 ** help reduce memory requirements, sometimes an Expr object will be
11829 ** truncated.  And to reduce the number of memory allocations, sometimes
11830 ** two or more Expr objects will be stored in a single memory allocation,
11831 ** together with Expr.zToken strings.
11832 **
11833 ** If the EP_Reduced and EP_TokenOnly flags are set when
11834 ** an Expr object is truncated.  When EP_Reduced is set, then all
11835 ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
11836 ** are contained within the same memory allocation.  Note, however, that
11837 ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
11838 ** allocated, regardless of whether or not EP_Reduced is set.
11839 */
11840 struct Expr {
11841   u8 op;                 /* Operation performed by this node */
11842   char affinity;         /* The affinity of the column or 0 if not a column */
11843   u32 flags;             /* Various flags.  EP_* See below */
11844   union {
11845     char *zToken;          /* Token value. Zero terminated and dequoted */
11846     int iValue;            /* Non-negative integer value if EP_IntValue */
11847   } u;
11848
11849   /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
11850   ** space is allocated for the fields below this point. An attempt to
11851   ** access them will result in a segfault or malfunction. 
11852   *********************************************************************/
11853
11854   Expr *pLeft;           /* Left subnode */
11855   Expr *pRight;          /* Right subnode */
11856   union {
11857     ExprList *pList;     /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
11858     Select *pSelect;     /* EP_xIsSelect and op = IN, EXISTS, SELECT */
11859   } x;
11860
11861   /* If the EP_Reduced flag is set in the Expr.flags mask, then no
11862   ** space is allocated for the fields below this point. An attempt to
11863   ** access them will result in a segfault or malfunction.
11864   *********************************************************************/
11865
11866 #if SQLITE_MAX_EXPR_DEPTH>0
11867   int nHeight;           /* Height of the tree headed by this node */
11868 #endif
11869   int iTable;            /* TK_COLUMN: cursor number of table holding column
11870                          ** TK_REGISTER: register number
11871                          ** TK_TRIGGER: 1 -> new, 0 -> old
11872                          ** EP_Unlikely:  134217728 times likelihood */
11873   ynVar iColumn;         /* TK_COLUMN: column index.  -1 for rowid.
11874                          ** TK_VARIABLE: variable number (always >= 1). */
11875   i16 iAgg;              /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
11876   i16 iRightJoinTable;   /* If EP_FromJoin, the right table of the join */
11877   u8 op2;                /* TK_REGISTER: original value of Expr.op
11878                          ** TK_COLUMN: the value of p5 for OP_Column
11879                          ** TK_AGG_FUNCTION: nesting depth */
11880   AggInfo *pAggInfo;     /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
11881   Table *pTab;           /* Table for TK_COLUMN expressions. */
11882 };
11883
11884 /*
11885 ** The following are the meanings of bits in the Expr.flags field.
11886 */
11887 #define EP_FromJoin  0x000001 /* Originates in ON/USING clause of outer join */
11888 #define EP_Agg       0x000002 /* Contains one or more aggregate functions */
11889 #define EP_Resolved  0x000004 /* IDs have been resolved to COLUMNs */
11890 #define EP_Error     0x000008 /* Expression contains one or more errors */
11891 #define EP_Distinct  0x000010 /* Aggregate function with DISTINCT keyword */
11892 #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
11893 #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
11894 #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
11895 #define EP_Collate   0x000100 /* Tree contains a TK_COLLATE operator */
11896 #define EP_Generic   0x000200 /* Ignore COLLATE or affinity on this tree */
11897 #define EP_IntValue  0x000400 /* Integer value contained in u.iValue */
11898 #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
11899 #define EP_Skip      0x001000 /* COLLATE, AS, or UNLIKELY */
11900 #define EP_Reduced   0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
11901 #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
11902 #define EP_Static    0x008000 /* Held in memory not obtained from malloc() */
11903 #define EP_MemToken  0x010000 /* Need to sqlite3DbFree() Expr.zToken */
11904 #define EP_NoReduce  0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
11905 #define EP_Unlikely  0x040000 /* unlikely() or likelihood() function */
11906 #define EP_ConstFunc 0x080000 /* Node is a SQLITE_FUNC_CONSTANT function */
11907 #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
11908 #define EP_Subquery  0x200000 /* Tree contains a TK_SELECT operator */
11909
11910 /*
11911 ** Combinations of two or more EP_* flags
11912 */
11913 #define EP_Propagate (EP_Collate|EP_Subquery) /* Propagate these bits up tree */
11914
11915 /*
11916 ** These macros can be used to test, set, or clear bits in the 
11917 ** Expr.flags field.
11918 */
11919 #define ExprHasProperty(E,P)     (((E)->flags&(P))!=0)
11920 #define ExprHasAllProperty(E,P)  (((E)->flags&(P))==(P))
11921 #define ExprSetProperty(E,P)     (E)->flags|=(P)
11922 #define ExprClearProperty(E,P)   (E)->flags&=~(P)
11923
11924 /* The ExprSetVVAProperty() macro is used for Verification, Validation,
11925 ** and Accreditation only.  It works like ExprSetProperty() during VVA
11926 ** processes but is a no-op for delivery.
11927 */
11928 #ifdef SQLITE_DEBUG
11929 # define ExprSetVVAProperty(E,P)  (E)->flags|=(P)
11930 #else
11931 # define ExprSetVVAProperty(E,P)
11932 #endif
11933
11934 /*
11935 ** Macros to determine the number of bytes required by a normal Expr 
11936 ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags 
11937 ** and an Expr struct with the EP_TokenOnly flag set.
11938 */
11939 #define EXPR_FULLSIZE           sizeof(Expr)           /* Full size */
11940 #define EXPR_REDUCEDSIZE        offsetof(Expr,iTable)  /* Common features */
11941 #define EXPR_TOKENONLYSIZE      offsetof(Expr,pLeft)   /* Fewer features */
11942
11943 /*
11944 ** Flags passed to the sqlite3ExprDup() function. See the header comment 
11945 ** above sqlite3ExprDup() for details.
11946 */
11947 #define EXPRDUP_REDUCE         0x0001  /* Used reduced-size Expr nodes */
11948
11949 /*
11950 ** A list of expressions.  Each expression may optionally have a
11951 ** name.  An expr/name combination can be used in several ways, such
11952 ** as the list of "expr AS ID" fields following a "SELECT" or in the
11953 ** list of "ID = expr" items in an UPDATE.  A list of expressions can
11954 ** also be used as the argument to a function, in which case the a.zName
11955 ** field is not used.
11956 **
11957 ** By default the Expr.zSpan field holds a human-readable description of
11958 ** the expression that is used in the generation of error messages and
11959 ** column labels.  In this case, Expr.zSpan is typically the text of a
11960 ** column expression as it exists in a SELECT statement.  However, if
11961 ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
11962 ** of the result column in the form: DATABASE.TABLE.COLUMN.  This later
11963 ** form is used for name resolution with nested FROM clauses.
11964 */
11965 struct ExprList {
11966   int nExpr;             /* Number of expressions on the list */
11967   struct ExprList_item { /* For each expression in the list */
11968     Expr *pExpr;            /* The list of expressions */
11969     char *zName;            /* Token associated with this expression */
11970     char *zSpan;            /* Original text of the expression */
11971     u8 sortOrder;           /* 1 for DESC or 0 for ASC */
11972     unsigned done :1;       /* A flag to indicate when processing is finished */
11973     unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
11974     unsigned reusable :1;   /* Constant expression is reusable */
11975     union {
11976       struct {
11977         u16 iOrderByCol;      /* For ORDER BY, column number in result set */
11978         u16 iAlias;           /* Index into Parse.aAlias[] for zName */
11979       } x;
11980       int iConstExprReg;      /* Register in which Expr value is cached */
11981     } u;
11982   } *a;                  /* Alloc a power of two greater or equal to nExpr */
11983 };
11984
11985 /*
11986 ** An instance of this structure is used by the parser to record both
11987 ** the parse tree for an expression and the span of input text for an
11988 ** expression.
11989 */
11990 struct ExprSpan {
11991   Expr *pExpr;          /* The expression parse tree */
11992   const char *zStart;   /* First character of input text */
11993   const char *zEnd;     /* One character past the end of input text */
11994 };
11995
11996 /*
11997 ** An instance of this structure can hold a simple list of identifiers,
11998 ** such as the list "a,b,c" in the following statements:
11999 **
12000 **      INSERT INTO t(a,b,c) VALUES ...;
12001 **      CREATE INDEX idx ON t(a,b,c);
12002 **      CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
12003 **
12004 ** The IdList.a.idx field is used when the IdList represents the list of
12005 ** column names after a table name in an INSERT statement.  In the statement
12006 **
12007 **     INSERT INTO t(a,b,c) ...
12008 **
12009 ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
12010 */
12011 struct IdList {
12012   struct IdList_item {
12013     char *zName;      /* Name of the identifier */
12014     int idx;          /* Index in some Table.aCol[] of a column named zName */
12015   } *a;
12016   int nId;         /* Number of identifiers on the list */
12017 };
12018
12019 /*
12020 ** The bitmask datatype defined below is used for various optimizations.
12021 **
12022 ** Changing this from a 64-bit to a 32-bit type limits the number of
12023 ** tables in a join to 32 instead of 64.  But it also reduces the size
12024 ** of the library by 738 bytes on ix86.
12025 */
12026 typedef u64 Bitmask;
12027
12028 /*
12029 ** The number of bits in a Bitmask.  "BMS" means "BitMask Size".
12030 */
12031 #define BMS  ((int)(sizeof(Bitmask)*8))
12032
12033 /*
12034 ** A bit in a Bitmask
12035 */
12036 #define MASKBIT(n)   (((Bitmask)1)<<(n))
12037 #define MASKBIT32(n) (((unsigned int)1)<<(n))
12038
12039 /*
12040 ** The following structure describes the FROM clause of a SELECT statement.
12041 ** Each table or subquery in the FROM clause is a separate element of
12042 ** the SrcList.a[] array.
12043 **
12044 ** With the addition of multiple database support, the following structure
12045 ** can also be used to describe a particular table such as the table that
12046 ** is modified by an INSERT, DELETE, or UPDATE statement.  In standard SQL,
12047 ** such a table must be a simple name: ID.  But in SQLite, the table can
12048 ** now be identified by a database name, a dot, then the table name: ID.ID.
12049 **
12050 ** The jointype starts out showing the join type between the current table
12051 ** and the next table on the list.  The parser builds the list this way.
12052 ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
12053 ** jointype expresses the join between the table and the previous table.
12054 **
12055 ** In the colUsed field, the high-order bit (bit 63) is set if the table
12056 ** contains more than 63 columns and the 64-th or later column is used.
12057 */
12058 struct SrcList {
12059   int nSrc;        /* Number of tables or subqueries in the FROM clause */
12060   u32 nAlloc;      /* Number of entries allocated in a[] below */
12061   struct SrcList_item {
12062     Schema *pSchema;  /* Schema to which this item is fixed */
12063     char *zDatabase;  /* Name of database holding this table */
12064     char *zName;      /* Name of the table */
12065     char *zAlias;     /* The "B" part of a "A AS B" phrase.  zName is the "A" */
12066     Table *pTab;      /* An SQL table corresponding to zName */
12067     Select *pSelect;  /* A SELECT statement used in place of a table name */
12068     int addrFillSub;  /* Address of subroutine to manifest a subquery */
12069     int regReturn;    /* Register holding return address of addrFillSub */
12070     int regResult;    /* Registers holding results of a co-routine */
12071     u8 jointype;      /* Type of join between this able and the previous */
12072     unsigned notIndexed :1;    /* True if there is a NOT INDEXED clause */
12073     unsigned isCorrelated :1;  /* True if sub-query is correlated */
12074     unsigned viaCoroutine :1;  /* Implemented as a co-routine */
12075     unsigned isRecursive :1;   /* True for recursive reference in WITH */
12076 #ifndef SQLITE_OMIT_EXPLAIN
12077     u8 iSelectId;     /* If pSelect!=0, the id of the sub-select in EQP */
12078 #endif
12079     int iCursor;      /* The VDBE cursor number used to access this table */
12080     Expr *pOn;        /* The ON clause of a join */
12081     IdList *pUsing;   /* The USING clause of a join */
12082     Bitmask colUsed;  /* Bit N (1<<N) set if column N of pTab is used */
12083     char *zIndex;     /* Identifier from "INDEXED BY <zIndex>" clause */
12084     Index *pIndex;    /* Index structure corresponding to zIndex, if any */
12085   } a[1];             /* One entry for each identifier on the list */
12086 };
12087
12088 /*
12089 ** Permitted values of the SrcList.a.jointype field
12090 */
12091 #define JT_INNER     0x0001    /* Any kind of inner or cross join */
12092 #define JT_CROSS     0x0002    /* Explicit use of the CROSS keyword */
12093 #define JT_NATURAL   0x0004    /* True for a "natural" join */
12094 #define JT_LEFT      0x0008    /* Left outer join */
12095 #define JT_RIGHT     0x0010    /* Right outer join */
12096 #define JT_OUTER     0x0020    /* The "OUTER" keyword is present */
12097 #define JT_ERROR     0x0040    /* unknown or unsupported join type */
12098
12099
12100 /*
12101 ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
12102 ** and the WhereInfo.wctrlFlags member.
12103 */
12104 #define WHERE_ORDERBY_NORMAL   0x0000 /* No-op */
12105 #define WHERE_ORDERBY_MIN      0x0001 /* ORDER BY processing for min() func */
12106 #define WHERE_ORDERBY_MAX      0x0002 /* ORDER BY processing for max() func */
12107 #define WHERE_ONEPASS_DESIRED  0x0004 /* Want to do one-pass UPDATE/DELETE */
12108 #define WHERE_DUPLICATES_OK    0x0008 /* Ok to return a row more than once */
12109 #define WHERE_OMIT_OPEN_CLOSE  0x0010 /* Table cursors are already open */
12110 #define WHERE_FORCE_TABLE      0x0020 /* Do not use an index-only search */
12111 #define WHERE_ONETABLE_ONLY    0x0040 /* Only code the 1st table in pTabList */
12112 #define WHERE_NO_AUTOINDEX     0x0080 /* Disallow automatic indexes */
12113 #define WHERE_GROUPBY          0x0100 /* pOrderBy is really a GROUP BY */
12114 #define WHERE_DISTINCTBY       0x0200 /* pOrderby is really a DISTINCT clause */
12115 #define WHERE_WANT_DISTINCT    0x0400 /* All output needs to be distinct */
12116 #define WHERE_SORTBYGROUP      0x0800 /* Support sqlite3WhereIsSorted() */
12117 #define WHERE_REOPEN_IDX       0x1000 /* Try to use OP_ReopenIdx */
12118
12119 /* Allowed return values from sqlite3WhereIsDistinct()
12120 */
12121 #define WHERE_DISTINCT_NOOP      0  /* DISTINCT keyword not used */
12122 #define WHERE_DISTINCT_UNIQUE    1  /* No duplicates */
12123 #define WHERE_DISTINCT_ORDERED   2  /* All duplicates are adjacent */
12124 #define WHERE_DISTINCT_UNORDERED 3  /* Duplicates are scattered */
12125
12126 /*
12127 ** A NameContext defines a context in which to resolve table and column
12128 ** names.  The context consists of a list of tables (the pSrcList) field and
12129 ** a list of named expression (pEList).  The named expression list may
12130 ** be NULL.  The pSrc corresponds to the FROM clause of a SELECT or
12131 ** to the table being operated on by INSERT, UPDATE, or DELETE.  The
12132 ** pEList corresponds to the result set of a SELECT and is NULL for
12133 ** other statements.
12134 **
12135 ** NameContexts can be nested.  When resolving names, the inner-most 
12136 ** context is searched first.  If no match is found, the next outer
12137 ** context is checked.  If there is still no match, the next context
12138 ** is checked.  This process continues until either a match is found
12139 ** or all contexts are check.  When a match is found, the nRef member of
12140 ** the context containing the match is incremented. 
12141 **
12142 ** Each subquery gets a new NameContext.  The pNext field points to the
12143 ** NameContext in the parent query.  Thus the process of scanning the
12144 ** NameContext list corresponds to searching through successively outer
12145 ** subqueries looking for a match.
12146 */
12147 struct NameContext {
12148   Parse *pParse;       /* The parser */
12149   SrcList *pSrcList;   /* One or more tables used to resolve names */
12150   ExprList *pEList;    /* Optional list of result-set columns */
12151   AggInfo *pAggInfo;   /* Information about aggregates at this level */
12152   NameContext *pNext;  /* Next outer name context.  NULL for outermost */
12153   int nRef;            /* Number of names resolved by this context */
12154   int nErr;            /* Number of errors encountered while resolving names */
12155   u16 ncFlags;         /* Zero or more NC_* flags defined below */
12156 };
12157
12158 /*
12159 ** Allowed values for the NameContext, ncFlags field.
12160 **
12161 ** Note:  NC_MinMaxAgg must have the same value as SF_MinMaxAgg and
12162 ** SQLITE_FUNC_MINMAX.
12163 ** 
12164 */
12165 #define NC_AllowAgg  0x0001  /* Aggregate functions are allowed here */
12166 #define NC_HasAgg    0x0002  /* One or more aggregate functions seen */
12167 #define NC_IsCheck   0x0004  /* True if resolving names in a CHECK constraint */
12168 #define NC_InAggFunc 0x0008  /* True if analyzing arguments to an agg func */
12169 #define NC_PartIdx   0x0010  /* True if resolving a partial index WHERE */
12170 #define NC_MinMaxAgg 0x1000  /* min/max aggregates seen.  See note above */
12171
12172 /*
12173 ** An instance of the following structure contains all information
12174 ** needed to generate code for a single SELECT statement.
12175 **
12176 ** nLimit is set to -1 if there is no LIMIT clause.  nOffset is set to 0.
12177 ** If there is a LIMIT clause, the parser sets nLimit to the value of the
12178 ** limit and nOffset to the value of the offset (or 0 if there is not
12179 ** offset).  But later on, nLimit and nOffset become the memory locations
12180 ** in the VDBE that record the limit and offset counters.
12181 **
12182 ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
12183 ** These addresses must be stored so that we can go back and fill in
12184 ** the P4_KEYINFO and P2 parameters later.  Neither the KeyInfo nor
12185 ** the number of columns in P2 can be computed at the same time
12186 ** as the OP_OpenEphm instruction is coded because not
12187 ** enough information about the compound query is known at that point.
12188 ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
12189 ** for the result set.  The KeyInfo for addrOpenEphm[2] contains collating
12190 ** sequences for the ORDER BY clause.
12191 */
12192 struct Select {
12193   ExprList *pEList;      /* The fields of the result */
12194   u8 op;                 /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
12195   u16 selFlags;          /* Various SF_* values */
12196   int iLimit, iOffset;   /* Memory registers holding LIMIT & OFFSET counters */
12197 #if SELECTTRACE_ENABLED
12198   char zSelName[12];     /* Symbolic name of this SELECT use for debugging */
12199 #endif
12200   int addrOpenEphm[2];   /* OP_OpenEphem opcodes related to this select */
12201   u64 nSelectRow;        /* Estimated number of result rows */
12202   SrcList *pSrc;         /* The FROM clause */
12203   Expr *pWhere;          /* The WHERE clause */
12204   ExprList *pGroupBy;    /* The GROUP BY clause */
12205   Expr *pHaving;         /* The HAVING clause */
12206   ExprList *pOrderBy;    /* The ORDER BY clause */
12207   Select *pPrior;        /* Prior select in a compound select statement */
12208   Select *pNext;         /* Next select to the left in a compound */
12209   Expr *pLimit;          /* LIMIT expression. NULL means not used. */
12210   Expr *pOffset;         /* OFFSET expression. NULL means not used. */
12211   With *pWith;           /* WITH clause attached to this select. Or NULL. */
12212 };
12213
12214 /*
12215 ** Allowed values for Select.selFlags.  The "SF" prefix stands for
12216 ** "Select Flag".
12217 */
12218 #define SF_Distinct        0x0001  /* Output should be DISTINCT */
12219 #define SF_Resolved        0x0002  /* Identifiers have been resolved */
12220 #define SF_Aggregate       0x0004  /* Contains aggregate functions */
12221 #define SF_UsesEphemeral   0x0008  /* Uses the OpenEphemeral opcode */
12222 #define SF_Expanded        0x0010  /* sqlite3SelectExpand() called on this */
12223 #define SF_HasTypeInfo     0x0020  /* FROM subqueries have Table metadata */
12224 #define SF_Compound        0x0040  /* Part of a compound query */
12225 #define SF_Values          0x0080  /* Synthesized from VALUES clause */
12226 #define SF_AllValues       0x0100  /* All terms of compound are VALUES */
12227 #define SF_NestedFrom      0x0200  /* Part of a parenthesized FROM clause */
12228 #define SF_MaybeConvert    0x0400  /* Need convertCompoundSelectToSubquery() */
12229 #define SF_Recursive       0x0800  /* The recursive part of a recursive CTE */
12230 #define SF_MinMaxAgg       0x1000  /* Aggregate containing min() or max() */
12231 #define SF_Converted       0x2000  /* By convertCompoundSelectToSubquery() */
12232
12233
12234 /*
12235 ** The results of a SELECT can be distributed in several ways, as defined
12236 ** by one of the following macros.  The "SRT" prefix means "SELECT Result
12237 ** Type".
12238 **
12239 **     SRT_Union       Store results as a key in a temporary index 
12240 **                     identified by pDest->iSDParm.
12241 **
12242 **     SRT_Except      Remove results from the temporary index pDest->iSDParm.
12243 **
12244 **     SRT_Exists      Store a 1 in memory cell pDest->iSDParm if the result
12245 **                     set is not empty.
12246 **
12247 **     SRT_Discard     Throw the results away.  This is used by SELECT
12248 **                     statements within triggers whose only purpose is
12249 **                     the side-effects of functions.
12250 **
12251 ** All of the above are free to ignore their ORDER BY clause. Those that
12252 ** follow must honor the ORDER BY clause.
12253 **
12254 **     SRT_Output      Generate a row of output (using the OP_ResultRow
12255 **                     opcode) for each row in the result set.
12256 **
12257 **     SRT_Mem         Only valid if the result is a single column.
12258 **                     Store the first column of the first result row
12259 **                     in register pDest->iSDParm then abandon the rest
12260 **                     of the query.  This destination implies "LIMIT 1".
12261 **
12262 **     SRT_Set         The result must be a single column.  Store each
12263 **                     row of result as the key in table pDest->iSDParm. 
12264 **                     Apply the affinity pDest->affSdst before storing
12265 **                     results.  Used to implement "IN (SELECT ...)".
12266 **
12267 **     SRT_EphemTab    Create an temporary table pDest->iSDParm and store
12268 **                     the result there. The cursor is left open after
12269 **                     returning.  This is like SRT_Table except that
12270 **                     this destination uses OP_OpenEphemeral to create
12271 **                     the table first.
12272 **
12273 **     SRT_Coroutine   Generate a co-routine that returns a new row of
12274 **                     results each time it is invoked.  The entry point
12275 **                     of the co-routine is stored in register pDest->iSDParm
12276 **                     and the result row is stored in pDest->nDest registers
12277 **                     starting with pDest->iSdst.
12278 **
12279 **     SRT_Table       Store results in temporary table pDest->iSDParm.
12280 **     SRT_Fifo        This is like SRT_EphemTab except that the table
12281 **                     is assumed to already be open.  SRT_Fifo has
12282 **                     the additional property of being able to ignore
12283 **                     the ORDER BY clause.
12284 **
12285 **     SRT_DistFifo    Store results in a temporary table pDest->iSDParm.
12286 **                     But also use temporary table pDest->iSDParm+1 as
12287 **                     a record of all prior results and ignore any duplicate
12288 **                     rows.  Name means:  "Distinct Fifo".
12289 **
12290 **     SRT_Queue       Store results in priority queue pDest->iSDParm (really
12291 **                     an index).  Append a sequence number so that all entries
12292 **                     are distinct.
12293 **
12294 **     SRT_DistQueue   Store results in priority queue pDest->iSDParm only if
12295 **                     the same record has never been stored before.  The
12296 **                     index at pDest->iSDParm+1 hold all prior stores.
12297 */
12298 #define SRT_Union        1  /* Store result as keys in an index */
12299 #define SRT_Except       2  /* Remove result from a UNION index */
12300 #define SRT_Exists       3  /* Store 1 if the result is not empty */
12301 #define SRT_Discard      4  /* Do not save the results anywhere */
12302 #define SRT_Fifo         5  /* Store result as data with an automatic rowid */
12303 #define SRT_DistFifo     6  /* Like SRT_Fifo, but unique results only */
12304 #define SRT_Queue        7  /* Store result in an queue */
12305 #define SRT_DistQueue    8  /* Like SRT_Queue, but unique results only */
12306
12307 /* The ORDER BY clause is ignored for all of the above */
12308 #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
12309
12310 #define SRT_Output       9  /* Output each row of result */
12311 #define SRT_Mem         10  /* Store result in a memory cell */
12312 #define SRT_Set         11  /* Store results as keys in an index */
12313 #define SRT_EphemTab    12  /* Create transient tab and store like SRT_Table */
12314 #define SRT_Coroutine   13  /* Generate a single row of result */
12315 #define SRT_Table       14  /* Store result as data with an automatic rowid */
12316
12317 /*
12318 ** An instance of this object describes where to put of the results of
12319 ** a SELECT statement.
12320 */
12321 struct SelectDest {
12322   u8 eDest;            /* How to dispose of the results.  On of SRT_* above. */
12323   char affSdst;        /* Affinity used when eDest==SRT_Set */
12324   int iSDParm;         /* A parameter used by the eDest disposal method */
12325   int iSdst;           /* Base register where results are written */
12326   int nSdst;           /* Number of registers allocated */
12327   ExprList *pOrderBy;  /* Key columns for SRT_Queue and SRT_DistQueue */
12328 };
12329
12330 /*
12331 ** During code generation of statements that do inserts into AUTOINCREMENT 
12332 ** tables, the following information is attached to the Table.u.autoInc.p
12333 ** pointer of each autoincrement table to record some side information that
12334 ** the code generator needs.  We have to keep per-table autoincrement
12335 ** information in case inserts are down within triggers.  Triggers do not
12336 ** normally coordinate their activities, but we do need to coordinate the
12337 ** loading and saving of autoincrement information.
12338 */
12339 struct AutoincInfo {
12340   AutoincInfo *pNext;   /* Next info block in a list of them all */
12341   Table *pTab;          /* Table this info block refers to */
12342   int iDb;              /* Index in sqlite3.aDb[] of database holding pTab */
12343   int regCtr;           /* Memory register holding the rowid counter */
12344 };
12345
12346 /*
12347 ** Size of the column cache
12348 */
12349 #ifndef SQLITE_N_COLCACHE
12350 # define SQLITE_N_COLCACHE 10
12351 #endif
12352
12353 /*
12354 ** At least one instance of the following structure is created for each 
12355 ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
12356 ** statement. All such objects are stored in the linked list headed at
12357 ** Parse.pTriggerPrg and deleted once statement compilation has been
12358 ** completed.
12359 **
12360 ** A Vdbe sub-program that implements the body and WHEN clause of trigger
12361 ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
12362 ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
12363 ** The Parse.pTriggerPrg list never contains two entries with the same
12364 ** values for both pTrigger and orconf.
12365 **
12366 ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
12367 ** accessed (or set to 0 for triggers fired as a result of INSERT 
12368 ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
12369 ** a mask of new.* columns used by the program.
12370 */
12371 struct TriggerPrg {
12372   Trigger *pTrigger;      /* Trigger this program was coded from */
12373   TriggerPrg *pNext;      /* Next entry in Parse.pTriggerPrg list */
12374   SubProgram *pProgram;   /* Program implementing pTrigger/orconf */
12375   int orconf;             /* Default ON CONFLICT policy */
12376   u32 aColmask[2];        /* Masks of old.*, new.* columns accessed */
12377 };
12378
12379 /*
12380 ** The yDbMask datatype for the bitmask of all attached databases.
12381 */
12382 #if SQLITE_MAX_ATTACHED>30
12383   typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
12384 # define DbMaskTest(M,I)    (((M)[(I)/8]&(1<<((I)&7)))!=0)
12385 # define DbMaskZero(M)      memset((M),0,sizeof(M))
12386 # define DbMaskSet(M,I)     (M)[(I)/8]|=(1<<((I)&7))
12387 # define DbMaskAllZero(M)   sqlite3DbMaskAllZero(M)
12388 # define DbMaskNonZero(M)   (sqlite3DbMaskAllZero(M)==0)
12389 #else
12390   typedef unsigned int yDbMask;
12391 # define DbMaskTest(M,I)    (((M)&(((yDbMask)1)<<(I)))!=0)
12392 # define DbMaskZero(M)      (M)=0
12393 # define DbMaskSet(M,I)     (M)|=(((yDbMask)1)<<(I))
12394 # define DbMaskAllZero(M)   (M)==0
12395 # define DbMaskNonZero(M)   (M)!=0
12396 #endif
12397
12398 /*
12399 ** An SQL parser context.  A copy of this structure is passed through
12400 ** the parser and down into all the parser action routine in order to
12401 ** carry around information that is global to the entire parse.
12402 **
12403 ** The structure is divided into two parts.  When the parser and code
12404 ** generate call themselves recursively, the first part of the structure
12405 ** is constant but the second part is reset at the beginning and end of
12406 ** each recursion.
12407 **
12408 ** The nTableLock and aTableLock variables are only used if the shared-cache 
12409 ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
12410 ** used to store the set of table-locks required by the statement being
12411 ** compiled. Function sqlite3TableLock() is used to add entries to the
12412 ** list.
12413 */
12414 struct Parse {
12415   sqlite3 *db;         /* The main database structure */
12416   char *zErrMsg;       /* An error message */
12417   Vdbe *pVdbe;         /* An engine for executing database bytecode */
12418   int rc;              /* Return code from execution */
12419   u8 colNamesSet;      /* TRUE after OP_ColumnName has been issued to pVdbe */
12420   u8 checkSchema;      /* Causes schema cookie check after an error */
12421   u8 nested;           /* Number of nested calls to the parser/code generator */
12422   u8 nTempReg;         /* Number of temporary registers in aTempReg[] */
12423   u8 isMultiWrite;     /* True if statement may modify/insert multiple rows */
12424   u8 mayAbort;         /* True if statement may throw an ABORT exception */
12425   u8 hasCompound;      /* Need to invoke convertCompoundSelectToSubquery() */
12426   u8 okConstFactor;    /* OK to factor out constants */
12427   int aTempReg[8];     /* Holding area for temporary registers */
12428   int nRangeReg;       /* Size of the temporary register block */
12429   int iRangeReg;       /* First register in temporary register block */
12430   int nErr;            /* Number of errors seen */
12431   int nTab;            /* Number of previously allocated VDBE cursors */
12432   int nMem;            /* Number of memory cells used so far */
12433   int nSet;            /* Number of sets used so far */
12434   int nOnce;           /* Number of OP_Once instructions so far */
12435   int nOpAlloc;        /* Number of slots allocated for Vdbe.aOp[] */
12436   int iFixedOp;        /* Never back out opcodes iFixedOp-1 or earlier */
12437   int ckBase;          /* Base register of data during check constraints */
12438   int iPartIdxTab;     /* Table corresponding to a partial index */
12439   int iCacheLevel;     /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
12440   int iCacheCnt;       /* Counter used to generate aColCache[].lru values */
12441   int nLabel;          /* Number of labels used */
12442   int *aLabel;         /* Space to hold the labels */
12443   struct yColCache {
12444     int iTable;           /* Table cursor number */
12445     i16 iColumn;          /* Table column number */
12446     u8 tempReg;           /* iReg is a temp register that needs to be freed */
12447     int iLevel;           /* Nesting level */
12448     int iReg;             /* Reg with value of this column. 0 means none. */
12449     int lru;              /* Least recently used entry has the smallest value */
12450   } aColCache[SQLITE_N_COLCACHE];  /* One for each column cache entry */
12451   ExprList *pConstExpr;/* Constant expressions */
12452   Token constraintName;/* Name of the constraint currently being parsed */
12453   yDbMask writeMask;   /* Start a write transaction on these databases */
12454   yDbMask cookieMask;  /* Bitmask of schema verified databases */
12455   int cookieValue[SQLITE_MAX_ATTACHED+2];  /* Values of cookies to verify */
12456   int regRowid;        /* Register holding rowid of CREATE TABLE entry */
12457   int regRoot;         /* Register holding root page number for new objects */
12458   int nMaxArg;         /* Max args passed to user function by sub-program */
12459 #if SELECTTRACE_ENABLED
12460   int nSelect;         /* Number of SELECT statements seen */
12461   int nSelectIndent;   /* How far to indent SELECTTRACE() output */
12462 #endif
12463 #ifndef SQLITE_OMIT_SHARED_CACHE
12464   int nTableLock;        /* Number of locks in aTableLock */
12465   TableLock *aTableLock; /* Required table locks for shared-cache mode */
12466 #endif
12467   AutoincInfo *pAinc;  /* Information about AUTOINCREMENT counters */
12468
12469   /* Information used while coding trigger programs. */
12470   Parse *pToplevel;    /* Parse structure for main program (or NULL) */
12471   Table *pTriggerTab;  /* Table triggers are being coded for */
12472   int addrCrTab;       /* Address of OP_CreateTable opcode on CREATE TABLE */
12473   int addrSkipPK;      /* Address of instruction to skip PRIMARY KEY index */
12474   u32 nQueryLoop;      /* Est number of iterations of a query (10*log2(N)) */
12475   u32 oldmask;         /* Mask of old.* columns referenced */
12476   u32 newmask;         /* Mask of new.* columns referenced */
12477   u8 eTriggerOp;       /* TK_UPDATE, TK_INSERT or TK_DELETE */
12478   u8 eOrconf;          /* Default ON CONFLICT policy for trigger steps */
12479   u8 disableTriggers;  /* True to disable triggers */
12480
12481   /************************************************************************
12482   ** Above is constant between recursions.  Below is reset before and after
12483   ** each recursion.  The boundary between these two regions is determined
12484   ** using offsetof(Parse,nVar) so the nVar field must be the first field
12485   ** in the recursive region.
12486   ************************************************************************/
12487
12488   int nVar;                 /* Number of '?' variables seen in the SQL so far */
12489   int nzVar;                /* Number of available slots in azVar[] */
12490   u8 iPkSortOrder;          /* ASC or DESC for INTEGER PRIMARY KEY */
12491   u8 bFreeWith;             /* True if pWith should be freed with parser */
12492   u8 explain;               /* True if the EXPLAIN flag is found on the query */
12493 #ifndef SQLITE_OMIT_VIRTUALTABLE
12494   u8 declareVtab;           /* True if inside sqlite3_declare_vtab() */
12495   int nVtabLock;            /* Number of virtual tables to lock */
12496 #endif
12497   int nAlias;               /* Number of aliased result set columns */
12498   int nHeight;              /* Expression tree height of current sub-select */
12499 #ifndef SQLITE_OMIT_EXPLAIN
12500   int iSelectId;            /* ID of current select for EXPLAIN output */
12501   int iNextSelectId;        /* Next available select ID for EXPLAIN output */
12502 #endif
12503   char **azVar;             /* Pointers to names of parameters */
12504   Vdbe *pReprepare;         /* VM being reprepared (sqlite3Reprepare()) */
12505   const char *zTail;        /* All SQL text past the last semicolon parsed */
12506   Table *pNewTable;         /* A table being constructed by CREATE TABLE */
12507   Trigger *pNewTrigger;     /* Trigger under construct by a CREATE TRIGGER */
12508   const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
12509   Token sNameToken;         /* Token with unqualified schema object name */
12510   Token sLastToken;         /* The last token parsed */
12511 #ifndef SQLITE_OMIT_VIRTUALTABLE
12512   Token sArg;               /* Complete text of a module argument */
12513   Table **apVtabLock;       /* Pointer to virtual tables needing locking */
12514 #endif
12515   Table *pZombieTab;        /* List of Table objects to delete after code gen */
12516   TriggerPrg *pTriggerPrg;  /* Linked list of coded triggers */
12517   With *pWith;              /* Current WITH clause, or NULL */
12518 };
12519
12520 /*
12521 ** Return true if currently inside an sqlite3_declare_vtab() call.
12522 */
12523 #ifdef SQLITE_OMIT_VIRTUALTABLE
12524   #define IN_DECLARE_VTAB 0
12525 #else
12526   #define IN_DECLARE_VTAB (pParse->declareVtab)
12527 #endif
12528
12529 /*
12530 ** An instance of the following structure can be declared on a stack and used
12531 ** to save the Parse.zAuthContext value so that it can be restored later.
12532 */
12533 struct AuthContext {
12534   const char *zAuthContext;   /* Put saved Parse.zAuthContext here */
12535   Parse *pParse;              /* The Parse structure */
12536 };
12537
12538 /*
12539 ** Bitfield flags for P5 value in various opcodes.
12540 */
12541 #define OPFLAG_NCHANGE       0x01    /* Set to update db->nChange */
12542 #define OPFLAG_EPHEM         0x01    /* OP_Column: Ephemeral output is ok */
12543 #define OPFLAG_LASTROWID     0x02    /* Set to update db->lastRowid */
12544 #define OPFLAG_ISUPDATE      0x04    /* This OP_Insert is an sql UPDATE */
12545 #define OPFLAG_APPEND        0x08    /* This is likely to be an append */
12546 #define OPFLAG_USESEEKRESULT 0x10    /* Try to avoid a seek in BtreeInsert() */
12547 #define OPFLAG_LENGTHARG     0x40    /* OP_Column only used for length() */
12548 #define OPFLAG_TYPEOFARG     0x80    /* OP_Column only used for typeof() */
12549 #define OPFLAG_BULKCSR       0x01    /* OP_Open** used to open bulk cursor */
12550 #define OPFLAG_SEEKEQ        0x02    /* OP_Open** cursor uses EQ seek only */
12551 #define OPFLAG_P2ISREG       0x04    /* P2 to OP_Open** is a register number */
12552 #define OPFLAG_PERMUTE       0x01    /* OP_Compare: use the permutation */
12553
12554 /*
12555  * Each trigger present in the database schema is stored as an instance of
12556  * struct Trigger. 
12557  *
12558  * Pointers to instances of struct Trigger are stored in two ways.
12559  * 1. In the "trigHash" hash table (part of the sqlite3* that represents the 
12560  *    database). This allows Trigger structures to be retrieved by name.
12561  * 2. All triggers associated with a single table form a linked list, using the
12562  *    pNext member of struct Trigger. A pointer to the first element of the
12563  *    linked list is stored as the "pTrigger" member of the associated
12564  *    struct Table.
12565  *
12566  * The "step_list" member points to the first element of a linked list
12567  * containing the SQL statements specified as the trigger program.
12568  */
12569 struct Trigger {
12570   char *zName;            /* The name of the trigger                        */
12571   char *table;            /* The table or view to which the trigger applies */
12572   u8 op;                  /* One of TK_DELETE, TK_UPDATE, TK_INSERT         */
12573   u8 tr_tm;               /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
12574   Expr *pWhen;            /* The WHEN clause of the expression (may be NULL) */
12575   IdList *pColumns;       /* If this is an UPDATE OF <column-list> trigger,
12576                              the <column-list> is stored here */
12577   Schema *pSchema;        /* Schema containing the trigger */
12578   Schema *pTabSchema;     /* Schema containing the table */
12579   TriggerStep *step_list; /* Link list of trigger program steps             */
12580   Trigger *pNext;         /* Next trigger associated with the table */
12581 };
12582
12583 /*
12584 ** A trigger is either a BEFORE or an AFTER trigger.  The following constants
12585 ** determine which. 
12586 **
12587 ** If there are multiple triggers, you might of some BEFORE and some AFTER.
12588 ** In that cases, the constants below can be ORed together.
12589 */
12590 #define TRIGGER_BEFORE  1
12591 #define TRIGGER_AFTER   2
12592
12593 /*
12594  * An instance of struct TriggerStep is used to store a single SQL statement
12595  * that is a part of a trigger-program. 
12596  *
12597  * Instances of struct TriggerStep are stored in a singly linked list (linked
12598  * using the "pNext" member) referenced by the "step_list" member of the 
12599  * associated struct Trigger instance. The first element of the linked list is
12600  * the first step of the trigger-program.
12601  * 
12602  * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
12603  * "SELECT" statement. The meanings of the other members is determined by the 
12604  * value of "op" as follows:
12605  *
12606  * (op == TK_INSERT)
12607  * orconf    -> stores the ON CONFLICT algorithm
12608  * pSelect   -> If this is an INSERT INTO ... SELECT ... statement, then
12609  *              this stores a pointer to the SELECT statement. Otherwise NULL.
12610  * target    -> A token holding the quoted name of the table to insert into.
12611  * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
12612  *              this stores values to be inserted. Otherwise NULL.
12613  * pIdList   -> If this is an INSERT INTO ... (<column-names>) VALUES ... 
12614  *              statement, then this stores the column-names to be
12615  *              inserted into.
12616  *
12617  * (op == TK_DELETE)
12618  * target    -> A token holding the quoted name of the table to delete from.
12619  * pWhere    -> The WHERE clause of the DELETE statement if one is specified.
12620  *              Otherwise NULL.
12621  * 
12622  * (op == TK_UPDATE)
12623  * target    -> A token holding the quoted name of the table to update rows of.
12624  * pWhere    -> The WHERE clause of the UPDATE statement if one is specified.
12625  *              Otherwise NULL.
12626  * pExprList -> A list of the columns to update and the expressions to update
12627  *              them to. See sqlite3Update() documentation of "pChanges"
12628  *              argument.
12629  * 
12630  */
12631 struct TriggerStep {
12632   u8 op;               /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
12633   u8 orconf;           /* OE_Rollback etc. */
12634   Trigger *pTrig;      /* The trigger that this step is a part of */
12635   Select *pSelect;     /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
12636   Token target;        /* Target table for DELETE, UPDATE, INSERT */
12637   Expr *pWhere;        /* The WHERE clause for DELETE or UPDATE steps */
12638   ExprList *pExprList; /* SET clause for UPDATE. */
12639   IdList *pIdList;     /* Column names for INSERT */
12640   TriggerStep *pNext;  /* Next in the link-list */
12641   TriggerStep *pLast;  /* Last element in link-list. Valid for 1st elem only */
12642 };
12643
12644 /*
12645 ** The following structure contains information used by the sqliteFix...
12646 ** routines as they walk the parse tree to make database references
12647 ** explicit.  
12648 */
12649 typedef struct DbFixer DbFixer;
12650 struct DbFixer {
12651   Parse *pParse;      /* The parsing context.  Error messages written here */
12652   Schema *pSchema;    /* Fix items to this schema */
12653   int bVarOnly;       /* Check for variable references only */
12654   const char *zDb;    /* Make sure all objects are contained in this database */
12655   const char *zType;  /* Type of the container - used for error messages */
12656   const Token *pName; /* Name of the container - used for error messages */
12657 };
12658
12659 /*
12660 ** An objected used to accumulate the text of a string where we
12661 ** do not necessarily know how big the string will be in the end.
12662 */
12663 struct StrAccum {
12664   sqlite3 *db;         /* Optional database for lookaside.  Can be NULL */
12665   char *zBase;         /* A base allocation.  Not from malloc. */
12666   char *zText;         /* The string collected so far */
12667   int  nChar;          /* Length of the string so far */
12668   int  nAlloc;         /* Amount of space allocated in zText */
12669   int  mxAlloc;        /* Maximum allowed string length */
12670   u8   useMalloc;      /* 0: none,  1: sqlite3DbMalloc,  2: sqlite3_malloc */
12671   u8   accError;       /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
12672 };
12673 #define STRACCUM_NOMEM   1
12674 #define STRACCUM_TOOBIG  2
12675
12676 /*
12677 ** A pointer to this structure is used to communicate information
12678 ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
12679 */
12680 typedef struct {
12681   sqlite3 *db;        /* The database being initialized */
12682   char **pzErrMsg;    /* Error message stored here */
12683   int iDb;            /* 0 for main database.  1 for TEMP, 2.. for ATTACHed */
12684   int rc;             /* Result code stored here */
12685 } InitData;
12686
12687 /*
12688 ** Structure containing global configuration data for the SQLite library.
12689 **
12690 ** This structure also contains some state information.
12691 */
12692 struct Sqlite3Config {
12693   int bMemstat;                     /* True to enable memory status */
12694   int bCoreMutex;                   /* True to enable core mutexing */
12695   int bFullMutex;                   /* True to enable full mutexing */
12696   int bOpenUri;                     /* True to interpret filenames as URIs */
12697   int bUseCis;                      /* Use covering indices for full-scans */
12698   int mxStrlen;                     /* Maximum string length */
12699   int neverCorrupt;                 /* Database is always well-formed */
12700   int szLookaside;                  /* Default lookaside buffer size */
12701   int nLookaside;                   /* Default lookaside buffer count */
12702   sqlite3_mem_methods m;            /* Low-level memory allocation interface */
12703   sqlite3_mutex_methods mutex;      /* Low-level mutex interface */
12704   sqlite3_pcache_methods2 pcache2;  /* Low-level page-cache interface */
12705   void *pHeap;                      /* Heap storage space */
12706   int nHeap;                        /* Size of pHeap[] */
12707   int mnReq, mxReq;                 /* Min and max heap requests sizes */
12708   sqlite3_int64 szMmap;             /* mmap() space per open file */
12709   sqlite3_int64 mxMmap;             /* Maximum value for szMmap */
12710   void *pScratch;                   /* Scratch memory */
12711   int szScratch;                    /* Size of each scratch buffer */
12712   int nScratch;                     /* Number of scratch buffers */
12713   void *pPage;                      /* Page cache memory */
12714   int szPage;                       /* Size of each page in pPage[] */
12715   int nPage;                        /* Number of pages in pPage[] */
12716   int mxParserStack;                /* maximum depth of the parser stack */
12717   int sharedCacheEnabled;           /* true if shared-cache mode enabled */
12718   u32 szPma;                        /* Maximum Sorter PMA size */
12719   /* The above might be initialized to non-zero.  The following need to always
12720   ** initially be zero, however. */
12721   int isInit;                       /* True after initialization has finished */
12722   int inProgress;                   /* True while initialization in progress */
12723   int isMutexInit;                  /* True after mutexes are initialized */
12724   int isMallocInit;                 /* True after malloc is initialized */
12725   int isPCacheInit;                 /* True after malloc is initialized */
12726   int nRefInitMutex;                /* Number of users of pInitMutex */
12727   sqlite3_mutex *pInitMutex;        /* Mutex used by sqlite3_initialize() */
12728   void (*xLog)(void*,int,const char*); /* Function for logging */
12729   void *pLogArg;                       /* First argument to xLog() */
12730 #ifdef SQLITE_ENABLE_SQLLOG
12731   void(*xSqllog)(void*,sqlite3*,const char*, int);
12732   void *pSqllogArg;
12733 #endif
12734 #ifdef SQLITE_VDBE_COVERAGE
12735   /* The following callback (if not NULL) is invoked on every VDBE branch
12736   ** operation.  Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
12737   */
12738   void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx);  /* Callback */
12739   void *pVdbeBranchArg;                                     /* 1st argument */
12740 #endif
12741 #ifndef SQLITE_OMIT_BUILTIN_TEST
12742   int (*xTestCallback)(int);        /* Invoked by sqlite3FaultSim() */
12743 #endif
12744   int bLocaltimeFault;              /* True to fail localtime() calls */
12745 };
12746
12747 /*
12748 ** This macro is used inside of assert() statements to indicate that
12749 ** the assert is only valid on a well-formed database.  Instead of:
12750 **
12751 **     assert( X );
12752 **
12753 ** One writes:
12754 **
12755 **     assert( X || CORRUPT_DB );
12756 **
12757 ** CORRUPT_DB is true during normal operation.  CORRUPT_DB does not indicate
12758 ** that the database is definitely corrupt, only that it might be corrupt.
12759 ** For most test cases, CORRUPT_DB is set to false using a special
12760 ** sqlite3_test_control().  This enables assert() statements to prove
12761 ** things that are always true for well-formed databases.
12762 */
12763 #define CORRUPT_DB  (sqlite3Config.neverCorrupt==0)
12764
12765 /*
12766 ** Context pointer passed down through the tree-walk.
12767 */
12768 struct Walker {
12769   int (*xExprCallback)(Walker*, Expr*);     /* Callback for expressions */
12770   int (*xSelectCallback)(Walker*,Select*);  /* Callback for SELECTs */
12771   void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
12772   Parse *pParse;                            /* Parser context.  */
12773   int walkerDepth;                          /* Number of subqueries */
12774   u8 eCode;                                 /* A small processing code */
12775   union {                                   /* Extra data for callback */
12776     NameContext *pNC;                          /* Naming context */
12777     int n;                                     /* A counter */
12778     int iCur;                                  /* A cursor number */
12779     SrcList *pSrcList;                         /* FROM clause */
12780     struct SrcCount *pSrcCount;                /* Counting column references */
12781   } u;
12782 };
12783
12784 /* Forward declarations */
12785 SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
12786 SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
12787 SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
12788 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
12789 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
12790
12791 /*
12792 ** Return code from the parse-tree walking primitives and their
12793 ** callbacks.
12794 */
12795 #define WRC_Continue    0   /* Continue down into children */
12796 #define WRC_Prune       1   /* Omit children but continue walking siblings */
12797 #define WRC_Abort       2   /* Abandon the tree walk */
12798
12799 /*
12800 ** An instance of this structure represents a set of one or more CTEs
12801 ** (common table expressions) created by a single WITH clause.
12802 */
12803 struct With {
12804   int nCte;                       /* Number of CTEs in the WITH clause */
12805   With *pOuter;                   /* Containing WITH clause, or NULL */
12806   struct Cte {                    /* For each CTE in the WITH clause.... */
12807     char *zName;                    /* Name of this CTE */
12808     ExprList *pCols;                /* List of explicit column names, or NULL */
12809     Select *pSelect;                /* The definition of this CTE */
12810     const char *zErr;               /* Error message for circular references */
12811   } a[1];
12812 };
12813
12814 #ifdef SQLITE_DEBUG
12815 /*
12816 ** An instance of the TreeView object is used for printing the content of
12817 ** data structures on sqlite3DebugPrintf() using a tree-like view.
12818 */
12819 struct TreeView {
12820   int iLevel;             /* Which level of the tree we are on */
12821   u8  bLine[100];         /* Draw vertical in column i if bLine[i] is true */
12822 };
12823 #endif /* SQLITE_DEBUG */
12824
12825 /*
12826 ** Assuming zIn points to the first byte of a UTF-8 character,
12827 ** advance zIn to point to the first byte of the next UTF-8 character.
12828 */
12829 #define SQLITE_SKIP_UTF8(zIn) {                        \
12830   if( (*(zIn++))>=0xc0 ){                              \
12831     while( (*zIn & 0xc0)==0x80 ){ zIn++; }             \
12832   }                                                    \
12833 }
12834
12835 /*
12836 ** The SQLITE_*_BKPT macros are substitutes for the error codes with
12837 ** the same name but without the _BKPT suffix.  These macros invoke
12838 ** routines that report the line-number on which the error originated
12839 ** using sqlite3_log().  The routines also provide a convenient place
12840 ** to set a debugger breakpoint.
12841 */
12842 SQLITE_PRIVATE int sqlite3CorruptError(int);
12843 SQLITE_PRIVATE int sqlite3MisuseError(int);
12844 SQLITE_PRIVATE int sqlite3CantopenError(int);
12845 #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
12846 #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
12847 #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
12848
12849
12850 /*
12851 ** FTS4 is really an extension for FTS3.  It is enabled using the
12852 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also call
12853 ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
12854 */
12855 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
12856 # define SQLITE_ENABLE_FTS3 1
12857 #endif
12858
12859 /*
12860 ** The ctype.h header is needed for non-ASCII systems.  It is also
12861 ** needed by FTS3 when FTS3 is included in the amalgamation.
12862 */
12863 #if !defined(SQLITE_ASCII) || \
12864     (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
12865 # include <ctype.h>
12866 #endif
12867
12868 /*
12869 ** The following macros mimic the standard library functions toupper(),
12870 ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
12871 ** sqlite versions only work for ASCII characters, regardless of locale.
12872 */
12873 #ifdef SQLITE_ASCII
12874 # define sqlite3Toupper(x)  ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
12875 # define sqlite3Isspace(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
12876 # define sqlite3Isalnum(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
12877 # define sqlite3Isalpha(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
12878 # define sqlite3Isdigit(x)   (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
12879 # define sqlite3Isxdigit(x)  (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
12880 # define sqlite3Tolower(x)   (sqlite3UpperToLower[(unsigned char)(x)])
12881 #else
12882 # define sqlite3Toupper(x)   toupper((unsigned char)(x))
12883 # define sqlite3Isspace(x)   isspace((unsigned char)(x))
12884 # define sqlite3Isalnum(x)   isalnum((unsigned char)(x))
12885 # define sqlite3Isalpha(x)   isalpha((unsigned char)(x))
12886 # define sqlite3Isdigit(x)   isdigit((unsigned char)(x))
12887 # define sqlite3Isxdigit(x)  isxdigit((unsigned char)(x))
12888 # define sqlite3Tolower(x)   tolower((unsigned char)(x))
12889 #endif
12890 SQLITE_PRIVATE int sqlite3IsIdChar(u8);
12891
12892 /*
12893 ** Internal function prototypes
12894 */
12895 #define sqlite3StrICmp sqlite3_stricmp
12896 SQLITE_PRIVATE int sqlite3Strlen30(const char*);
12897 #define sqlite3StrNICmp sqlite3_strnicmp
12898
12899 SQLITE_PRIVATE int sqlite3MallocInit(void);
12900 SQLITE_PRIVATE void sqlite3MallocEnd(void);
12901 SQLITE_PRIVATE void *sqlite3Malloc(u64);
12902 SQLITE_PRIVATE void *sqlite3MallocZero(u64);
12903 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
12904 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
12905 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
12906 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
12907 SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
12908 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
12909 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
12910 SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
12911 SQLITE_PRIVATE int sqlite3MallocSize(void*);
12912 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
12913 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
12914 SQLITE_PRIVATE void sqlite3ScratchFree(void*);
12915 SQLITE_PRIVATE void *sqlite3PageMalloc(int);
12916 SQLITE_PRIVATE void sqlite3PageFree(void*);
12917 SQLITE_PRIVATE void sqlite3MemSetDefault(void);
12918 SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
12919 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
12920
12921 /*
12922 ** On systems with ample stack space and that support alloca(), make
12923 ** use of alloca() to obtain space for large automatic objects.  By default,
12924 ** obtain space from malloc().
12925 **
12926 ** The alloca() routine never returns NULL.  This will cause code paths
12927 ** that deal with sqlite3StackAlloc() failures to be unreachable.
12928 */
12929 #ifdef SQLITE_USE_ALLOCA
12930 # define sqlite3StackAllocRaw(D,N)   alloca(N)
12931 # define sqlite3StackAllocZero(D,N)  memset(alloca(N), 0, N)
12932 # define sqlite3StackFree(D,P)       
12933 #else
12934 # define sqlite3StackAllocRaw(D,N)   sqlite3DbMallocRaw(D,N)
12935 # define sqlite3StackAllocZero(D,N)  sqlite3DbMallocZero(D,N)
12936 # define sqlite3StackFree(D,P)       sqlite3DbFree(D,P)
12937 #endif
12938
12939 #ifdef SQLITE_ENABLE_MEMSYS3
12940 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
12941 #endif
12942 #ifdef SQLITE_ENABLE_MEMSYS5
12943 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
12944 #endif
12945
12946
12947 #ifndef SQLITE_MUTEX_OMIT
12948 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
12949 SQLITE_PRIVATE   sqlite3_mutex_methods const *sqlite3NoopMutex(void);
12950 SQLITE_PRIVATE   sqlite3_mutex *sqlite3MutexAlloc(int);
12951 SQLITE_PRIVATE   int sqlite3MutexInit(void);
12952 SQLITE_PRIVATE   int sqlite3MutexEnd(void);
12953 #endif
12954
12955 SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int);
12956 SQLITE_PRIVATE void sqlite3StatusUp(int, int);
12957 SQLITE_PRIVATE void sqlite3StatusDown(int, int);
12958 SQLITE_PRIVATE void sqlite3StatusSet(int, int);
12959
12960 /* Access to mutexes used by sqlite3_status() */
12961 SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void);
12962 SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void);
12963
12964 #ifndef SQLITE_OMIT_FLOATING_POINT
12965 SQLITE_PRIVATE   int sqlite3IsNaN(double);
12966 #else
12967 # define sqlite3IsNaN(X)  0
12968 #endif
12969
12970 /*
12971 ** An instance of the following structure holds information about SQL
12972 ** functions arguments that are the parameters to the printf() function.
12973 */
12974 struct PrintfArguments {
12975   int nArg;                /* Total number of arguments */
12976   int nUsed;               /* Number of arguments used so far */
12977   sqlite3_value **apArg;   /* The argument values */
12978 };
12979
12980 #define SQLITE_PRINTF_INTERNAL 0x01
12981 #define SQLITE_PRINTF_SQLFUNC  0x02
12982 SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, u32, const char*, va_list);
12983 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, u32, const char*, ...);
12984 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
12985 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
12986 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
12987 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
12988 SQLITE_PRIVATE   void sqlite3DebugPrintf(const char*, ...);
12989 #endif
12990 #if defined(SQLITE_TEST)
12991 SQLITE_PRIVATE   void *sqlite3TestTextToPtr(const char*);
12992 #endif
12993
12994 #if defined(SQLITE_DEBUG)
12995 SQLITE_PRIVATE   TreeView *sqlite3TreeViewPush(TreeView*,u8);
12996 SQLITE_PRIVATE   void sqlite3TreeViewPop(TreeView*);
12997 SQLITE_PRIVATE   void sqlite3TreeViewLine(TreeView*, const char*, ...);
12998 SQLITE_PRIVATE   void sqlite3TreeViewItem(TreeView*, const char*, u8);
12999 SQLITE_PRIVATE   void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
13000 SQLITE_PRIVATE   void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
13001 SQLITE_PRIVATE   void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
13002 #endif
13003
13004
13005 SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
13006 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
13007 SQLITE_PRIVATE int sqlite3Dequote(char*);
13008 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
13009 SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
13010 SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
13011 SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
13012 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
13013 SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
13014 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
13015 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
13016 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
13017 SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
13018 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
13019 SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
13020 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
13021 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
13022 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
13023 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
13024 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
13025 SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
13026 SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
13027 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
13028 SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList*);
13029 SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
13030 SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
13031 SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
13032 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
13033 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
13034 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
13035 SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
13036 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
13037 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
13038 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
13039 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
13040 SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
13041 SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
13042 SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
13043 SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
13044 SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
13045 SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
13046 SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
13047 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
13048 SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
13049 SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
13050 SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
13051                     sqlite3_vfs**,char**,char **);
13052 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
13053 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
13054
13055 #ifdef SQLITE_OMIT_BUILTIN_TEST
13056 # define sqlite3FaultSim(X) SQLITE_OK
13057 #else
13058 SQLITE_PRIVATE   int sqlite3FaultSim(int);
13059 #endif
13060
13061 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
13062 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
13063 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
13064 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
13065 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
13066 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
13067 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
13068
13069 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
13070 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
13071 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
13072 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
13073 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
13074
13075 SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
13076
13077 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
13078 SQLITE_PRIVATE   int sqlite3ViewGetColumnNames(Parse*,Table*);
13079 #else
13080 # define sqlite3ViewGetColumnNames(A,B) 0
13081 #endif
13082
13083 #if SQLITE_MAX_ATTACHED>30
13084 SQLITE_PRIVATE   int sqlite3DbMaskAllZero(yDbMask);
13085 #endif
13086 SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
13087 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
13088 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
13089 #ifndef SQLITE_OMIT_AUTOINCREMENT
13090 SQLITE_PRIVATE   void sqlite3AutoincrementBegin(Parse *pParse);
13091 SQLITE_PRIVATE   void sqlite3AutoincrementEnd(Parse *pParse);
13092 #else
13093 # define sqlite3AutoincrementBegin(X)
13094 # define sqlite3AutoincrementEnd(X)
13095 #endif
13096 SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
13097 SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
13098 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
13099 SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
13100 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
13101 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
13102 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
13103                                       Token*, Select*, Expr*, IdList*);
13104 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
13105 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
13106 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
13107 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
13108 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
13109 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
13110 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
13111 SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
13112                           Expr*, int, int);
13113 SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
13114 SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
13115 SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
13116                          Expr*,ExprList*,u16,Expr*,Expr*);
13117 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
13118 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
13119 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
13120 SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
13121 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
13122 SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
13123 #endif
13124 SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
13125 SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
13126 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
13127 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
13128 SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
13129 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
13130 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
13131 SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
13132 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
13133 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
13134 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
13135 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
13136 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
13137 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
13138 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
13139 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
13140 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
13141 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
13142 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
13143 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
13144 SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
13145 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
13146 SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
13147 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
13148 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
13149 SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
13150 SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, u8);
13151 #define SQLITE_ECEL_DUP      0x01  /* Deep, not shallow copies */
13152 #define SQLITE_ECEL_FACTOR   0x02  /* Factor out constant terms */
13153 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
13154 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
13155 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
13156 SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
13157 SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
13158 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
13159 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
13160 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
13161 SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
13162 SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
13163 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
13164 SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
13165 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
13166 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
13167 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
13168 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
13169 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
13170 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
13171 SQLITE_PRIVATE void sqlite3PrngSaveState(void);
13172 SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
13173 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
13174 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
13175 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
13176 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
13177 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
13178 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
13179 SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
13180 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
13181 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
13182 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
13183 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
13184 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
13185 SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr*,int);
13186 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
13187 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
13188 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
13189 SQLITE_PRIVATE int sqlite3IsRowid(const char*);
13190 SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8);
13191 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*);
13192 SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
13193 SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
13194 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
13195                                      u8,u8,int,int*);
13196 SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
13197 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int, u8*, int*, int*);
13198 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
13199 SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
13200 SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
13201 SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
13202 SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
13203 SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
13204 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
13205 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
13206 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
13207 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
13208 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
13209 #if SELECTTRACE_ENABLED
13210 SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
13211 #else
13212 # define sqlite3SelectSetName(A,B)
13213 #endif
13214 SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
13215 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
13216 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
13217 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
13218 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
13219 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
13220 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
13221 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
13222
13223 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
13224 SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
13225 #endif
13226
13227 #ifndef SQLITE_OMIT_TRIGGER
13228 SQLITE_PRIVATE   void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
13229                            Expr*,int, int);
13230 SQLITE_PRIVATE   void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
13231 SQLITE_PRIVATE   void sqlite3DropTrigger(Parse*, SrcList*, int);
13232 SQLITE_PRIVATE   void sqlite3DropTriggerPtr(Parse*, Trigger*);
13233 SQLITE_PRIVATE   Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
13234 SQLITE_PRIVATE   Trigger *sqlite3TriggerList(Parse *, Table *);
13235 SQLITE_PRIVATE   void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
13236                             int, int, int);
13237 SQLITE_PRIVATE   void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
13238   void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
13239 SQLITE_PRIVATE   void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
13240 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
13241 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
13242                                         Select*,u8);
13243 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
13244 SQLITE_PRIVATE   TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
13245 SQLITE_PRIVATE   void sqlite3DeleteTrigger(sqlite3*, Trigger*);
13246 SQLITE_PRIVATE   void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
13247 SQLITE_PRIVATE   u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
13248 # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
13249 #else
13250 # define sqlite3TriggersExist(B,C,D,E,F) 0
13251 # define sqlite3DeleteTrigger(A,B)
13252 # define sqlite3DropTriggerPtr(A,B)
13253 # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
13254 # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
13255 # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
13256 # define sqlite3TriggerList(X, Y) 0
13257 # define sqlite3ParseToplevel(p) p
13258 # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
13259 #endif
13260
13261 SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
13262 SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
13263 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
13264 #ifndef SQLITE_OMIT_AUTHORIZATION
13265 SQLITE_PRIVATE   void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
13266 SQLITE_PRIVATE   int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
13267 SQLITE_PRIVATE   void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
13268 SQLITE_PRIVATE   void sqlite3AuthContextPop(AuthContext*);
13269 SQLITE_PRIVATE   int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
13270 #else
13271 # define sqlite3AuthRead(a,b,c,d)
13272 # define sqlite3AuthCheck(a,b,c,d,e)    SQLITE_OK
13273 # define sqlite3AuthContextPush(a,b,c)
13274 # define sqlite3AuthContextPop(a)  ((void)(a))
13275 #endif
13276 SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
13277 SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
13278 SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
13279 SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
13280 SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
13281 SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
13282 SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
13283 SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
13284 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
13285 SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
13286 SQLITE_PRIVATE int sqlite3Atoi(const char*);
13287 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
13288 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
13289 SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
13290 SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
13291 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
13292 #ifndef SQLITE_OMIT_VIRTUALTABLE
13293 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
13294 #endif
13295 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
13296
13297 /*
13298 ** Routines to read and write variable-length integers.  These used to
13299 ** be defined locally, but now we use the varint routines in the util.c
13300 ** file.
13301 */
13302 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
13303 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
13304 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
13305 SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
13306
13307 /*
13308 ** The common case is for a varint to be a single byte.  They following
13309 ** macros handle the common case without a procedure call, but then call
13310 ** the procedure for larger varints.
13311 */
13312 #define getVarint32(A,B)  \
13313   (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
13314 #define putVarint32(A,B)  \
13315   (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
13316   sqlite3PutVarint((A),(B)))
13317 #define getVarint    sqlite3GetVarint
13318 #define putVarint    sqlite3PutVarint
13319
13320
13321 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
13322 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
13323 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
13324 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
13325 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
13326 SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
13327 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
13328 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
13329 SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
13330 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
13331 SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
13332 SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
13333
13334 #if defined(SQLITE_TEST) 
13335 SQLITE_PRIVATE const char *sqlite3ErrName(int);
13336 #endif
13337
13338 SQLITE_PRIVATE const char *sqlite3ErrStr(int);
13339 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
13340 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
13341 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
13342 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
13343 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*, int);
13344 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
13345 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
13346 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
13347 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
13348 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
13349 SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
13350 SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
13351 SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
13352 SQLITE_PRIVATE int sqlite3AbsInt32(int);
13353 #ifdef SQLITE_ENABLE_8_3_NAMES
13354 SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
13355 #else
13356 # define sqlite3FileSuffix3(X,Y)
13357 #endif
13358 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
13359
13360 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
13361 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
13362 SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8, 
13363                         void(*)(void*));
13364 SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
13365 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
13366 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
13367 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
13368 SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
13369 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
13370 #ifndef SQLITE_AMALGAMATION
13371 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
13372 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
13373 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
13374 SQLITE_PRIVATE const Token sqlite3IntTokens[];
13375 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
13376 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
13377 #ifndef SQLITE_OMIT_WSD
13378 SQLITE_PRIVATE int sqlite3PendingByte;
13379 #endif
13380 #endif
13381 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
13382 SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
13383 SQLITE_PRIVATE void sqlite3AlterFunctions(void);
13384 SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
13385 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
13386 SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
13387 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
13388 SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
13389 SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
13390 SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
13391 SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
13392 SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
13393 SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
13394 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
13395 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
13396 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
13397 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
13398 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
13399 SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
13400 SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
13401 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
13402 SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
13403 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
13404 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
13405 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
13406 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
13407 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
13408 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
13409 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
13410 SQLITE_PRIVATE void sqlite3SchemaClear(void *);
13411 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
13412 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
13413 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
13414 SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
13415 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
13416 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
13417 #ifdef SQLITE_DEBUG
13418 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
13419 #endif
13420 SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *, 
13421   void (*)(sqlite3_context*,int,sqlite3_value **),
13422   void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
13423   FuncDestructor *pDestructor
13424 );
13425 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
13426 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
13427
13428 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
13429 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
13430 SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
13431 SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
13432 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
13433 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
13434 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
13435 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
13436
13437 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
13438 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
13439
13440 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
13441 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
13442 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
13443 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
13444 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
13445 SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
13446 #endif
13447
13448 /*
13449 ** The interface to the LEMON-generated parser
13450 */
13451 SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
13452 SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
13453 SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
13454 #ifdef YYTRACKMAXSTACKDEPTH
13455 SQLITE_PRIVATE   int sqlite3ParserStackPeak(void*);
13456 #endif
13457
13458 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
13459 #ifndef SQLITE_OMIT_LOAD_EXTENSION
13460 SQLITE_PRIVATE   void sqlite3CloseExtensions(sqlite3*);
13461 #else
13462 # define sqlite3CloseExtensions(X)
13463 #endif
13464
13465 #ifndef SQLITE_OMIT_SHARED_CACHE
13466 SQLITE_PRIVATE   void sqlite3TableLock(Parse *, int, int, u8, const char *);
13467 #else
13468   #define sqlite3TableLock(v,w,x,y,z)
13469 #endif
13470
13471 #ifdef SQLITE_TEST
13472 SQLITE_PRIVATE   int sqlite3Utf8To8(unsigned char*);
13473 #endif
13474
13475 #ifdef SQLITE_OMIT_VIRTUALTABLE
13476 #  define sqlite3VtabClear(Y)
13477 #  define sqlite3VtabSync(X,Y) SQLITE_OK
13478 #  define sqlite3VtabRollback(X)
13479 #  define sqlite3VtabCommit(X)
13480 #  define sqlite3VtabInSync(db) 0
13481 #  define sqlite3VtabLock(X) 
13482 #  define sqlite3VtabUnlock(X)
13483 #  define sqlite3VtabUnlockList(X)
13484 #  define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
13485 #  define sqlite3GetVTable(X,Y)  ((VTable*)0)
13486 #else
13487 SQLITE_PRIVATE    void sqlite3VtabClear(sqlite3 *db, Table*);
13488 SQLITE_PRIVATE    void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
13489 SQLITE_PRIVATE    int sqlite3VtabSync(sqlite3 *db, Vdbe*);
13490 SQLITE_PRIVATE    int sqlite3VtabRollback(sqlite3 *db);
13491 SQLITE_PRIVATE    int sqlite3VtabCommit(sqlite3 *db);
13492 SQLITE_PRIVATE    void sqlite3VtabLock(VTable *);
13493 SQLITE_PRIVATE    void sqlite3VtabUnlock(VTable *);
13494 SQLITE_PRIVATE    void sqlite3VtabUnlockList(sqlite3*);
13495 SQLITE_PRIVATE    int sqlite3VtabSavepoint(sqlite3 *, int, int);
13496 SQLITE_PRIVATE    void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
13497 SQLITE_PRIVATE    VTable *sqlite3GetVTable(sqlite3*, Table*);
13498 #  define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
13499 #endif
13500 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
13501 SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
13502 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
13503 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
13504 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
13505 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
13506 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
13507 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
13508 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
13509 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
13510 SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
13511 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
13512 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
13513 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
13514 SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
13515 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
13516 SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
13517 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
13518 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
13519 SQLITE_PRIVATE const char *sqlite3JournalModename(int);
13520 #ifndef SQLITE_OMIT_WAL
13521 SQLITE_PRIVATE   int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
13522 SQLITE_PRIVATE   int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
13523 #endif
13524 #ifndef SQLITE_OMIT_CTE
13525 SQLITE_PRIVATE   With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
13526 SQLITE_PRIVATE   void sqlite3WithDelete(sqlite3*,With*);
13527 SQLITE_PRIVATE   void sqlite3WithPush(Parse*, With*, u8);
13528 #else
13529 #define sqlite3WithPush(x,y,z)
13530 #define sqlite3WithDelete(x,y)
13531 #endif
13532
13533 /* Declarations for functions in fkey.c. All of these are replaced by
13534 ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
13535 ** key functionality is available. If OMIT_TRIGGER is defined but
13536 ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
13537 ** this case foreign keys are parsed, but no other functionality is 
13538 ** provided (enforcement of FK constraints requires the triggers sub-system).
13539 */
13540 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
13541 SQLITE_PRIVATE   void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
13542 SQLITE_PRIVATE   void sqlite3FkDropTable(Parse*, SrcList *, Table*);
13543 SQLITE_PRIVATE   void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
13544 SQLITE_PRIVATE   int sqlite3FkRequired(Parse*, Table*, int*, int);
13545 SQLITE_PRIVATE   u32 sqlite3FkOldmask(Parse*, Table*);
13546 SQLITE_PRIVATE   FKey *sqlite3FkReferences(Table *);
13547 #else
13548   #define sqlite3FkActions(a,b,c,d,e,f)
13549   #define sqlite3FkCheck(a,b,c,d,e,f)
13550   #define sqlite3FkDropTable(a,b,c)
13551   #define sqlite3FkOldmask(a,b)         0
13552   #define sqlite3FkRequired(a,b,c,d)    0
13553 #endif
13554 #ifndef SQLITE_OMIT_FOREIGN_KEY
13555 SQLITE_PRIVATE   void sqlite3FkDelete(sqlite3 *, Table*);
13556 SQLITE_PRIVATE   int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
13557 #else
13558   #define sqlite3FkDelete(a,b)
13559   #define sqlite3FkLocateIndex(a,b,c,d,e)
13560 #endif
13561
13562
13563 /*
13564 ** Available fault injectors.  Should be numbered beginning with 0.
13565 */
13566 #define SQLITE_FAULTINJECTOR_MALLOC     0
13567 #define SQLITE_FAULTINJECTOR_COUNT      1
13568
13569 /*
13570 ** The interface to the code in fault.c used for identifying "benign"
13571 ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
13572 ** is not defined.
13573 */
13574 #ifndef SQLITE_OMIT_BUILTIN_TEST
13575 SQLITE_PRIVATE   void sqlite3BeginBenignMalloc(void);
13576 SQLITE_PRIVATE   void sqlite3EndBenignMalloc(void);
13577 #else
13578   #define sqlite3BeginBenignMalloc()
13579   #define sqlite3EndBenignMalloc()
13580 #endif
13581
13582 /*
13583 ** Allowed return values from sqlite3FindInIndex()
13584 */
13585 #define IN_INDEX_ROWID        1   /* Search the rowid of the table */
13586 #define IN_INDEX_EPH          2   /* Search an ephemeral b-tree */
13587 #define IN_INDEX_INDEX_ASC    3   /* Existing index ASCENDING */
13588 #define IN_INDEX_INDEX_DESC   4   /* Existing index DESCENDING */
13589 #define IN_INDEX_NOOP         5   /* No table available. Use comparisons */
13590 /*
13591 ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
13592 */
13593 #define IN_INDEX_NOOP_OK     0x0001  /* OK to return IN_INDEX_NOOP */
13594 #define IN_INDEX_MEMBERSHIP  0x0002  /* IN operator used for membership test */
13595 #define IN_INDEX_LOOP        0x0004  /* IN operator used as a loop */
13596 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*);
13597
13598 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
13599 SQLITE_PRIVATE   int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
13600 SQLITE_PRIVATE   int sqlite3JournalSize(sqlite3_vfs *);
13601 SQLITE_PRIVATE   int sqlite3JournalCreate(sqlite3_file *);
13602 SQLITE_PRIVATE   int sqlite3JournalExists(sqlite3_file *p);
13603 #else
13604   #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
13605   #define sqlite3JournalExists(p) 1
13606 #endif
13607
13608 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
13609 SQLITE_PRIVATE int sqlite3MemJournalSize(void);
13610 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
13611
13612 SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p);
13613 #if SQLITE_MAX_EXPR_DEPTH>0
13614 SQLITE_PRIVATE   int sqlite3SelectExprHeight(Select *);
13615 SQLITE_PRIVATE   int sqlite3ExprCheckHeight(Parse*, int);
13616 #else
13617   #define sqlite3SelectExprHeight(x) 0
13618   #define sqlite3ExprCheckHeight(x,y)
13619 #endif
13620
13621 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
13622 SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
13623
13624 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
13625 SQLITE_PRIVATE   void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
13626 SQLITE_PRIVATE   void sqlite3ConnectionUnlocked(sqlite3 *db);
13627 SQLITE_PRIVATE   void sqlite3ConnectionClosed(sqlite3 *db);
13628 #else
13629   #define sqlite3ConnectionBlocked(x,y)
13630   #define sqlite3ConnectionUnlocked(x)
13631   #define sqlite3ConnectionClosed(x)
13632 #endif
13633
13634 #ifdef SQLITE_DEBUG
13635 SQLITE_PRIVATE   void sqlite3ParserTrace(FILE*, char *);
13636 #endif
13637
13638 /*
13639 ** If the SQLITE_ENABLE IOTRACE exists then the global variable
13640 ** sqlite3IoTrace is a pointer to a printf-like routine used to
13641 ** print I/O tracing messages. 
13642 */
13643 #ifdef SQLITE_ENABLE_IOTRACE
13644 # define IOTRACE(A)  if( sqlite3IoTrace ){ sqlite3IoTrace A; }
13645 SQLITE_PRIVATE   void sqlite3VdbeIOTraceSql(Vdbe*);
13646 SQLITE_API SQLITE_EXTERN void (SQLITE_CDECL *sqlite3IoTrace)(const char*,...);
13647 #else
13648 # define IOTRACE(A)
13649 # define sqlite3VdbeIOTraceSql(X)
13650 #endif
13651
13652 /*
13653 ** These routines are available for the mem2.c debugging memory allocator
13654 ** only.  They are used to verify that different "types" of memory
13655 ** allocations are properly tracked by the system.
13656 **
13657 ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
13658 ** the MEMTYPE_* macros defined below.  The type must be a bitmask with
13659 ** a single bit set.
13660 **
13661 ** sqlite3MemdebugHasType() returns true if any of the bits in its second
13662 ** argument match the type set by the previous sqlite3MemdebugSetType().
13663 ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
13664 **
13665 ** sqlite3MemdebugNoType() returns true if none of the bits in its second
13666 ** argument match the type set by the previous sqlite3MemdebugSetType().
13667 **
13668 ** Perhaps the most important point is the difference between MEMTYPE_HEAP
13669 ** and MEMTYPE_LOOKASIDE.  If an allocation is MEMTYPE_LOOKASIDE, that means
13670 ** it might have been allocated by lookaside, except the allocation was
13671 ** too large or lookaside was already full.  It is important to verify
13672 ** that allocations that might have been satisfied by lookaside are not
13673 ** passed back to non-lookaside free() routines.  Asserts such as the
13674 ** example above are placed on the non-lookaside free() routines to verify
13675 ** this constraint. 
13676 **
13677 ** All of this is no-op for a production build.  It only comes into
13678 ** play when the SQLITE_MEMDEBUG compile-time option is used.
13679 */
13680 #ifdef SQLITE_MEMDEBUG
13681 SQLITE_PRIVATE   void sqlite3MemdebugSetType(void*,u8);
13682 SQLITE_PRIVATE   int sqlite3MemdebugHasType(void*,u8);
13683 SQLITE_PRIVATE   int sqlite3MemdebugNoType(void*,u8);
13684 #else
13685 # define sqlite3MemdebugSetType(X,Y)  /* no-op */
13686 # define sqlite3MemdebugHasType(X,Y)  1
13687 # define sqlite3MemdebugNoType(X,Y)   1
13688 #endif
13689 #define MEMTYPE_HEAP       0x01  /* General heap allocations */
13690 #define MEMTYPE_LOOKASIDE  0x02  /* Heap that might have been lookaside */
13691 #define MEMTYPE_SCRATCH    0x04  /* Scratch allocations */
13692 #define MEMTYPE_PCACHE     0x08  /* Page cache allocations */
13693
13694 /*
13695 ** Threading interface
13696 */
13697 #if SQLITE_MAX_WORKER_THREADS>0
13698 SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
13699 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
13700 #endif
13701
13702 #endif /* _SQLITEINT_H_ */
13703
13704 /************** End of sqliteInt.h *******************************************/
13705 /************** Begin file global.c ******************************************/
13706 /*
13707 ** 2008 June 13
13708 **
13709 ** The author disclaims copyright to this source code.  In place of
13710 ** a legal notice, here is a blessing:
13711 **
13712 **    May you do good and not evil.
13713 **    May you find forgiveness for yourself and forgive others.
13714 **    May you share freely, never taking more than you give.
13715 **
13716 *************************************************************************
13717 **
13718 ** This file contains definitions of global variables and constants.
13719 */
13720
13721 /* An array to map all upper-case characters into their corresponding
13722 ** lower-case character. 
13723 **
13724 ** SQLite only considers US-ASCII (or EBCDIC) characters.  We do not
13725 ** handle case conversions for the UTF character set since the tables
13726 ** involved are nearly as big or bigger than SQLite itself.
13727 */
13728 SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
13729 #ifdef SQLITE_ASCII
13730       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
13731      18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
13732      36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
13733      54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
13734     104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
13735     122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
13736     108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
13737     126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
13738     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
13739     162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
13740     180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
13741     198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
13742     216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
13743     234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
13744     252,253,254,255
13745 #endif
13746 #ifdef SQLITE_EBCDIC
13747       0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, /* 0x */
13748      16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
13749      32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
13750      48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
13751      64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
13752      80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
13753      96, 97, 98, 99,100,101,102,103,104,105,106,107,108,109,110,111, /* 6x */
13754     112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127, /* 7x */
13755     128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
13756     144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159, /* 9x */
13757     160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
13758     176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
13759     192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
13760     208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
13761     224,225,162,163,164,165,166,167,168,169,234,235,236,237,238,239, /* Ex */
13762     240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255, /* Fx */
13763 #endif
13764 };
13765
13766 /*
13767 ** The following 256 byte lookup table is used to support SQLites built-in
13768 ** equivalents to the following standard library functions:
13769 **
13770 **   isspace()                        0x01
13771 **   isalpha()                        0x02
13772 **   isdigit()                        0x04
13773 **   isalnum()                        0x06
13774 **   isxdigit()                       0x08
13775 **   toupper()                        0x20
13776 **   SQLite identifier character      0x40
13777 **
13778 ** Bit 0x20 is set if the mapped character requires translation to upper
13779 ** case. i.e. if the character is a lower-case ASCII character.
13780 ** If x is a lower-case ASCII character, then its upper-case equivalent
13781 ** is (x - 0x20). Therefore toupper() can be implemented as:
13782 **
13783 **   (x & ~(map[x]&0x20))
13784 **
13785 ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
13786 ** array. tolower() is used more often than toupper() by SQLite.
13787 **
13788 ** Bit 0x40 is set if the character non-alphanumeric and can be used in an 
13789 ** SQLite identifier.  Identifiers are alphanumerics, "_", "$", and any
13790 ** non-ASCII UTF character. Hence the test for whether or not a character is
13791 ** part of an identifier is 0x46.
13792 **
13793 ** SQLite's versions are identical to the standard versions assuming a
13794 ** locale of "C". They are implemented as macros in sqliteInt.h.
13795 */
13796 #ifdef SQLITE_ASCII
13797 SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
13798   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 00..07    ........ */
13799   0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00,  /* 08..0f    ........ */
13800   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 10..17    ........ */
13801   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 18..1f    ........ */
13802   0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00,  /* 20..27     !"#$%&' */
13803   0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 28..2f    ()*+,-./ */
13804   0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c,  /* 30..37    01234567 */
13805   0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 38..3f    89:;<=>? */
13806
13807   0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02,  /* 40..47    @ABCDEFG */
13808   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 48..4f    HIJKLMNO */
13809   0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02,  /* 50..57    PQRSTUVW */
13810   0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40,  /* 58..5f    XYZ[\]^_ */
13811   0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22,  /* 60..67    `abcdefg */
13812   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 68..6f    hijklmno */
13813   0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22,  /* 70..77    pqrstuvw */
13814   0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00,  /* 78..7f    xyz{|}~. */
13815
13816   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 80..87    ........ */
13817   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 88..8f    ........ */
13818   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 90..97    ........ */
13819   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* 98..9f    ........ */
13820   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a0..a7    ........ */
13821   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* a8..af    ........ */
13822   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b0..b7    ........ */
13823   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* b8..bf    ........ */
13824
13825   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c0..c7    ........ */
13826   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* c8..cf    ........ */
13827   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d0..d7    ........ */
13828   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* d8..df    ........ */
13829   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e0..e7    ........ */
13830   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* e8..ef    ........ */
13831   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40,  /* f0..f7    ........ */
13832   0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40   /* f8..ff    ........ */
13833 };
13834 #endif
13835
13836 /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
13837 ** compatibility for legacy applications, the URI filename capability is
13838 ** disabled by default.
13839 **
13840 ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
13841 ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
13842 **
13843 ** EVIDENCE-OF: R-43642-56306 By default, URI handling is globally
13844 ** disabled. The default value may be changed by compiling with the
13845 ** SQLITE_USE_URI symbol defined.
13846 */
13847 #ifndef SQLITE_USE_URI
13848 # define  SQLITE_USE_URI 0
13849 #endif
13850
13851 /* EVIDENCE-OF: R-38720-18127 The default setting is determined by the
13852 ** SQLITE_ALLOW_COVERING_INDEX_SCAN compile-time option, or is "on" if
13853 ** that compile-time option is omitted.
13854 */
13855 #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
13856 # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
13857 #endif
13858
13859 /* The minimum PMA size is set to this value multiplied by the database
13860 ** page size in bytes.
13861 */
13862 #ifndef SQLITE_SORTER_PMASZ
13863 # define SQLITE_SORTER_PMASZ 250
13864 #endif
13865
13866 /*
13867 ** The following singleton contains the global configuration for
13868 ** the SQLite library.
13869 */
13870 SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
13871    SQLITE_DEFAULT_MEMSTATUS,  /* bMemstat */
13872    1,                         /* bCoreMutex */
13873    SQLITE_THREADSAFE==1,      /* bFullMutex */
13874    SQLITE_USE_URI,            /* bOpenUri */
13875    SQLITE_ALLOW_COVERING_INDEX_SCAN,   /* bUseCis */
13876    0x7ffffffe,                /* mxStrlen */
13877    0,                         /* neverCorrupt */
13878    128,                       /* szLookaside */
13879    500,                       /* nLookaside */
13880    {0,0,0,0,0,0,0,0},         /* m */
13881    {0,0,0,0,0,0,0,0,0},       /* mutex */
13882    {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
13883    (void*)0,                  /* pHeap */
13884    0,                         /* nHeap */
13885    0, 0,                      /* mnHeap, mxHeap */
13886    SQLITE_DEFAULT_MMAP_SIZE,  /* szMmap */
13887    SQLITE_MAX_MMAP_SIZE,      /* mxMmap */
13888    (void*)0,                  /* pScratch */
13889    0,                         /* szScratch */
13890    0,                         /* nScratch */
13891    (void*)0,                  /* pPage */
13892    0,                         /* szPage */
13893    0,                         /* nPage */
13894    0,                         /* mxParserStack */
13895    0,                         /* sharedCacheEnabled */
13896    SQLITE_SORTER_PMASZ,       /* szPma */
13897    /* All the rest should always be initialized to zero */
13898    0,                         /* isInit */
13899    0,                         /* inProgress */
13900    0,                         /* isMutexInit */
13901    0,                         /* isMallocInit */
13902    0,                         /* isPCacheInit */
13903    0,                         /* nRefInitMutex */
13904    0,                         /* pInitMutex */
13905    0,                         /* xLog */
13906    0,                         /* pLogArg */
13907 #ifdef SQLITE_ENABLE_SQLLOG
13908    0,                         /* xSqllog */
13909    0,                         /* pSqllogArg */
13910 #endif
13911 #ifdef SQLITE_VDBE_COVERAGE
13912    0,                         /* xVdbeBranch */
13913    0,                         /* pVbeBranchArg */
13914 #endif
13915 #ifndef SQLITE_OMIT_BUILTIN_TEST
13916    0,                         /* xTestCallback */
13917 #endif
13918    0                          /* bLocaltimeFault */
13919 };
13920
13921 /*
13922 ** Hash table for global functions - functions common to all
13923 ** database connections.  After initialization, this table is
13924 ** read-only.
13925 */
13926 SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
13927
13928 /*
13929 ** Constant tokens for values 0 and 1.
13930 */
13931 SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
13932    { "0", 1 },
13933    { "1", 1 }
13934 };
13935
13936
13937 /*
13938 ** The value of the "pending" byte must be 0x40000000 (1 byte past the
13939 ** 1-gibabyte boundary) in a compatible database.  SQLite never uses
13940 ** the database page that contains the pending byte.  It never attempts
13941 ** to read or write that page.  The pending byte page is set assign
13942 ** for use by the VFS layers as space for managing file locks.
13943 **
13944 ** During testing, it is often desirable to move the pending byte to
13945 ** a different position in the file.  This allows code that has to
13946 ** deal with the pending byte to run on files that are much smaller
13947 ** than 1 GiB.  The sqlite3_test_control() interface can be used to
13948 ** move the pending byte.
13949 **
13950 ** IMPORTANT:  Changing the pending byte to any value other than
13951 ** 0x40000000 results in an incompatible database file format!
13952 ** Changing the pending byte during operation will result in undefined
13953 ** and incorrect behavior.
13954 */
13955 #ifndef SQLITE_OMIT_WSD
13956 SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
13957 #endif
13958
13959 /*
13960 ** Properties of opcodes.  The OPFLG_INITIALIZER macro is
13961 ** created by mkopcodeh.awk during compilation.  Data is obtained
13962 ** from the comments following the "case OP_xxxx:" statements in
13963 ** the vdbe.c file.  
13964 */
13965 SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
13966
13967 /************** End of global.c **********************************************/
13968 /************** Begin file ctime.c *******************************************/
13969 /*
13970 ** 2010 February 23
13971 **
13972 ** The author disclaims copyright to this source code.  In place of
13973 ** a legal notice, here is a blessing:
13974 **
13975 **    May you do good and not evil.
13976 **    May you find forgiveness for yourself and forgive others.
13977 **    May you share freely, never taking more than you give.
13978 **
13979 *************************************************************************
13980 **
13981 ** This file implements routines used to report what compile-time options
13982 ** SQLite was built with.
13983 */
13984
13985 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
13986
13987
13988 /*
13989 ** An array of names of all compile-time options.  This array should 
13990 ** be sorted A-Z.
13991 **
13992 ** This array looks large, but in a typical installation actually uses
13993 ** only a handful of compile-time options, so most times this array is usually
13994 ** rather short and uses little memory space.
13995 */
13996 static const char * const azCompileOpt[] = {
13997
13998 /* These macros are provided to "stringify" the value of the define
13999 ** for those options in which the value is meaningful. */
14000 #define CTIMEOPT_VAL_(opt) #opt
14001 #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
14002
14003 #if SQLITE_32BIT_ROWID
14004   "32BIT_ROWID",
14005 #endif
14006 #if SQLITE_4_BYTE_ALIGNED_MALLOC
14007   "4_BYTE_ALIGNED_MALLOC",
14008 #endif
14009 #if SQLITE_CASE_SENSITIVE_LIKE
14010   "CASE_SENSITIVE_LIKE",
14011 #endif
14012 #if SQLITE_CHECK_PAGES
14013   "CHECK_PAGES",
14014 #endif
14015 #if SQLITE_COVERAGE_TEST
14016   "COVERAGE_TEST",
14017 #endif
14018 #if SQLITE_DEBUG
14019   "DEBUG",
14020 #endif
14021 #if SQLITE_DEFAULT_LOCKING_MODE
14022   "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
14023 #endif
14024 #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
14025   "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
14026 #endif
14027 #if SQLITE_DISABLE_DIRSYNC
14028   "DISABLE_DIRSYNC",
14029 #endif
14030 #if SQLITE_DISABLE_LFS
14031   "DISABLE_LFS",
14032 #endif
14033 #if SQLITE_ENABLE_API_ARMOR
14034   "ENABLE_API_ARMOR",
14035 #endif
14036 #if SQLITE_ENABLE_ATOMIC_WRITE
14037   "ENABLE_ATOMIC_WRITE",
14038 #endif
14039 #if SQLITE_ENABLE_CEROD
14040   "ENABLE_CEROD",
14041 #endif
14042 #if SQLITE_ENABLE_COLUMN_METADATA
14043   "ENABLE_COLUMN_METADATA",
14044 #endif
14045 #if SQLITE_ENABLE_EXPENSIVE_ASSERT
14046   "ENABLE_EXPENSIVE_ASSERT",
14047 #endif
14048 #if SQLITE_ENABLE_FTS1
14049   "ENABLE_FTS1",
14050 #endif
14051 #if SQLITE_ENABLE_FTS2
14052   "ENABLE_FTS2",
14053 #endif
14054 #if SQLITE_ENABLE_FTS3
14055   "ENABLE_FTS3",
14056 #endif
14057 #if SQLITE_ENABLE_FTS3_PARENTHESIS
14058   "ENABLE_FTS3_PARENTHESIS",
14059 #endif
14060 #if SQLITE_ENABLE_FTS4
14061   "ENABLE_FTS4",
14062 #endif
14063 #if SQLITE_ENABLE_ICU
14064   "ENABLE_ICU",
14065 #endif
14066 #if SQLITE_ENABLE_IOTRACE
14067   "ENABLE_IOTRACE",
14068 #endif
14069 #if SQLITE_ENABLE_LOAD_EXTENSION
14070   "ENABLE_LOAD_EXTENSION",
14071 #endif
14072 #if SQLITE_ENABLE_LOCKING_STYLE
14073   "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
14074 #endif
14075 #if SQLITE_ENABLE_MEMORY_MANAGEMENT
14076   "ENABLE_MEMORY_MANAGEMENT",
14077 #endif
14078 #if SQLITE_ENABLE_MEMSYS3
14079   "ENABLE_MEMSYS3",
14080 #endif
14081 #if SQLITE_ENABLE_MEMSYS5
14082   "ENABLE_MEMSYS5",
14083 #endif
14084 #if SQLITE_ENABLE_OVERSIZE_CELL_CHECK
14085   "ENABLE_OVERSIZE_CELL_CHECK",
14086 #endif
14087 #if SQLITE_ENABLE_RTREE
14088   "ENABLE_RTREE",
14089 #endif
14090 #if defined(SQLITE_ENABLE_STAT4)
14091   "ENABLE_STAT4",
14092 #elif defined(SQLITE_ENABLE_STAT3)
14093   "ENABLE_STAT3",
14094 #endif
14095 #if SQLITE_ENABLE_UNLOCK_NOTIFY
14096   "ENABLE_UNLOCK_NOTIFY",
14097 #endif
14098 #if SQLITE_ENABLE_UPDATE_DELETE_LIMIT
14099   "ENABLE_UPDATE_DELETE_LIMIT",
14100 #endif
14101 #if SQLITE_HAS_CODEC
14102   "HAS_CODEC",
14103 #endif
14104 #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
14105   "HAVE_ISNAN",
14106 #endif
14107 #if SQLITE_HOMEGROWN_RECURSIVE_MUTEX
14108   "HOMEGROWN_RECURSIVE_MUTEX",
14109 #endif
14110 #if SQLITE_IGNORE_AFP_LOCK_ERRORS
14111   "IGNORE_AFP_LOCK_ERRORS",
14112 #endif
14113 #if SQLITE_IGNORE_FLOCK_LOCK_ERRORS
14114   "IGNORE_FLOCK_LOCK_ERRORS",
14115 #endif
14116 #ifdef SQLITE_INT64_TYPE
14117   "INT64_TYPE",
14118 #endif
14119 #if SQLITE_LOCK_TRACE
14120   "LOCK_TRACE",
14121 #endif
14122 #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
14123   "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
14124 #endif
14125 #ifdef SQLITE_MAX_SCHEMA_RETRY
14126   "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
14127 #endif
14128 #if SQLITE_MEMDEBUG
14129   "MEMDEBUG",
14130 #endif
14131 #if SQLITE_MIXED_ENDIAN_64BIT_FLOAT
14132   "MIXED_ENDIAN_64BIT_FLOAT",
14133 #endif
14134 #if SQLITE_NO_SYNC
14135   "NO_SYNC",
14136 #endif
14137 #if SQLITE_OMIT_ALTERTABLE
14138   "OMIT_ALTERTABLE",
14139 #endif
14140 #if SQLITE_OMIT_ANALYZE
14141   "OMIT_ANALYZE",
14142 #endif
14143 #if SQLITE_OMIT_ATTACH
14144   "OMIT_ATTACH",
14145 #endif
14146 #if SQLITE_OMIT_AUTHORIZATION
14147   "OMIT_AUTHORIZATION",
14148 #endif
14149 #if SQLITE_OMIT_AUTOINCREMENT
14150   "OMIT_AUTOINCREMENT",
14151 #endif
14152 #if SQLITE_OMIT_AUTOINIT
14153   "OMIT_AUTOINIT",
14154 #endif
14155 #if SQLITE_OMIT_AUTOMATIC_INDEX
14156   "OMIT_AUTOMATIC_INDEX",
14157 #endif
14158 #if SQLITE_OMIT_AUTORESET
14159   "OMIT_AUTORESET",
14160 #endif
14161 #if SQLITE_OMIT_AUTOVACUUM
14162   "OMIT_AUTOVACUUM",
14163 #endif
14164 #if SQLITE_OMIT_BETWEEN_OPTIMIZATION
14165   "OMIT_BETWEEN_OPTIMIZATION",
14166 #endif
14167 #if SQLITE_OMIT_BLOB_LITERAL
14168   "OMIT_BLOB_LITERAL",
14169 #endif
14170 #if SQLITE_OMIT_BTREECOUNT
14171   "OMIT_BTREECOUNT",
14172 #endif
14173 #if SQLITE_OMIT_BUILTIN_TEST
14174   "OMIT_BUILTIN_TEST",
14175 #endif
14176 #if SQLITE_OMIT_CAST
14177   "OMIT_CAST",
14178 #endif
14179 #if SQLITE_OMIT_CHECK
14180   "OMIT_CHECK",
14181 #endif
14182 #if SQLITE_OMIT_COMPLETE
14183   "OMIT_COMPLETE",
14184 #endif
14185 #if SQLITE_OMIT_COMPOUND_SELECT
14186   "OMIT_COMPOUND_SELECT",
14187 #endif
14188 #if SQLITE_OMIT_CTE
14189   "OMIT_CTE",
14190 #endif
14191 #if SQLITE_OMIT_DATETIME_FUNCS
14192   "OMIT_DATETIME_FUNCS",
14193 #endif
14194 #if SQLITE_OMIT_DECLTYPE
14195   "OMIT_DECLTYPE",
14196 #endif
14197 #if SQLITE_OMIT_DEPRECATED
14198   "OMIT_DEPRECATED",
14199 #endif
14200 #if SQLITE_OMIT_DISKIO
14201   "OMIT_DISKIO",
14202 #endif
14203 #if SQLITE_OMIT_EXPLAIN
14204   "OMIT_EXPLAIN",
14205 #endif
14206 #if SQLITE_OMIT_FLAG_PRAGMAS
14207   "OMIT_FLAG_PRAGMAS",
14208 #endif
14209 #if SQLITE_OMIT_FLOATING_POINT
14210   "OMIT_FLOATING_POINT",
14211 #endif
14212 #if SQLITE_OMIT_FOREIGN_KEY
14213   "OMIT_FOREIGN_KEY",
14214 #endif
14215 #if SQLITE_OMIT_GET_TABLE
14216   "OMIT_GET_TABLE",
14217 #endif
14218 #if SQLITE_OMIT_INCRBLOB
14219   "OMIT_INCRBLOB",
14220 #endif
14221 #if SQLITE_OMIT_INTEGRITY_CHECK
14222   "OMIT_INTEGRITY_CHECK",
14223 #endif
14224 #if SQLITE_OMIT_LIKE_OPTIMIZATION
14225   "OMIT_LIKE_OPTIMIZATION",
14226 #endif
14227 #if SQLITE_OMIT_LOAD_EXTENSION
14228   "OMIT_LOAD_EXTENSION",
14229 #endif
14230 #if SQLITE_OMIT_LOCALTIME
14231   "OMIT_LOCALTIME",
14232 #endif
14233 #if SQLITE_OMIT_LOOKASIDE
14234   "OMIT_LOOKASIDE",
14235 #endif
14236 #if SQLITE_OMIT_MEMORYDB
14237   "OMIT_MEMORYDB",
14238 #endif
14239 #if SQLITE_OMIT_OR_OPTIMIZATION
14240   "OMIT_OR_OPTIMIZATION",
14241 #endif
14242 #if SQLITE_OMIT_PAGER_PRAGMAS
14243   "OMIT_PAGER_PRAGMAS",
14244 #endif
14245 #if SQLITE_OMIT_PRAGMA
14246   "OMIT_PRAGMA",
14247 #endif
14248 #if SQLITE_OMIT_PROGRESS_CALLBACK
14249   "OMIT_PROGRESS_CALLBACK",
14250 #endif
14251 #if SQLITE_OMIT_QUICKBALANCE
14252   "OMIT_QUICKBALANCE",
14253 #endif
14254 #if SQLITE_OMIT_REINDEX
14255   "OMIT_REINDEX",
14256 #endif
14257 #if SQLITE_OMIT_SCHEMA_PRAGMAS
14258   "OMIT_SCHEMA_PRAGMAS",
14259 #endif
14260 #if SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
14261   "OMIT_SCHEMA_VERSION_PRAGMAS",
14262 #endif
14263 #if SQLITE_OMIT_SHARED_CACHE
14264   "OMIT_SHARED_CACHE",
14265 #endif
14266 #if SQLITE_OMIT_SUBQUERY
14267   "OMIT_SUBQUERY",
14268 #endif
14269 #if SQLITE_OMIT_TCL_VARIABLE
14270   "OMIT_TCL_VARIABLE",
14271 #endif
14272 #if SQLITE_OMIT_TEMPDB
14273   "OMIT_TEMPDB",
14274 #endif
14275 #if SQLITE_OMIT_TRACE
14276   "OMIT_TRACE",
14277 #endif
14278 #if SQLITE_OMIT_TRIGGER
14279   "OMIT_TRIGGER",
14280 #endif
14281 #if SQLITE_OMIT_TRUNCATE_OPTIMIZATION
14282   "OMIT_TRUNCATE_OPTIMIZATION",
14283 #endif
14284 #if SQLITE_OMIT_UTF16
14285   "OMIT_UTF16",
14286 #endif
14287 #if SQLITE_OMIT_VACUUM
14288   "OMIT_VACUUM",
14289 #endif
14290 #if SQLITE_OMIT_VIEW
14291   "OMIT_VIEW",
14292 #endif
14293 #if SQLITE_OMIT_VIRTUALTABLE
14294   "OMIT_VIRTUALTABLE",
14295 #endif
14296 #if SQLITE_OMIT_WAL
14297   "OMIT_WAL",
14298 #endif
14299 #if SQLITE_OMIT_WSD
14300   "OMIT_WSD",
14301 #endif
14302 #if SQLITE_OMIT_XFER_OPT
14303   "OMIT_XFER_OPT",
14304 #endif
14305 #if SQLITE_PERFORMANCE_TRACE
14306   "PERFORMANCE_TRACE",
14307 #endif
14308 #if SQLITE_PROXY_DEBUG
14309   "PROXY_DEBUG",
14310 #endif
14311 #if SQLITE_RTREE_INT_ONLY
14312   "RTREE_INT_ONLY",
14313 #endif
14314 #if SQLITE_SECURE_DELETE
14315   "SECURE_DELETE",
14316 #endif
14317 #if SQLITE_SMALL_STACK
14318   "SMALL_STACK",
14319 #endif
14320 #if SQLITE_SOUNDEX
14321   "SOUNDEX",
14322 #endif
14323 #if SQLITE_SYSTEM_MALLOC
14324   "SYSTEM_MALLOC",
14325 #endif
14326 #if SQLITE_TCL
14327   "TCL",
14328 #endif
14329 #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
14330   "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
14331 #endif
14332 #if SQLITE_TEST
14333   "TEST",
14334 #endif
14335 #if defined(SQLITE_THREADSAFE)
14336   "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
14337 #endif
14338 #if SQLITE_USE_ALLOCA
14339   "USE_ALLOCA",
14340 #endif
14341 #if SQLITE_USER_AUTHENTICATION
14342   "USER_AUTHENTICATION",
14343 #endif
14344 #if SQLITE_WIN32_MALLOC
14345   "WIN32_MALLOC",
14346 #endif
14347 #if SQLITE_ZERO_MALLOC
14348   "ZERO_MALLOC"
14349 #endif
14350 };
14351
14352 /*
14353 ** Given the name of a compile-time option, return true if that option
14354 ** was used and false if not.
14355 **
14356 ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
14357 ** is not required for a match.
14358 */
14359 SQLITE_API int SQLITE_STDCALL sqlite3_compileoption_used(const char *zOptName){
14360   int i, n;
14361
14362 #if SQLITE_ENABLE_API_ARMOR
14363   if( zOptName==0 ){
14364     (void)SQLITE_MISUSE_BKPT;
14365     return 0;
14366   }
14367 #endif
14368   if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
14369   n = sqlite3Strlen30(zOptName);
14370
14371   /* Since ArraySize(azCompileOpt) is normally in single digits, a
14372   ** linear search is adequate.  No need for a binary search. */
14373   for(i=0; i<ArraySize(azCompileOpt); i++){
14374     if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
14375      && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
14376     ){
14377       return 1;
14378     }
14379   }
14380   return 0;
14381 }
14382
14383 /*
14384 ** Return the N-th compile-time option string.  If N is out of range,
14385 ** return a NULL pointer.
14386 */
14387 SQLITE_API const char *SQLITE_STDCALL sqlite3_compileoption_get(int N){
14388   if( N>=0 && N<ArraySize(azCompileOpt) ){
14389     return azCompileOpt[N];
14390   }
14391   return 0;
14392 }
14393
14394 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
14395
14396 /************** End of ctime.c ***********************************************/
14397 /************** Begin file status.c ******************************************/
14398 /*
14399 ** 2008 June 18
14400 **
14401 ** The author disclaims copyright to this source code.  In place of
14402 ** a legal notice, here is a blessing:
14403 **
14404 **    May you do good and not evil.
14405 **    May you find forgiveness for yourself and forgive others.
14406 **    May you share freely, never taking more than you give.
14407 **
14408 *************************************************************************
14409 **
14410 ** This module implements the sqlite3_status() interface and related
14411 ** functionality.
14412 */
14413 /************** Include vdbeInt.h in the middle of status.c ******************/
14414 /************** Begin file vdbeInt.h *****************************************/
14415 /*
14416 ** 2003 September 6
14417 **
14418 ** The author disclaims copyright to this source code.  In place of
14419 ** a legal notice, here is a blessing:
14420 **
14421 **    May you do good and not evil.
14422 **    May you find forgiveness for yourself and forgive others.
14423 **    May you share freely, never taking more than you give.
14424 **
14425 *************************************************************************
14426 ** This is the header file for information that is private to the
14427 ** VDBE.  This information used to all be at the top of the single
14428 ** source code file "vdbe.c".  When that file became too big (over
14429 ** 6000 lines long) it was split up into several smaller files and
14430 ** this header information was factored out.
14431 */
14432 #ifndef _VDBEINT_H_
14433 #define _VDBEINT_H_
14434
14435 /*
14436 ** The maximum number of times that a statement will try to reparse
14437 ** itself before giving up and returning SQLITE_SCHEMA.
14438 */
14439 #ifndef SQLITE_MAX_SCHEMA_RETRY
14440 # define SQLITE_MAX_SCHEMA_RETRY 50
14441 #endif
14442
14443 /*
14444 ** SQL is translated into a sequence of instructions to be
14445 ** executed by a virtual machine.  Each instruction is an instance
14446 ** of the following structure.
14447 */
14448 typedef struct VdbeOp Op;
14449
14450 /*
14451 ** Boolean values
14452 */
14453 typedef unsigned Bool;
14454
14455 /* Opaque type used by code in vdbesort.c */
14456 typedef struct VdbeSorter VdbeSorter;
14457
14458 /* Opaque type used by the explainer */
14459 typedef struct Explain Explain;
14460
14461 /* Elements of the linked list at Vdbe.pAuxData */
14462 typedef struct AuxData AuxData;
14463
14464 /*
14465 ** A cursor is a pointer into a single BTree within a database file.
14466 ** The cursor can seek to a BTree entry with a particular key, or
14467 ** loop over all entries of the Btree.  You can also insert new BTree
14468 ** entries or retrieve the key or data from the entry that the cursor
14469 ** is currently pointing to.
14470 **
14471 ** Cursors can also point to virtual tables, sorters, or "pseudo-tables".
14472 ** A pseudo-table is a single-row table implemented by registers.
14473 ** 
14474 ** Every cursor that the virtual machine has open is represented by an
14475 ** instance of the following structure.
14476 */
14477 struct VdbeCursor {
14478   BtCursor *pCursor;    /* The cursor structure of the backend */
14479   Btree *pBt;           /* Separate file holding temporary table */
14480   KeyInfo *pKeyInfo;    /* Info about index keys needed by index cursors */
14481   int seekResult;       /* Result of previous sqlite3BtreeMoveto() */
14482   int pseudoTableReg;   /* Register holding pseudotable content. */
14483   i16 nField;           /* Number of fields in the header */
14484   u16 nHdrParsed;       /* Number of header fields parsed so far */
14485 #ifdef SQLITE_DEBUG
14486   u8 seekOp;            /* Most recent seek operation on this cursor */
14487 #endif
14488   i8 iDb;               /* Index of cursor database in db->aDb[] (or -1) */
14489   u8 nullRow;           /* True if pointing to a row with no data */
14490   u8 deferredMoveto;    /* A call to sqlite3BtreeMoveto() is needed */
14491   Bool isEphemeral:1;   /* True for an ephemeral table */
14492   Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
14493   Bool isTable:1;       /* True if a table requiring integer keys */
14494   Bool isOrdered:1;     /* True if the underlying table is BTREE_UNORDERED */
14495   Pgno pgnoRoot;        /* Root page of the open btree cursor */
14496   sqlite3_vtab_cursor *pVtabCursor;  /* The cursor for a virtual table */
14497   i64 seqCount;         /* Sequence counter */
14498   i64 movetoTarget;     /* Argument to the deferred sqlite3BtreeMoveto() */
14499   VdbeSorter *pSorter;  /* Sorter object for OP_SorterOpen cursors */
14500
14501   /* Cached information about the header for the data record that the
14502   ** cursor is currently pointing to.  Only valid if cacheStatus matches
14503   ** Vdbe.cacheCtr.  Vdbe.cacheCtr will never take on the value of
14504   ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
14505   ** the cache is out of date.
14506   **
14507   ** aRow might point to (ephemeral) data for the current row, or it might
14508   ** be NULL.
14509   */
14510   u32 cacheStatus;      /* Cache is valid if this matches Vdbe.cacheCtr */
14511   u32 payloadSize;      /* Total number of bytes in the record */
14512   u32 szRow;            /* Byte available in aRow */
14513   u32 iHdrOffset;       /* Offset to next unparsed byte of the header */
14514   const u8 *aRow;       /* Data for the current row, if all on one page */
14515   u32 *aOffset;         /* Pointer to aType[nField] */
14516   u32 aType[1];         /* Type values for all entries in the record */
14517   /* 2*nField extra array elements allocated for aType[], beyond the one
14518   ** static element declared in the structure.  nField total array slots for
14519   ** aType[] and nField+1 array slots for aOffset[] */
14520 };
14521 typedef struct VdbeCursor VdbeCursor;
14522
14523 /*
14524 ** When a sub-program is executed (OP_Program), a structure of this type
14525 ** is allocated to store the current value of the program counter, as
14526 ** well as the current memory cell array and various other frame specific
14527 ** values stored in the Vdbe struct. When the sub-program is finished, 
14528 ** these values are copied back to the Vdbe from the VdbeFrame structure,
14529 ** restoring the state of the VM to as it was before the sub-program
14530 ** began executing.
14531 **
14532 ** The memory for a VdbeFrame object is allocated and managed by a memory
14533 ** cell in the parent (calling) frame. When the memory cell is deleted or
14534 ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
14535 ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
14536 ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
14537 ** this instead of deleting the VdbeFrame immediately is to avoid recursive
14538 ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
14539 ** child frame are released.
14540 **
14541 ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
14542 ** set to NULL if the currently executing frame is the main program.
14543 */
14544 typedef struct VdbeFrame VdbeFrame;
14545 struct VdbeFrame {
14546   Vdbe *v;                /* VM this frame belongs to */
14547   VdbeFrame *pParent;     /* Parent of this frame, or NULL if parent is main */
14548   Op *aOp;                /* Program instructions for parent frame */
14549   i64 *anExec;            /* Event counters from parent frame */
14550   Mem *aMem;              /* Array of memory cells for parent frame */
14551   u8 *aOnceFlag;          /* Array of OP_Once flags for parent frame */
14552   VdbeCursor **apCsr;     /* Array of Vdbe cursors for parent frame */
14553   void *token;            /* Copy of SubProgram.token */
14554   i64 lastRowid;          /* Last insert rowid (sqlite3.lastRowid) */
14555   int nCursor;            /* Number of entries in apCsr */
14556   int pc;                 /* Program Counter in parent (calling) frame */
14557   int nOp;                /* Size of aOp array */
14558   int nMem;               /* Number of entries in aMem */
14559   int nOnceFlag;          /* Number of entries in aOnceFlag */
14560   int nChildMem;          /* Number of memory cells for child frame */
14561   int nChildCsr;          /* Number of cursors for child frame */
14562   int nChange;            /* Statement changes (Vdbe.nChange)     */
14563   int nDbChange;          /* Value of db->nChange */
14564 };
14565
14566 #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
14567
14568 /*
14569 ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
14570 */
14571 #define CACHE_STALE 0
14572
14573 /*
14574 ** Internally, the vdbe manipulates nearly all SQL values as Mem
14575 ** structures. Each Mem struct may cache multiple representations (string,
14576 ** integer etc.) of the same value.
14577 */
14578 struct Mem {
14579   union MemValue {
14580     double r;           /* Real value used when MEM_Real is set in flags */
14581     i64 i;              /* Integer value used when MEM_Int is set in flags */
14582     int nZero;          /* Used when bit MEM_Zero is set in flags */
14583     FuncDef *pDef;      /* Used only when flags==MEM_Agg */
14584     RowSet *pRowSet;    /* Used only when flags==MEM_RowSet */
14585     VdbeFrame *pFrame;  /* Used when flags==MEM_Frame */
14586   } u;
14587   u16 flags;          /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
14588   u8  enc;            /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
14589   int n;              /* Number of characters in string value, excluding '\0' */
14590   char *z;            /* String or BLOB value */
14591   /* ShallowCopy only needs to copy the information above */
14592   char *zMalloc;      /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
14593   int szMalloc;       /* Size of the zMalloc allocation */
14594   u32 uTemp;          /* Transient storage for serial_type in OP_MakeRecord */
14595   sqlite3 *db;        /* The associated database connection */
14596   void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
14597 #ifdef SQLITE_DEBUG
14598   Mem *pScopyFrom;    /* This Mem is a shallow copy of pScopyFrom */
14599   void *pFiller;      /* So that sizeof(Mem) is a multiple of 8 */
14600 #endif
14601 };
14602
14603 /* One or more of the following flags are set to indicate the validOK
14604 ** representations of the value stored in the Mem struct.
14605 **
14606 ** If the MEM_Null flag is set, then the value is an SQL NULL value.
14607 ** No other flags may be set in this case.
14608 **
14609 ** If the MEM_Str flag is set then Mem.z points at a string representation.
14610 ** Usually this is encoded in the same unicode encoding as the main
14611 ** database (see below for exceptions). If the MEM_Term flag is also
14612 ** set, then the string is nul terminated. The MEM_Int and MEM_Real 
14613 ** flags may coexist with the MEM_Str flag.
14614 */
14615 #define MEM_Null      0x0001   /* Value is NULL */
14616 #define MEM_Str       0x0002   /* Value is a string */
14617 #define MEM_Int       0x0004   /* Value is an integer */
14618 #define MEM_Real      0x0008   /* Value is a real number */
14619 #define MEM_Blob      0x0010   /* Value is a BLOB */
14620 #define MEM_AffMask   0x001f   /* Mask of affinity bits */
14621 #define MEM_RowSet    0x0020   /* Value is a RowSet object */
14622 #define MEM_Frame     0x0040   /* Value is a VdbeFrame object */
14623 #define MEM_Undefined 0x0080   /* Value is undefined */
14624 #define MEM_Cleared   0x0100   /* NULL set by OP_Null, not from data */
14625 #define MEM_TypeMask  0x01ff   /* Mask of type bits */
14626
14627
14628 /* Whenever Mem contains a valid string or blob representation, one of
14629 ** the following flags must be set to determine the memory management
14630 ** policy for Mem.z.  The MEM_Term flag tells us whether or not the
14631 ** string is \000 or \u0000 terminated
14632 */
14633 #define MEM_Term      0x0200   /* String rep is nul terminated */
14634 #define MEM_Dyn       0x0400   /* Need to call Mem.xDel() on Mem.z */
14635 #define MEM_Static    0x0800   /* Mem.z points to a static string */
14636 #define MEM_Ephem     0x1000   /* Mem.z points to an ephemeral string */
14637 #define MEM_Agg       0x2000   /* Mem.z points to an agg function context */
14638 #define MEM_Zero      0x4000   /* Mem.i contains count of 0s appended to blob */
14639 #ifdef SQLITE_OMIT_INCRBLOB
14640   #undef MEM_Zero
14641   #define MEM_Zero 0x0000
14642 #endif
14643
14644 /*
14645 ** Clear any existing type flags from a Mem and replace them with f
14646 */
14647 #define MemSetTypeFlag(p, f) \
14648    ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
14649
14650 /*
14651 ** Return true if a memory cell is not marked as invalid.  This macro
14652 ** is for use inside assert() statements only.
14653 */
14654 #ifdef SQLITE_DEBUG
14655 #define memIsValid(M)  ((M)->flags & MEM_Undefined)==0
14656 #endif
14657
14658 /*
14659 ** Each auxiliary data pointer stored by a user defined function 
14660 ** implementation calling sqlite3_set_auxdata() is stored in an instance
14661 ** of this structure. All such structures associated with a single VM
14662 ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
14663 ** when the VM is halted (if not before).
14664 */
14665 struct AuxData {
14666   int iOp;                        /* Instruction number of OP_Function opcode */
14667   int iArg;                       /* Index of function argument. */
14668   void *pAux;                     /* Aux data pointer */
14669   void (*xDelete)(void *);        /* Destructor for the aux data */
14670   AuxData *pNext;                 /* Next element in list */
14671 };
14672
14673 /*
14674 ** The "context" argument for an installable function.  A pointer to an
14675 ** instance of this structure is the first argument to the routines used
14676 ** implement the SQL functions.
14677 **
14678 ** There is a typedef for this structure in sqlite.h.  So all routines,
14679 ** even the public interface to SQLite, can use a pointer to this structure.
14680 ** But this file is the only place where the internal details of this
14681 ** structure are known.
14682 **
14683 ** This structure is defined inside of vdbeInt.h because it uses substructures
14684 ** (Mem) which are only defined there.
14685 */
14686 struct sqlite3_context {
14687   Mem *pOut;            /* The return value is stored here */
14688   FuncDef *pFunc;       /* Pointer to function information */
14689   Mem *pMem;            /* Memory cell used to store aggregate context */
14690   Vdbe *pVdbe;          /* The VM that owns this context */
14691   int iOp;              /* Instruction number of OP_Function */
14692   int isError;          /* Error code returned by the function. */
14693   u8 skipFlag;          /* Skip accumulator loading if true */
14694   u8 fErrorOrAux;       /* isError!=0 or pVdbe->pAuxData modified */
14695 };
14696
14697 /*
14698 ** An Explain object accumulates indented output which is helpful
14699 ** in describing recursive data structures.
14700 */
14701 struct Explain {
14702   Vdbe *pVdbe;       /* Attach the explanation to this Vdbe */
14703   StrAccum str;      /* The string being accumulated */
14704   int nIndent;       /* Number of elements in aIndent */
14705   u16 aIndent[100];  /* Levels of indentation */
14706   char zBase[100];   /* Initial space */
14707 };
14708
14709 /* A bitfield type for use inside of structures.  Always follow with :N where
14710 ** N is the number of bits.
14711 */
14712 typedef unsigned bft;  /* Bit Field Type */
14713
14714 typedef struct ScanStatus ScanStatus;
14715 struct ScanStatus {
14716   int addrExplain;                /* OP_Explain for loop */
14717   int addrLoop;                   /* Address of "loops" counter */
14718   int addrVisit;                  /* Address of "rows visited" counter */
14719   int iSelectID;                  /* The "Select-ID" for this loop */
14720   LogEst nEst;                    /* Estimated output rows per loop */
14721   char *zName;                    /* Name of table or index */
14722 };
14723
14724 /*
14725 ** An instance of the virtual machine.  This structure contains the complete
14726 ** state of the virtual machine.
14727 **
14728 ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
14729 ** is really a pointer to an instance of this structure.
14730 */
14731 struct Vdbe {
14732   sqlite3 *db;            /* The database connection that owns this statement */
14733   Op *aOp;                /* Space to hold the virtual machine's program */
14734   Mem *aMem;              /* The memory locations */
14735   Mem **apArg;            /* Arguments to currently executing user function */
14736   Mem *aColName;          /* Column names to return */
14737   Mem *pResultSet;        /* Pointer to an array of results */
14738   Parse *pParse;          /* Parsing context used to create this Vdbe */
14739   int nMem;               /* Number of memory locations currently allocated */
14740   int nOp;                /* Number of instructions in the program */
14741   int nCursor;            /* Number of slots in apCsr[] */
14742   u32 magic;              /* Magic number for sanity checking */
14743   char *zErrMsg;          /* Error message written here */
14744   Vdbe *pPrev,*pNext;     /* Linked list of VDBEs with the same Vdbe.db */
14745   VdbeCursor **apCsr;     /* One element of this array for each open cursor */
14746   Mem *aVar;              /* Values for the OP_Variable opcode. */
14747   char **azVar;           /* Name of variables */
14748   ynVar nVar;             /* Number of entries in aVar[] */
14749   ynVar nzVar;            /* Number of entries in azVar[] */
14750   u32 cacheCtr;           /* VdbeCursor row cache generation counter */
14751   int pc;                 /* The program counter */
14752   int rc;                 /* Value to return */
14753 #ifdef SQLITE_DEBUG
14754   int rcApp;              /* errcode set by sqlite3_result_error_code() */
14755 #endif
14756   u16 nResColumn;         /* Number of columns in one row of the result set */
14757   u8 errorAction;         /* Recovery action to do in case of an error */
14758   u8 minWriteFileFormat;  /* Minimum file format for writable database files */
14759   bft explain:2;          /* True if EXPLAIN present on SQL command */
14760   bft changeCntOn:1;      /* True to update the change-counter */
14761   bft expired:1;          /* True if the VM needs to be recompiled */
14762   bft runOnlyOnce:1;      /* Automatically expire on reset */
14763   bft usesStmtJournal:1;  /* True if uses a statement journal */
14764   bft readOnly:1;         /* True for statements that do not write */
14765   bft bIsReader:1;        /* True for statements that read */
14766   bft isPrepareV2:1;      /* True if prepared with prepare_v2() */
14767   bft doingRerun:1;       /* True if rerunning after an auto-reprepare */
14768   int nChange;            /* Number of db changes made since last reset */
14769   yDbMask btreeMask;      /* Bitmask of db->aDb[] entries referenced */
14770   yDbMask lockMask;       /* Subset of btreeMask that requires a lock */
14771   int iStatement;         /* Statement number (or 0 if has not opened stmt) */
14772   u32 aCounter[5];        /* Counters used by sqlite3_stmt_status() */
14773 #ifndef SQLITE_OMIT_TRACE
14774   i64 startTime;          /* Time when query started - used for profiling */
14775 #endif
14776   i64 iCurrentTime;       /* Value of julianday('now') for this statement */
14777   i64 nFkConstraint;      /* Number of imm. FK constraints this VM */
14778   i64 nStmtDefCons;       /* Number of def. constraints when stmt started */
14779   i64 nStmtDefImmCons;    /* Number of def. imm constraints when stmt started */
14780   char *zSql;             /* Text of the SQL statement that generated this */
14781   void *pFree;            /* Free this when deleting the vdbe */
14782   VdbeFrame *pFrame;      /* Parent frame */
14783   VdbeFrame *pDelFrame;   /* List of frame objects to free on VM reset */
14784   int nFrame;             /* Number of frames in pFrame list */
14785   u32 expmask;            /* Binding to these vars invalidates VM */
14786   SubProgram *pProgram;   /* Linked list of all sub-programs used by VM */
14787   int nOnceFlag;          /* Size of array aOnceFlag[] */
14788   u8 *aOnceFlag;          /* Flags for OP_Once */
14789   AuxData *pAuxData;      /* Linked list of auxdata allocations */
14790 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
14791   i64 *anExec;            /* Number of times each op has been executed */
14792   int nScan;              /* Entries in aScan[] */
14793   ScanStatus *aScan;      /* Scan definitions for sqlite3_stmt_scanstatus() */
14794 #endif
14795 };
14796
14797 /*
14798 ** The following are allowed values for Vdbe.magic
14799 */
14800 #define VDBE_MAGIC_INIT     0x26bceaa5    /* Building a VDBE program */
14801 #define VDBE_MAGIC_RUN      0xbdf20da3    /* VDBE is ready to execute */
14802 #define VDBE_MAGIC_HALT     0x519c2973    /* VDBE has completed execution */
14803 #define VDBE_MAGIC_DEAD     0xb606c3c8    /* The VDBE has been deallocated */
14804
14805 /*
14806 ** Function prototypes
14807 */
14808 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
14809 void sqliteVdbePopStack(Vdbe*,int);
14810 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
14811 SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
14812 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
14813 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
14814 #endif
14815 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
14816 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
14817 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
14818 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
14819 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
14820
14821 int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
14822 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
14823 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
14824 SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
14825 SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
14826 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
14827 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
14828 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
14829 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
14830 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
14831 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
14832 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
14833 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
14834 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
14835 #ifdef SQLITE_OMIT_FLOATING_POINT
14836 # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
14837 #else
14838 SQLITE_PRIVATE   void sqlite3VdbeMemSetDouble(Mem*, double);
14839 #endif
14840 SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
14841 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
14842 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
14843 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
14844 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
14845 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
14846 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
14847 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
14848 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
14849 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
14850 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
14851 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
14852 SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
14853 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*);
14854 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
14855 #define VdbeMemDynamic(X)  \
14856   (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
14857 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
14858 SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
14859 SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
14860 SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
14861 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
14862 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
14863 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
14864 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
14865
14866 SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
14867 SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
14868 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
14869 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
14870 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
14871 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
14872 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
14873 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
14874
14875 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
14876 SQLITE_PRIVATE   void sqlite3VdbeEnter(Vdbe*);
14877 SQLITE_PRIVATE   void sqlite3VdbeLeave(Vdbe*);
14878 #else
14879 # define sqlite3VdbeEnter(X)
14880 # define sqlite3VdbeLeave(X)
14881 #endif
14882
14883 #ifdef SQLITE_DEBUG
14884 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
14885 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
14886 #endif
14887
14888 #ifndef SQLITE_OMIT_FOREIGN_KEY
14889 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
14890 #else
14891 # define sqlite3VdbeCheckFk(p,i) 0
14892 #endif
14893
14894 SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
14895 #ifdef SQLITE_DEBUG
14896 SQLITE_PRIVATE   void sqlite3VdbePrintSql(Vdbe*);
14897 SQLITE_PRIVATE   void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
14898 #endif
14899 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
14900
14901 #ifndef SQLITE_OMIT_INCRBLOB
14902 SQLITE_PRIVATE   int sqlite3VdbeMemExpandBlob(Mem *);
14903   #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
14904 #else
14905   #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
14906   #define ExpandBlob(P) SQLITE_OK
14907 #endif
14908
14909 #endif /* !defined(_VDBEINT_H_) */
14910
14911 /************** End of vdbeInt.h *********************************************/
14912 /************** Continuing where we left off in status.c *********************/
14913
14914 /*
14915 ** Variables in which to record status information.
14916 */
14917 typedef struct sqlite3StatType sqlite3StatType;
14918 static SQLITE_WSD struct sqlite3StatType {
14919 #if SQLITE_PTRSIZE>4
14920   sqlite3_int64 nowValue[10];         /* Current value */
14921   sqlite3_int64 mxValue[10];          /* Maximum value */
14922 #else
14923   u32 nowValue[10];                   /* Current value */
14924   u32 mxValue[10];                    /* Maximum value */
14925 #endif
14926 } sqlite3Stat = { {0,}, {0,} };
14927
14928 /*
14929 ** Elements of sqlite3Stat[] are protected by either the memory allocator
14930 ** mutex, or by the pcache1 mutex.  The following array determines which.
14931 */
14932 static const char statMutex[] = {
14933   0,  /* SQLITE_STATUS_MEMORY_USED */
14934   1,  /* SQLITE_STATUS_PAGECACHE_USED */
14935   1,  /* SQLITE_STATUS_PAGECACHE_OVERFLOW */
14936   0,  /* SQLITE_STATUS_SCRATCH_USED */
14937   0,  /* SQLITE_STATUS_SCRATCH_OVERFLOW */
14938   0,  /* SQLITE_STATUS_MALLOC_SIZE */
14939   0,  /* SQLITE_STATUS_PARSER_STACK */
14940   1,  /* SQLITE_STATUS_PAGECACHE_SIZE */
14941   0,  /* SQLITE_STATUS_SCRATCH_SIZE */
14942   0,  /* SQLITE_STATUS_MALLOC_COUNT */
14943 };
14944
14945
14946 /* The "wsdStat" macro will resolve to the status information
14947 ** state vector.  If writable static data is unsupported on the target,
14948 ** we have to locate the state vector at run-time.  In the more common
14949 ** case where writable static data is supported, wsdStat can refer directly
14950 ** to the "sqlite3Stat" state vector declared above.
14951 */
14952 #ifdef SQLITE_OMIT_WSD
14953 # define wsdStatInit  sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
14954 # define wsdStat x[0]
14955 #else
14956 # define wsdStatInit
14957 # define wsdStat sqlite3Stat
14958 #endif
14959
14960 /*
14961 ** Return the current value of a status parameter.  The caller must
14962 ** be holding the appropriate mutex.
14963 */
14964 SQLITE_PRIVATE sqlite3_int64 sqlite3StatusValue(int op){
14965   wsdStatInit;
14966   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
14967   assert( op>=0 && op<ArraySize(statMutex) );
14968   assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
14969                                            : sqlite3MallocMutex()) );
14970   return wsdStat.nowValue[op];
14971 }
14972
14973 /*
14974 ** Add N to the value of a status record.  The caller must hold the
14975 ** appropriate mutex.  (Locking is checked by assert()).
14976 **
14977 ** The StatusUp() routine can accept positive or negative values for N.
14978 ** The value of N is added to the current status value and the high-water
14979 ** mark is adjusted if necessary.
14980 **
14981 ** The StatusDown() routine lowers the current value by N.  The highwater
14982 ** mark is unchanged.  N must be non-negative for StatusDown().
14983 */
14984 SQLITE_PRIVATE void sqlite3StatusUp(int op, int N){
14985   wsdStatInit;
14986   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
14987   assert( op>=0 && op<ArraySize(statMutex) );
14988   assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
14989                                            : sqlite3MallocMutex()) );
14990   wsdStat.nowValue[op] += N;
14991   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
14992     wsdStat.mxValue[op] = wsdStat.nowValue[op];
14993   }
14994 }
14995 SQLITE_PRIVATE void sqlite3StatusDown(int op, int N){
14996   wsdStatInit;
14997   assert( N>=0 );
14998   assert( op>=0 && op<ArraySize(statMutex) );
14999   assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
15000                                            : sqlite3MallocMutex()) );
15001   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
15002   wsdStat.nowValue[op] -= N;
15003 }
15004
15005 /*
15006 ** Set the value of a status to X.  The highwater mark is adjusted if
15007 ** necessary.  The caller must hold the appropriate mutex.
15008 */
15009 SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
15010   wsdStatInit;
15011   assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
15012   assert( op>=0 && op<ArraySize(statMutex) );
15013   assert( sqlite3_mutex_held(statMutex[op] ? sqlite3Pcache1Mutex()
15014                                            : sqlite3MallocMutex()) );
15015   wsdStat.nowValue[op] = X;
15016   if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
15017     wsdStat.mxValue[op] = wsdStat.nowValue[op];
15018   }
15019 }
15020
15021 /*
15022 ** Query status information.
15023 */
15024 SQLITE_API int SQLITE_STDCALL sqlite3_status64(
15025   int op,
15026   sqlite3_int64 *pCurrent,
15027   sqlite3_int64 *pHighwater,
15028   int resetFlag
15029 ){
15030   sqlite3_mutex *pMutex;
15031   wsdStatInit;
15032   if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
15033     return SQLITE_MISUSE_BKPT;
15034   }
15035 #ifdef SQLITE_ENABLE_API_ARMOR
15036   if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
15037 #endif
15038   pMutex = statMutex[op] ? sqlite3Pcache1Mutex() : sqlite3MallocMutex();
15039   sqlite3_mutex_enter(pMutex);
15040   *pCurrent = wsdStat.nowValue[op];
15041   *pHighwater = wsdStat.mxValue[op];
15042   if( resetFlag ){
15043     wsdStat.mxValue[op] = wsdStat.nowValue[op];
15044   }
15045   sqlite3_mutex_leave(pMutex);
15046   (void)pMutex;  /* Prevent warning when SQLITE_THREADSAFE=0 */
15047   return SQLITE_OK;
15048 }
15049 SQLITE_API int SQLITE_STDCALL sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
15050   sqlite3_int64 iCur, iHwtr;
15051   int rc;
15052 #ifdef SQLITE_ENABLE_API_ARMOR
15053   if( pCurrent==0 || pHighwater==0 ) return SQLITE_MISUSE_BKPT;
15054 #endif
15055   rc = sqlite3_status64(op, &iCur, &iHwtr, resetFlag);
15056   if( rc==0 ){
15057     *pCurrent = (int)iCur;
15058     *pHighwater = (int)iHwtr;
15059   }
15060   return rc;
15061 }
15062
15063 /*
15064 ** Query status information for a single database connection
15065 */
15066 SQLITE_API int SQLITE_STDCALL sqlite3_db_status(
15067   sqlite3 *db,          /* The database connection whose status is desired */
15068   int op,               /* Status verb */
15069   int *pCurrent,        /* Write current value here */
15070   int *pHighwater,      /* Write high-water mark here */
15071   int resetFlag         /* Reset high-water mark if true */
15072 ){
15073   int rc = SQLITE_OK;   /* Return code */
15074 #ifdef SQLITE_ENABLE_API_ARMOR
15075   if( !sqlite3SafetyCheckOk(db) || pCurrent==0|| pHighwater==0 ){
15076     return SQLITE_MISUSE_BKPT;
15077   }
15078 #endif
15079   sqlite3_mutex_enter(db->mutex);
15080   switch( op ){
15081     case SQLITE_DBSTATUS_LOOKASIDE_USED: {
15082       *pCurrent = db->lookaside.nOut;
15083       *pHighwater = db->lookaside.mxOut;
15084       if( resetFlag ){
15085         db->lookaside.mxOut = db->lookaside.nOut;
15086       }
15087       break;
15088     }
15089
15090     case SQLITE_DBSTATUS_LOOKASIDE_HIT:
15091     case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
15092     case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
15093       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
15094       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
15095       testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
15096       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
15097       assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
15098       *pCurrent = 0;
15099       *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
15100       if( resetFlag ){
15101         db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
15102       }
15103       break;
15104     }
15105
15106     /* 
15107     ** Return an approximation for the amount of memory currently used
15108     ** by all pagers associated with the given database connection.  The
15109     ** highwater mark is meaningless and is returned as zero.
15110     */
15111     case SQLITE_DBSTATUS_CACHE_USED: {
15112       int totalUsed = 0;
15113       int i;
15114       sqlite3BtreeEnterAll(db);
15115       for(i=0; i<db->nDb; i++){
15116         Btree *pBt = db->aDb[i].pBt;
15117         if( pBt ){
15118           Pager *pPager = sqlite3BtreePager(pBt);
15119           totalUsed += sqlite3PagerMemUsed(pPager);
15120         }
15121       }
15122       sqlite3BtreeLeaveAll(db);
15123       *pCurrent = totalUsed;
15124       *pHighwater = 0;
15125       break;
15126     }
15127
15128     /*
15129     ** *pCurrent gets an accurate estimate of the amount of memory used
15130     ** to store the schema for all databases (main, temp, and any ATTACHed
15131     ** databases.  *pHighwater is set to zero.
15132     */
15133     case SQLITE_DBSTATUS_SCHEMA_USED: {
15134       int i;                      /* Used to iterate through schemas */
15135       int nByte = 0;              /* Used to accumulate return value */
15136
15137       sqlite3BtreeEnterAll(db);
15138       db->pnBytesFreed = &nByte;
15139       for(i=0; i<db->nDb; i++){
15140         Schema *pSchema = db->aDb[i].pSchema;
15141         if( ALWAYS(pSchema!=0) ){
15142           HashElem *p;
15143
15144           nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
15145               pSchema->tblHash.count 
15146             + pSchema->trigHash.count
15147             + pSchema->idxHash.count
15148             + pSchema->fkeyHash.count
15149           );
15150           nByte += sqlite3MallocSize(pSchema->tblHash.ht);
15151           nByte += sqlite3MallocSize(pSchema->trigHash.ht);
15152           nByte += sqlite3MallocSize(pSchema->idxHash.ht);
15153           nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
15154
15155           for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
15156             sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
15157           }
15158           for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
15159             sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
15160           }
15161         }
15162       }
15163       db->pnBytesFreed = 0;
15164       sqlite3BtreeLeaveAll(db);
15165
15166       *pHighwater = 0;
15167       *pCurrent = nByte;
15168       break;
15169     }
15170
15171     /*
15172     ** *pCurrent gets an accurate estimate of the amount of memory used
15173     ** to store all prepared statements.
15174     ** *pHighwater is set to zero.
15175     */
15176     case SQLITE_DBSTATUS_STMT_USED: {
15177       struct Vdbe *pVdbe;         /* Used to iterate through VMs */
15178       int nByte = 0;              /* Used to accumulate return value */
15179
15180       db->pnBytesFreed = &nByte;
15181       for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
15182         sqlite3VdbeClearObject(db, pVdbe);
15183         sqlite3DbFree(db, pVdbe);
15184       }
15185       db->pnBytesFreed = 0;
15186
15187       *pHighwater = 0;  /* IMP: R-64479-57858 */
15188       *pCurrent = nByte;
15189
15190       break;
15191     }
15192
15193     /*
15194     ** Set *pCurrent to the total cache hits or misses encountered by all
15195     ** pagers the database handle is connected to. *pHighwater is always set 
15196     ** to zero.
15197     */
15198     case SQLITE_DBSTATUS_CACHE_HIT:
15199     case SQLITE_DBSTATUS_CACHE_MISS:
15200     case SQLITE_DBSTATUS_CACHE_WRITE:{
15201       int i;
15202       int nRet = 0;
15203       assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
15204       assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
15205
15206       for(i=0; i<db->nDb; i++){
15207         if( db->aDb[i].pBt ){
15208           Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
15209           sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
15210         }
15211       }
15212       *pHighwater = 0; /* IMP: R-42420-56072 */
15213                        /* IMP: R-54100-20147 */
15214                        /* IMP: R-29431-39229 */
15215       *pCurrent = nRet;
15216       break;
15217     }
15218
15219     /* Set *pCurrent to non-zero if there are unresolved deferred foreign
15220     ** key constraints.  Set *pCurrent to zero if all foreign key constraints
15221     ** have been satisfied.  The *pHighwater is always set to zero.
15222     */
15223     case SQLITE_DBSTATUS_DEFERRED_FKS: {
15224       *pHighwater = 0;  /* IMP: R-11967-56545 */
15225       *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
15226       break;
15227     }
15228
15229     default: {
15230       rc = SQLITE_ERROR;
15231     }
15232   }
15233   sqlite3_mutex_leave(db->mutex);
15234   return rc;
15235 }
15236
15237 /************** End of status.c **********************************************/
15238 /************** Begin file date.c ********************************************/
15239 /*
15240 ** 2003 October 31
15241 **
15242 ** The author disclaims copyright to this source code.  In place of
15243 ** a legal notice, here is a blessing:
15244 **
15245 **    May you do good and not evil.
15246 **    May you find forgiveness for yourself and forgive others.
15247 **    May you share freely, never taking more than you give.
15248 **
15249 *************************************************************************
15250 ** This file contains the C functions that implement date and time
15251 ** functions for SQLite.  
15252 **
15253 ** There is only one exported symbol in this file - the function
15254 ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
15255 ** All other code has file scope.
15256 **
15257 ** SQLite processes all times and dates as julian day numbers.  The
15258 ** dates and times are stored as the number of days since noon
15259 ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
15260 ** calendar system. 
15261 **
15262 ** 1970-01-01 00:00:00 is JD 2440587.5
15263 ** 2000-01-01 00:00:00 is JD 2451544.5
15264 **
15265 ** This implementation requires years to be expressed as a 4-digit number
15266 ** which means that only dates between 0000-01-01 and 9999-12-31 can
15267 ** be represented, even though julian day numbers allow a much wider
15268 ** range of dates.
15269 **
15270 ** The Gregorian calendar system is used for all dates and times,
15271 ** even those that predate the Gregorian calendar.  Historians usually
15272 ** use the julian calendar for dates prior to 1582-10-15 and for some
15273 ** dates afterwards, depending on locale.  Beware of this difference.
15274 **
15275 ** The conversion algorithms are implemented based on descriptions
15276 ** in the following text:
15277 **
15278 **      Jean Meeus
15279 **      Astronomical Algorithms, 2nd Edition, 1998
15280 **      ISBM 0-943396-61-1
15281 **      Willmann-Bell, Inc
15282 **      Richmond, Virginia (USA)
15283 */
15284 /* #include <stdlib.h> */
15285 /* #include <assert.h> */
15286 #include <time.h>
15287
15288 #ifndef SQLITE_OMIT_DATETIME_FUNCS
15289
15290
15291 /*
15292 ** A structure for holding a single date and time.
15293 */
15294 typedef struct DateTime DateTime;
15295 struct DateTime {
15296   sqlite3_int64 iJD; /* The julian day number times 86400000 */
15297   int Y, M, D;       /* Year, month, and day */
15298   int h, m;          /* Hour and minutes */
15299   int tz;            /* Timezone offset in minutes */
15300   double s;          /* Seconds */
15301   char validYMD;     /* True (1) if Y,M,D are valid */
15302   char validHMS;     /* True (1) if h,m,s are valid */
15303   char validJD;      /* True (1) if iJD is valid */
15304   char validTZ;      /* True (1) if tz is valid */
15305 };
15306
15307
15308 /*
15309 ** Convert zDate into one or more integers.  Additional arguments
15310 ** come in groups of 5 as follows:
15311 **
15312 **       N       number of digits in the integer
15313 **       min     minimum allowed value of the integer
15314 **       max     maximum allowed value of the integer
15315 **       nextC   first character after the integer
15316 **       pVal    where to write the integers value.
15317 **
15318 ** Conversions continue until one with nextC==0 is encountered.
15319 ** The function returns the number of successful conversions.
15320 */
15321 static int getDigits(const char *zDate, ...){
15322   va_list ap;
15323   int val;
15324   int N;
15325   int min;
15326   int max;
15327   int nextC;
15328   int *pVal;
15329   int cnt = 0;
15330   va_start(ap, zDate);
15331   do{
15332     N = va_arg(ap, int);
15333     min = va_arg(ap, int);
15334     max = va_arg(ap, int);
15335     nextC = va_arg(ap, int);
15336     pVal = va_arg(ap, int*);
15337     val = 0;
15338     while( N-- ){
15339       if( !sqlite3Isdigit(*zDate) ){
15340         goto end_getDigits;
15341       }
15342       val = val*10 + *zDate - '0';
15343       zDate++;
15344     }
15345     if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
15346       goto end_getDigits;
15347     }
15348     *pVal = val;
15349     zDate++;
15350     cnt++;
15351   }while( nextC );
15352 end_getDigits:
15353   va_end(ap);
15354   return cnt;
15355 }
15356
15357 /*
15358 ** Parse a timezone extension on the end of a date-time.
15359 ** The extension is of the form:
15360 **
15361 **        (+/-)HH:MM
15362 **
15363 ** Or the "zulu" notation:
15364 **
15365 **        Z
15366 **
15367 ** If the parse is successful, write the number of minutes
15368 ** of change in p->tz and return 0.  If a parser error occurs,
15369 ** return non-zero.
15370 **
15371 ** A missing specifier is not considered an error.
15372 */
15373 static int parseTimezone(const char *zDate, DateTime *p){
15374   int sgn = 0;
15375   int nHr, nMn;
15376   int c;
15377   while( sqlite3Isspace(*zDate) ){ zDate++; }
15378   p->tz = 0;
15379   c = *zDate;
15380   if( c=='-' ){
15381     sgn = -1;
15382   }else if( c=='+' ){
15383     sgn = +1;
15384   }else if( c=='Z' || c=='z' ){
15385     zDate++;
15386     goto zulu_time;
15387   }else{
15388     return c!=0;
15389   }
15390   zDate++;
15391   if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
15392     return 1;
15393   }
15394   zDate += 5;
15395   p->tz = sgn*(nMn + nHr*60);
15396 zulu_time:
15397   while( sqlite3Isspace(*zDate) ){ zDate++; }
15398   return *zDate!=0;
15399 }
15400
15401 /*
15402 ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
15403 ** The HH, MM, and SS must each be exactly 2 digits.  The
15404 ** fractional seconds FFFF can be one or more digits.
15405 **
15406 ** Return 1 if there is a parsing error and 0 on success.
15407 */
15408 static int parseHhMmSs(const char *zDate, DateTime *p){
15409   int h, m, s;
15410   double ms = 0.0;
15411   if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
15412     return 1;
15413   }
15414   zDate += 5;
15415   if( *zDate==':' ){
15416     zDate++;
15417     if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
15418       return 1;
15419     }
15420     zDate += 2;
15421     if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
15422       double rScale = 1.0;
15423       zDate++;
15424       while( sqlite3Isdigit(*zDate) ){
15425         ms = ms*10.0 + *zDate - '0';
15426         rScale *= 10.0;
15427         zDate++;
15428       }
15429       ms /= rScale;
15430     }
15431   }else{
15432     s = 0;
15433   }
15434   p->validJD = 0;
15435   p->validHMS = 1;
15436   p->h = h;
15437   p->m = m;
15438   p->s = s + ms;
15439   if( parseTimezone(zDate, p) ) return 1;
15440   p->validTZ = (p->tz!=0)?1:0;
15441   return 0;
15442 }
15443
15444 /*
15445 ** Convert from YYYY-MM-DD HH:MM:SS to julian day.  We always assume
15446 ** that the YYYY-MM-DD is according to the Gregorian calendar.
15447 **
15448 ** Reference:  Meeus page 61
15449 */
15450 static void computeJD(DateTime *p){
15451   int Y, M, D, A, B, X1, X2;
15452
15453   if( p->validJD ) return;
15454   if( p->validYMD ){
15455     Y = p->Y;
15456     M = p->M;
15457     D = p->D;
15458   }else{
15459     Y = 2000;  /* If no YMD specified, assume 2000-Jan-01 */
15460     M = 1;
15461     D = 1;
15462   }
15463   if( M<=2 ){
15464     Y--;
15465     M += 12;
15466   }
15467   A = Y/100;
15468   B = 2 - A + (A/4);
15469   X1 = 36525*(Y+4716)/100;
15470   X2 = 306001*(M+1)/10000;
15471   p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
15472   p->validJD = 1;
15473   if( p->validHMS ){
15474     p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
15475     if( p->validTZ ){
15476       p->iJD -= p->tz*60000;
15477       p->validYMD = 0;
15478       p->validHMS = 0;
15479       p->validTZ = 0;
15480     }
15481   }
15482 }
15483
15484 /*
15485 ** Parse dates of the form
15486 **
15487 **     YYYY-MM-DD HH:MM:SS.FFF
15488 **     YYYY-MM-DD HH:MM:SS
15489 **     YYYY-MM-DD HH:MM
15490 **     YYYY-MM-DD
15491 **
15492 ** Write the result into the DateTime structure and return 0
15493 ** on success and 1 if the input string is not a well-formed
15494 ** date.
15495 */
15496 static int parseYyyyMmDd(const char *zDate, DateTime *p){
15497   int Y, M, D, neg;
15498
15499   if( zDate[0]=='-' ){
15500     zDate++;
15501     neg = 1;
15502   }else{
15503     neg = 0;
15504   }
15505   if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
15506     return 1;
15507   }
15508   zDate += 10;
15509   while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
15510   if( parseHhMmSs(zDate, p)==0 ){
15511     /* We got the time */
15512   }else if( *zDate==0 ){
15513     p->validHMS = 0;
15514   }else{
15515     return 1;
15516   }
15517   p->validJD = 0;
15518   p->validYMD = 1;
15519   p->Y = neg ? -Y : Y;
15520   p->M = M;
15521   p->D = D;
15522   if( p->validTZ ){
15523     computeJD(p);
15524   }
15525   return 0;
15526 }
15527
15528 /*
15529 ** Set the time to the current time reported by the VFS.
15530 **
15531 ** Return the number of errors.
15532 */
15533 static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
15534   p->iJD = sqlite3StmtCurrentTime(context);
15535   if( p->iJD>0 ){
15536     p->validJD = 1;
15537     return 0;
15538   }else{
15539     return 1;
15540   }
15541 }
15542
15543 /*
15544 ** Attempt to parse the given string into a julian day number.  Return
15545 ** the number of errors.
15546 **
15547 ** The following are acceptable forms for the input string:
15548 **
15549 **      YYYY-MM-DD HH:MM:SS.FFF  +/-HH:MM
15550 **      DDDD.DD 
15551 **      now
15552 **
15553 ** In the first form, the +/-HH:MM is always optional.  The fractional
15554 ** seconds extension (the ".FFF") is optional.  The seconds portion
15555 ** (":SS.FFF") is option.  The year and date can be omitted as long
15556 ** as there is a time string.  The time string can be omitted as long
15557 ** as there is a year and date.
15558 */
15559 static int parseDateOrTime(
15560   sqlite3_context *context, 
15561   const char *zDate, 
15562   DateTime *p
15563 ){
15564   double r;
15565   if( parseYyyyMmDd(zDate,p)==0 ){
15566     return 0;
15567   }else if( parseHhMmSs(zDate, p)==0 ){
15568     return 0;
15569   }else if( sqlite3StrICmp(zDate,"now")==0){
15570     return setDateTimeToCurrent(context, p);
15571   }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
15572     p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
15573     p->validJD = 1;
15574     return 0;
15575   }
15576   return 1;
15577 }
15578
15579 /*
15580 ** Compute the Year, Month, and Day from the julian day number.
15581 */
15582 static void computeYMD(DateTime *p){
15583   int Z, A, B, C, D, E, X1;
15584   if( p->validYMD ) return;
15585   if( !p->validJD ){
15586     p->Y = 2000;
15587     p->M = 1;
15588     p->D = 1;
15589   }else{
15590     Z = (int)((p->iJD + 43200000)/86400000);
15591     A = (int)((Z - 1867216.25)/36524.25);
15592     A = Z + 1 + A - (A/4);
15593     B = A + 1524;
15594     C = (int)((B - 122.1)/365.25);
15595     D = (36525*C)/100;
15596     E = (int)((B-D)/30.6001);
15597     X1 = (int)(30.6001*E);
15598     p->D = B - D - X1;
15599     p->M = E<14 ? E-1 : E-13;
15600     p->Y = p->M>2 ? C - 4716 : C - 4715;
15601   }
15602   p->validYMD = 1;
15603 }
15604
15605 /*
15606 ** Compute the Hour, Minute, and Seconds from the julian day number.
15607 */
15608 static void computeHMS(DateTime *p){
15609   int s;
15610   if( p->validHMS ) return;
15611   computeJD(p);
15612   s = (int)((p->iJD + 43200000) % 86400000);
15613   p->s = s/1000.0;
15614   s = (int)p->s;
15615   p->s -= s;
15616   p->h = s/3600;
15617   s -= p->h*3600;
15618   p->m = s/60;
15619   p->s += s - p->m*60;
15620   p->validHMS = 1;
15621 }
15622
15623 /*
15624 ** Compute both YMD and HMS
15625 */
15626 static void computeYMD_HMS(DateTime *p){
15627   computeYMD(p);
15628   computeHMS(p);
15629 }
15630
15631 /*
15632 ** Clear the YMD and HMS and the TZ
15633 */
15634 static void clearYMD_HMS_TZ(DateTime *p){
15635   p->validYMD = 0;
15636   p->validHMS = 0;
15637   p->validTZ = 0;
15638 }
15639
15640 /*
15641 ** On recent Windows platforms, the localtime_s() function is available
15642 ** as part of the "Secure CRT". It is essentially equivalent to 
15643 ** localtime_r() available under most POSIX platforms, except that the 
15644 ** order of the parameters is reversed.
15645 **
15646 ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
15647 **
15648 ** If the user has not indicated to use localtime_r() or localtime_s()
15649 ** already, check for an MSVC build environment that provides 
15650 ** localtime_s().
15651 */
15652 #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S \
15653     && defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
15654 #undef  HAVE_LOCALTIME_S
15655 #define HAVE_LOCALTIME_S 1
15656 #endif
15657
15658 #ifndef SQLITE_OMIT_LOCALTIME
15659 /*
15660 ** The following routine implements the rough equivalent of localtime_r()
15661 ** using whatever operating-system specific localtime facility that
15662 ** is available.  This routine returns 0 on success and
15663 ** non-zero on any kind of error.
15664 **
15665 ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
15666 ** routine will always fail.
15667 **
15668 ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
15669 ** library function localtime_r() is used to assist in the calculation of
15670 ** local time.
15671 */
15672 static int osLocaltime(time_t *t, struct tm *pTm){
15673   int rc;
15674 #if !HAVE_LOCALTIME_R && !HAVE_LOCALTIME_S
15675   struct tm *pX;
15676 #if SQLITE_THREADSAFE>0
15677   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
15678 #endif
15679   sqlite3_mutex_enter(mutex);
15680   pX = localtime(t);
15681 #ifndef SQLITE_OMIT_BUILTIN_TEST
15682   if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
15683 #endif
15684   if( pX ) *pTm = *pX;
15685   sqlite3_mutex_leave(mutex);
15686   rc = pX==0;
15687 #else
15688 #ifndef SQLITE_OMIT_BUILTIN_TEST
15689   if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
15690 #endif
15691 #if HAVE_LOCALTIME_R
15692   rc = localtime_r(t, pTm)==0;
15693 #else
15694   rc = localtime_s(pTm, t);
15695 #endif /* HAVE_LOCALTIME_R */
15696 #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
15697   return rc;
15698 }
15699 #endif /* SQLITE_OMIT_LOCALTIME */
15700
15701
15702 #ifndef SQLITE_OMIT_LOCALTIME
15703 /*
15704 ** Compute the difference (in milliseconds) between localtime and UTC
15705 ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
15706 ** return this value and set *pRc to SQLITE_OK. 
15707 **
15708 ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
15709 ** is undefined in this case.
15710 */
15711 static sqlite3_int64 localtimeOffset(
15712   DateTime *p,                    /* Date at which to calculate offset */
15713   sqlite3_context *pCtx,          /* Write error here if one occurs */
15714   int *pRc                        /* OUT: Error code. SQLITE_OK or ERROR */
15715 ){
15716   DateTime x, y;
15717   time_t t;
15718   struct tm sLocal;
15719
15720   /* Initialize the contents of sLocal to avoid a compiler warning. */
15721   memset(&sLocal, 0, sizeof(sLocal));
15722
15723   x = *p;
15724   computeYMD_HMS(&x);
15725   if( x.Y<1971 || x.Y>=2038 ){
15726     /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
15727     ** works for years between 1970 and 2037. For dates outside this range,
15728     ** SQLite attempts to map the year into an equivalent year within this
15729     ** range, do the calculation, then map the year back.
15730     */
15731     x.Y = 2000;
15732     x.M = 1;
15733     x.D = 1;
15734     x.h = 0;
15735     x.m = 0;
15736     x.s = 0.0;
15737   } else {
15738     int s = (int)(x.s + 0.5);
15739     x.s = s;
15740   }
15741   x.tz = 0;
15742   x.validJD = 0;
15743   computeJD(&x);
15744   t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
15745   if( osLocaltime(&t, &sLocal) ){
15746     sqlite3_result_error(pCtx, "local time unavailable", -1);
15747     *pRc = SQLITE_ERROR;
15748     return 0;
15749   }
15750   y.Y = sLocal.tm_year + 1900;
15751   y.M = sLocal.tm_mon + 1;
15752   y.D = sLocal.tm_mday;
15753   y.h = sLocal.tm_hour;
15754   y.m = sLocal.tm_min;
15755   y.s = sLocal.tm_sec;
15756   y.validYMD = 1;
15757   y.validHMS = 1;
15758   y.validJD = 0;
15759   y.validTZ = 0;
15760   computeJD(&y);
15761   *pRc = SQLITE_OK;
15762   return y.iJD - x.iJD;
15763 }
15764 #endif /* SQLITE_OMIT_LOCALTIME */
15765
15766 /*
15767 ** Process a modifier to a date-time stamp.  The modifiers are
15768 ** as follows:
15769 **
15770 **     NNN days
15771 **     NNN hours
15772 **     NNN minutes
15773 **     NNN.NNNN seconds
15774 **     NNN months
15775 **     NNN years
15776 **     start of month
15777 **     start of year
15778 **     start of week
15779 **     start of day
15780 **     weekday N
15781 **     unixepoch
15782 **     localtime
15783 **     utc
15784 **
15785 ** Return 0 on success and 1 if there is any kind of error. If the error
15786 ** is in a system call (i.e. localtime()), then an error message is written
15787 ** to context pCtx. If the error is an unrecognized modifier, no error is
15788 ** written to pCtx.
15789 */
15790 static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
15791   int rc = 1;
15792   int n;
15793   double r;
15794   char *z, zBuf[30];
15795   z = zBuf;
15796   for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
15797     z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
15798   }
15799   z[n] = 0;
15800   switch( z[0] ){
15801 #ifndef SQLITE_OMIT_LOCALTIME
15802     case 'l': {
15803       /*    localtime
15804       **
15805       ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
15806       ** show local time.
15807       */
15808       if( strcmp(z, "localtime")==0 ){
15809         computeJD(p);
15810         p->iJD += localtimeOffset(p, pCtx, &rc);
15811         clearYMD_HMS_TZ(p);
15812       }
15813       break;
15814     }
15815 #endif
15816     case 'u': {
15817       /*
15818       **    unixepoch
15819       **
15820       ** Treat the current value of p->iJD as the number of
15821       ** seconds since 1970.  Convert to a real julian day number.
15822       */
15823       if( strcmp(z, "unixepoch")==0 && p->validJD ){
15824         p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
15825         clearYMD_HMS_TZ(p);
15826         rc = 0;
15827       }
15828 #ifndef SQLITE_OMIT_LOCALTIME
15829       else if( strcmp(z, "utc")==0 ){
15830         sqlite3_int64 c1;
15831         computeJD(p);
15832         c1 = localtimeOffset(p, pCtx, &rc);
15833         if( rc==SQLITE_OK ){
15834           p->iJD -= c1;
15835           clearYMD_HMS_TZ(p);
15836           p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
15837         }
15838       }
15839 #endif
15840       break;
15841     }
15842     case 'w': {
15843       /*
15844       **    weekday N
15845       **
15846       ** Move the date to the same time on the next occurrence of
15847       ** weekday N where 0==Sunday, 1==Monday, and so forth.  If the
15848       ** date is already on the appropriate weekday, this is a no-op.
15849       */
15850       if( strncmp(z, "weekday ", 8)==0
15851                && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
15852                && (n=(int)r)==r && n>=0 && r<7 ){
15853         sqlite3_int64 Z;
15854         computeYMD_HMS(p);
15855         p->validTZ = 0;
15856         p->validJD = 0;
15857         computeJD(p);
15858         Z = ((p->iJD + 129600000)/86400000) % 7;
15859         if( Z>n ) Z -= 7;
15860         p->iJD += (n - Z)*86400000;
15861         clearYMD_HMS_TZ(p);
15862         rc = 0;
15863       }
15864       break;
15865     }
15866     case 's': {
15867       /*
15868       **    start of TTTTT
15869       **
15870       ** Move the date backwards to the beginning of the current day,
15871       ** or month or year.
15872       */
15873       if( strncmp(z, "start of ", 9)!=0 ) break;
15874       z += 9;
15875       computeYMD(p);
15876       p->validHMS = 1;
15877       p->h = p->m = 0;
15878       p->s = 0.0;
15879       p->validTZ = 0;
15880       p->validJD = 0;
15881       if( strcmp(z,"month")==0 ){
15882         p->D = 1;
15883         rc = 0;
15884       }else if( strcmp(z,"year")==0 ){
15885         computeYMD(p);
15886         p->M = 1;
15887         p->D = 1;
15888         rc = 0;
15889       }else if( strcmp(z,"day")==0 ){
15890         rc = 0;
15891       }
15892       break;
15893     }
15894     case '+':
15895     case '-':
15896     case '0':
15897     case '1':
15898     case '2':
15899     case '3':
15900     case '4':
15901     case '5':
15902     case '6':
15903     case '7':
15904     case '8':
15905     case '9': {
15906       double rRounder;
15907       for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
15908       if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
15909         rc = 1;
15910         break;
15911       }
15912       if( z[n]==':' ){
15913         /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
15914         ** specified number of hours, minutes, seconds, and fractional seconds
15915         ** to the time.  The ".FFF" may be omitted.  The ":SS.FFF" may be
15916         ** omitted.
15917         */
15918         const char *z2 = z;
15919         DateTime tx;
15920         sqlite3_int64 day;
15921         if( !sqlite3Isdigit(*z2) ) z2++;
15922         memset(&tx, 0, sizeof(tx));
15923         if( parseHhMmSs(z2, &tx) ) break;
15924         computeJD(&tx);
15925         tx.iJD -= 43200000;
15926         day = tx.iJD/86400000;
15927         tx.iJD -= day*86400000;
15928         if( z[0]=='-' ) tx.iJD = -tx.iJD;
15929         computeJD(p);
15930         clearYMD_HMS_TZ(p);
15931         p->iJD += tx.iJD;
15932         rc = 0;
15933         break;
15934       }
15935       z += n;
15936       while( sqlite3Isspace(*z) ) z++;
15937       n = sqlite3Strlen30(z);
15938       if( n>10 || n<3 ) break;
15939       if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
15940       computeJD(p);
15941       rc = 0;
15942       rRounder = r<0 ? -0.5 : +0.5;
15943       if( n==3 && strcmp(z,"day")==0 ){
15944         p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
15945       }else if( n==4 && strcmp(z,"hour")==0 ){
15946         p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
15947       }else if( n==6 && strcmp(z,"minute")==0 ){
15948         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
15949       }else if( n==6 && strcmp(z,"second")==0 ){
15950         p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
15951       }else if( n==5 && strcmp(z,"month")==0 ){
15952         int x, y;
15953         computeYMD_HMS(p);
15954         p->M += (int)r;
15955         x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
15956         p->Y += x;
15957         p->M -= x*12;
15958         p->validJD = 0;
15959         computeJD(p);
15960         y = (int)r;
15961         if( y!=r ){
15962           p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
15963         }
15964       }else if( n==4 && strcmp(z,"year")==0 ){
15965         int y = (int)r;
15966         computeYMD_HMS(p);
15967         p->Y += y;
15968         p->validJD = 0;
15969         computeJD(p);
15970         if( y!=r ){
15971           p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
15972         }
15973       }else{
15974         rc = 1;
15975       }
15976       clearYMD_HMS_TZ(p);
15977       break;
15978     }
15979     default: {
15980       break;
15981     }
15982   }
15983   return rc;
15984 }
15985
15986 /*
15987 ** Process time function arguments.  argv[0] is a date-time stamp.
15988 ** argv[1] and following are modifiers.  Parse them all and write
15989 ** the resulting time into the DateTime structure p.  Return 0
15990 ** on success and 1 if there are any errors.
15991 **
15992 ** If there are zero parameters (if even argv[0] is undefined)
15993 ** then assume a default value of "now" for argv[0].
15994 */
15995 static int isDate(
15996   sqlite3_context *context, 
15997   int argc, 
15998   sqlite3_value **argv, 
15999   DateTime *p
16000 ){
16001   int i;
16002   const unsigned char *z;
16003   int eType;
16004   memset(p, 0, sizeof(*p));
16005   if( argc==0 ){
16006     return setDateTimeToCurrent(context, p);
16007   }
16008   if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
16009                    || eType==SQLITE_INTEGER ){
16010     p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
16011     p->validJD = 1;
16012   }else{
16013     z = sqlite3_value_text(argv[0]);
16014     if( !z || parseDateOrTime(context, (char*)z, p) ){
16015       return 1;
16016     }
16017   }
16018   for(i=1; i<argc; i++){
16019     z = sqlite3_value_text(argv[i]);
16020     if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
16021   }
16022   return 0;
16023 }
16024
16025
16026 /*
16027 ** The following routines implement the various date and time functions
16028 ** of SQLite.
16029 */
16030
16031 /*
16032 **    julianday( TIMESTRING, MOD, MOD, ...)
16033 **
16034 ** Return the julian day number of the date specified in the arguments
16035 */
16036 static void juliandayFunc(
16037   sqlite3_context *context,
16038   int argc,
16039   sqlite3_value **argv
16040 ){
16041   DateTime x;
16042   if( isDate(context, argc, argv, &x)==0 ){
16043     computeJD(&x);
16044     sqlite3_result_double(context, x.iJD/86400000.0);
16045   }
16046 }
16047
16048 /*
16049 **    datetime( TIMESTRING, MOD, MOD, ...)
16050 **
16051 ** Return YYYY-MM-DD HH:MM:SS
16052 */
16053 static void datetimeFunc(
16054   sqlite3_context *context,
16055   int argc,
16056   sqlite3_value **argv
16057 ){
16058   DateTime x;
16059   if( isDate(context, argc, argv, &x)==0 ){
16060     char zBuf[100];
16061     computeYMD_HMS(&x);
16062     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
16063                      x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
16064     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
16065   }
16066 }
16067
16068 /*
16069 **    time( TIMESTRING, MOD, MOD, ...)
16070 **
16071 ** Return HH:MM:SS
16072 */
16073 static void timeFunc(
16074   sqlite3_context *context,
16075   int argc,
16076   sqlite3_value **argv
16077 ){
16078   DateTime x;
16079   if( isDate(context, argc, argv, &x)==0 ){
16080     char zBuf[100];
16081     computeHMS(&x);
16082     sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
16083     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
16084   }
16085 }
16086
16087 /*
16088 **    date( TIMESTRING, MOD, MOD, ...)
16089 **
16090 ** Return YYYY-MM-DD
16091 */
16092 static void dateFunc(
16093   sqlite3_context *context,
16094   int argc,
16095   sqlite3_value **argv
16096 ){
16097   DateTime x;
16098   if( isDate(context, argc, argv, &x)==0 ){
16099     char zBuf[100];
16100     computeYMD(&x);
16101     sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
16102     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
16103   }
16104 }
16105
16106 /*
16107 **    strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
16108 **
16109 ** Return a string described by FORMAT.  Conversions as follows:
16110 **
16111 **   %d  day of month
16112 **   %f  ** fractional seconds  SS.SSS
16113 **   %H  hour 00-24
16114 **   %j  day of year 000-366
16115 **   %J  ** julian day number
16116 **   %m  month 01-12
16117 **   %M  minute 00-59
16118 **   %s  seconds since 1970-01-01
16119 **   %S  seconds 00-59
16120 **   %w  day of week 0-6  sunday==0
16121 **   %W  week of year 00-53
16122 **   %Y  year 0000-9999
16123 **   %%  %
16124 */
16125 static void strftimeFunc(
16126   sqlite3_context *context,
16127   int argc,
16128   sqlite3_value **argv
16129 ){
16130   DateTime x;
16131   u64 n;
16132   size_t i,j;
16133   char *z;
16134   sqlite3 *db;
16135   const char *zFmt;
16136   char zBuf[100];
16137   if( argc==0 ) return;
16138   zFmt = (const char*)sqlite3_value_text(argv[0]);
16139   if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
16140   db = sqlite3_context_db_handle(context);
16141   for(i=0, n=1; zFmt[i]; i++, n++){
16142     if( zFmt[i]=='%' ){
16143       switch( zFmt[i+1] ){
16144         case 'd':
16145         case 'H':
16146         case 'm':
16147         case 'M':
16148         case 'S':
16149         case 'W':
16150           n++;
16151           /* fall thru */
16152         case 'w':
16153         case '%':
16154           break;
16155         case 'f':
16156           n += 8;
16157           break;
16158         case 'j':
16159           n += 3;
16160           break;
16161         case 'Y':
16162           n += 8;
16163           break;
16164         case 's':
16165         case 'J':
16166           n += 50;
16167           break;
16168         default:
16169           return;  /* ERROR.  return a NULL */
16170       }
16171       i++;
16172     }
16173   }
16174   testcase( n==sizeof(zBuf)-1 );
16175   testcase( n==sizeof(zBuf) );
16176   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
16177   testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
16178   if( n<sizeof(zBuf) ){
16179     z = zBuf;
16180   }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
16181     sqlite3_result_error_toobig(context);
16182     return;
16183   }else{
16184     z = sqlite3DbMallocRaw(db, (int)n);
16185     if( z==0 ){
16186       sqlite3_result_error_nomem(context);
16187       return;
16188     }
16189   }
16190   computeJD(&x);
16191   computeYMD_HMS(&x);
16192   for(i=j=0; zFmt[i]; i++){
16193     if( zFmt[i]!='%' ){
16194       z[j++] = zFmt[i];
16195     }else{
16196       i++;
16197       switch( zFmt[i] ){
16198         case 'd':  sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
16199         case 'f': {
16200           double s = x.s;
16201           if( s>59.999 ) s = 59.999;
16202           sqlite3_snprintf(7, &z[j],"%06.3f", s);
16203           j += sqlite3Strlen30(&z[j]);
16204           break;
16205         }
16206         case 'H':  sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
16207         case 'W': /* Fall thru */
16208         case 'j': {
16209           int nDay;             /* Number of days since 1st day of year */
16210           DateTime y = x;
16211           y.validJD = 0;
16212           y.M = 1;
16213           y.D = 1;
16214           computeJD(&y);
16215           nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
16216           if( zFmt[i]=='W' ){
16217             int wd;   /* 0=Monday, 1=Tuesday, ... 6=Sunday */
16218             wd = (int)(((x.iJD+43200000)/86400000)%7);
16219             sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
16220             j += 2;
16221           }else{
16222             sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
16223             j += 3;
16224           }
16225           break;
16226         }
16227         case 'J': {
16228           sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
16229           j+=sqlite3Strlen30(&z[j]);
16230           break;
16231         }
16232         case 'm':  sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
16233         case 'M':  sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
16234         case 's': {
16235           sqlite3_snprintf(30,&z[j],"%lld",
16236                            (i64)(x.iJD/1000 - 21086676*(i64)10000));
16237           j += sqlite3Strlen30(&z[j]);
16238           break;
16239         }
16240         case 'S':  sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
16241         case 'w': {
16242           z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
16243           break;
16244         }
16245         case 'Y': {
16246           sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
16247           break;
16248         }
16249         default:   z[j++] = '%'; break;
16250       }
16251     }
16252   }
16253   z[j] = 0;
16254   sqlite3_result_text(context, z, -1,
16255                       z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
16256 }
16257
16258 /*
16259 ** current_time()
16260 **
16261 ** This function returns the same value as time('now').
16262 */
16263 static void ctimeFunc(
16264   sqlite3_context *context,
16265   int NotUsed,
16266   sqlite3_value **NotUsed2
16267 ){
16268   UNUSED_PARAMETER2(NotUsed, NotUsed2);
16269   timeFunc(context, 0, 0);
16270 }
16271
16272 /*
16273 ** current_date()
16274 **
16275 ** This function returns the same value as date('now').
16276 */
16277 static void cdateFunc(
16278   sqlite3_context *context,
16279   int NotUsed,
16280   sqlite3_value **NotUsed2
16281 ){
16282   UNUSED_PARAMETER2(NotUsed, NotUsed2);
16283   dateFunc(context, 0, 0);
16284 }
16285
16286 /*
16287 ** current_timestamp()
16288 **
16289 ** This function returns the same value as datetime('now').
16290 */
16291 static void ctimestampFunc(
16292   sqlite3_context *context,
16293   int NotUsed,
16294   sqlite3_value **NotUsed2
16295 ){
16296   UNUSED_PARAMETER2(NotUsed, NotUsed2);
16297   datetimeFunc(context, 0, 0);
16298 }
16299 #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
16300
16301 #ifdef SQLITE_OMIT_DATETIME_FUNCS
16302 /*
16303 ** If the library is compiled to omit the full-scale date and time
16304 ** handling (to get a smaller binary), the following minimal version
16305 ** of the functions current_time(), current_date() and current_timestamp()
16306 ** are included instead. This is to support column declarations that
16307 ** include "DEFAULT CURRENT_TIME" etc.
16308 **
16309 ** This function uses the C-library functions time(), gmtime()
16310 ** and strftime(). The format string to pass to strftime() is supplied
16311 ** as the user-data for the function.
16312 */
16313 static void currentTimeFunc(
16314   sqlite3_context *context,
16315   int argc,
16316   sqlite3_value **argv
16317 ){
16318   time_t t;
16319   char *zFormat = (char *)sqlite3_user_data(context);
16320   sqlite3 *db;
16321   sqlite3_int64 iT;
16322   struct tm *pTm;
16323   struct tm sNow;
16324   char zBuf[20];
16325
16326   UNUSED_PARAMETER(argc);
16327   UNUSED_PARAMETER(argv);
16328
16329   iT = sqlite3StmtCurrentTime(context);
16330   if( iT<=0 ) return;
16331   t = iT/1000 - 10000*(sqlite3_int64)21086676;
16332 #if HAVE_GMTIME_R
16333   pTm = gmtime_r(&t, &sNow);
16334 #else
16335   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
16336   pTm = gmtime(&t);
16337   if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
16338   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
16339 #endif
16340   if( pTm ){
16341     strftime(zBuf, 20, zFormat, &sNow);
16342     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
16343   }
16344 }
16345 #endif
16346
16347 /*
16348 ** This function registered all of the above C functions as SQL
16349 ** functions.  This should be the only routine in this file with
16350 ** external linkage.
16351 */
16352 SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
16353   static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
16354 #ifndef SQLITE_OMIT_DATETIME_FUNCS
16355     FUNCTION(julianday,        -1, 0, 0, juliandayFunc ),
16356     FUNCTION(date,             -1, 0, 0, dateFunc      ),
16357     FUNCTION(time,             -1, 0, 0, timeFunc      ),
16358     FUNCTION(datetime,         -1, 0, 0, datetimeFunc  ),
16359     FUNCTION(strftime,         -1, 0, 0, strftimeFunc  ),
16360     FUNCTION(current_time,      0, 0, 0, ctimeFunc     ),
16361     FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
16362     FUNCTION(current_date,      0, 0, 0, cdateFunc     ),
16363 #else
16364     STR_FUNCTION(current_time,      0, "%H:%M:%S",          0, currentTimeFunc),
16365     STR_FUNCTION(current_date,      0, "%Y-%m-%d",          0, currentTimeFunc),
16366     STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
16367 #endif
16368   };
16369   int i;
16370   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
16371   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
16372
16373   for(i=0; i<ArraySize(aDateTimeFuncs); i++){
16374     sqlite3FuncDefInsert(pHash, &aFunc[i]);
16375   }
16376 }
16377
16378 /************** End of date.c ************************************************/
16379 /************** Begin file os.c **********************************************/
16380 /*
16381 ** 2005 November 29
16382 **
16383 ** The author disclaims copyright to this source code.  In place of
16384 ** a legal notice, here is a blessing:
16385 **
16386 **    May you do good and not evil.
16387 **    May you find forgiveness for yourself and forgive others.
16388 **    May you share freely, never taking more than you give.
16389 **
16390 ******************************************************************************
16391 **
16392 ** This file contains OS interface code that is common to all
16393 ** architectures.
16394 */
16395 #define _SQLITE_OS_C_ 1
16396 #undef _SQLITE_OS_C_
16397
16398 /*
16399 ** The default SQLite sqlite3_vfs implementations do not allocate
16400 ** memory (actually, os_unix.c allocates a small amount of memory
16401 ** from within OsOpen()), but some third-party implementations may.
16402 ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
16403 ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
16404 **
16405 ** The following functions are instrumented for malloc() failure 
16406 ** testing:
16407 **
16408 **     sqlite3OsRead()
16409 **     sqlite3OsWrite()
16410 **     sqlite3OsSync()
16411 **     sqlite3OsFileSize()
16412 **     sqlite3OsLock()
16413 **     sqlite3OsCheckReservedLock()
16414 **     sqlite3OsFileControl()
16415 **     sqlite3OsShmMap()
16416 **     sqlite3OsOpen()
16417 **     sqlite3OsDelete()
16418 **     sqlite3OsAccess()
16419 **     sqlite3OsFullPathname()
16420 **
16421 */
16422 #if defined(SQLITE_TEST)
16423 SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
16424   #define DO_OS_MALLOC_TEST(x)                                       \
16425   if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) {  \
16426     void *pTstAlloc = sqlite3Malloc(10);                             \
16427     if (!pTstAlloc) return SQLITE_IOERR_NOMEM;                       \
16428     sqlite3_free(pTstAlloc);                                         \
16429   }
16430 #else
16431   #define DO_OS_MALLOC_TEST(x)
16432 #endif
16433
16434 /*
16435 ** The following routines are convenience wrappers around methods
16436 ** of the sqlite3_file object.  This is mostly just syntactic sugar. All
16437 ** of this would be completely automatic if SQLite were coded using
16438 ** C++ instead of plain old C.
16439 */
16440 SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
16441   int rc = SQLITE_OK;
16442   if( pId->pMethods ){
16443     rc = pId->pMethods->xClose(pId);
16444     pId->pMethods = 0;
16445   }
16446   return rc;
16447 }
16448 SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
16449   DO_OS_MALLOC_TEST(id);
16450   return id->pMethods->xRead(id, pBuf, amt, offset);
16451 }
16452 SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
16453   DO_OS_MALLOC_TEST(id);
16454   return id->pMethods->xWrite(id, pBuf, amt, offset);
16455 }
16456 SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
16457   return id->pMethods->xTruncate(id, size);
16458 }
16459 SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
16460   DO_OS_MALLOC_TEST(id);
16461   return id->pMethods->xSync(id, flags);
16462 }
16463 SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
16464   DO_OS_MALLOC_TEST(id);
16465   return id->pMethods->xFileSize(id, pSize);
16466 }
16467 SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
16468   DO_OS_MALLOC_TEST(id);
16469   return id->pMethods->xLock(id, lockType);
16470 }
16471 SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
16472   return id->pMethods->xUnlock(id, lockType);
16473 }
16474 SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
16475   DO_OS_MALLOC_TEST(id);
16476   return id->pMethods->xCheckReservedLock(id, pResOut);
16477 }
16478
16479 /*
16480 ** Use sqlite3OsFileControl() when we are doing something that might fail
16481 ** and we need to know about the failures.  Use sqlite3OsFileControlHint()
16482 ** when simply tossing information over the wall to the VFS and we do not
16483 ** really care if the VFS receives and understands the information since it
16484 ** is only a hint and can be safely ignored.  The sqlite3OsFileControlHint()
16485 ** routine has no return value since the return value would be meaningless.
16486 */
16487 SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
16488 #ifdef SQLITE_TEST
16489   if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
16490     /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
16491     ** is using a regular VFS, it is called after the corresponding 
16492     ** transaction has been committed. Injecting a fault at this point 
16493     ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
16494     ** but the transaction is committed anyway.
16495     **
16496     ** The core must call OsFileControl() though, not OsFileControlHint(),
16497     ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
16498     ** means the commit really has failed and an error should be returned
16499     ** to the user.  */
16500     DO_OS_MALLOC_TEST(id);
16501   }
16502 #endif
16503   return id->pMethods->xFileControl(id, op, pArg);
16504 }
16505 SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
16506   (void)id->pMethods->xFileControl(id, op, pArg);
16507 }
16508
16509 SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
16510   int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
16511   return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
16512 }
16513 SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
16514   return id->pMethods->xDeviceCharacteristics(id);
16515 }
16516 SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
16517   return id->pMethods->xShmLock(id, offset, n, flags);
16518 }
16519 SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
16520   id->pMethods->xShmBarrier(id);
16521 }
16522 SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
16523   return id->pMethods->xShmUnmap(id, deleteFlag);
16524 }
16525 SQLITE_PRIVATE int sqlite3OsShmMap(
16526   sqlite3_file *id,               /* Database file handle */
16527   int iPage,
16528   int pgsz,
16529   int bExtend,                    /* True to extend file if necessary */
16530   void volatile **pp              /* OUT: Pointer to mapping */
16531 ){
16532   DO_OS_MALLOC_TEST(id);
16533   return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
16534 }
16535
16536 #if SQLITE_MAX_MMAP_SIZE>0
16537 /* The real implementation of xFetch and xUnfetch */
16538 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
16539   DO_OS_MALLOC_TEST(id);
16540   return id->pMethods->xFetch(id, iOff, iAmt, pp);
16541 }
16542 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
16543   return id->pMethods->xUnfetch(id, iOff, p);
16544 }
16545 #else
16546 /* No-op stubs to use when memory-mapped I/O is disabled */
16547 SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
16548   *pp = 0;
16549   return SQLITE_OK;
16550 }
16551 SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
16552   return SQLITE_OK;
16553 }
16554 #endif
16555
16556 /*
16557 ** The next group of routines are convenience wrappers around the
16558 ** VFS methods.
16559 */
16560 SQLITE_PRIVATE int sqlite3OsOpen(
16561   sqlite3_vfs *pVfs, 
16562   const char *zPath, 
16563   sqlite3_file *pFile, 
16564   int flags, 
16565   int *pFlagsOut
16566 ){
16567   int rc;
16568   DO_OS_MALLOC_TEST(0);
16569   /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
16570   ** down into the VFS layer.  Some SQLITE_OPEN_ flags (for example,
16571   ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
16572   ** reaching the VFS. */
16573   rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
16574   assert( rc==SQLITE_OK || pFile->pMethods==0 );
16575   return rc;
16576 }
16577 SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
16578   DO_OS_MALLOC_TEST(0);
16579   assert( dirSync==0 || dirSync==1 );
16580   return pVfs->xDelete(pVfs, zPath, dirSync);
16581 }
16582 SQLITE_PRIVATE int sqlite3OsAccess(
16583   sqlite3_vfs *pVfs, 
16584   const char *zPath, 
16585   int flags, 
16586   int *pResOut
16587 ){
16588   DO_OS_MALLOC_TEST(0);
16589   return pVfs->xAccess(pVfs, zPath, flags, pResOut);
16590 }
16591 SQLITE_PRIVATE int sqlite3OsFullPathname(
16592   sqlite3_vfs *pVfs, 
16593   const char *zPath, 
16594   int nPathOut, 
16595   char *zPathOut
16596 ){
16597   DO_OS_MALLOC_TEST(0);
16598   zPathOut[0] = 0;
16599   return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
16600 }
16601 #ifndef SQLITE_OMIT_LOAD_EXTENSION
16602 SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
16603   return pVfs->xDlOpen(pVfs, zPath);
16604 }
16605 SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
16606   pVfs->xDlError(pVfs, nByte, zBufOut);
16607 }
16608 SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
16609   return pVfs->xDlSym(pVfs, pHdle, zSym);
16610 }
16611 SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
16612   pVfs->xDlClose(pVfs, pHandle);
16613 }
16614 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
16615 SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
16616   return pVfs->xRandomness(pVfs, nByte, zBufOut);
16617 }
16618 SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
16619   return pVfs->xSleep(pVfs, nMicro);
16620 }
16621 SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
16622   int rc;
16623   /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
16624   ** method to get the current date and time if that method is available
16625   ** (if iVersion is 2 or greater and the function pointer is not NULL) and
16626   ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
16627   ** unavailable.
16628   */
16629   if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
16630     rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
16631   }else{
16632     double r;
16633     rc = pVfs->xCurrentTime(pVfs, &r);
16634     *pTimeOut = (sqlite3_int64)(r*86400000.0);
16635   }
16636   return rc;
16637 }
16638
16639 SQLITE_PRIVATE int sqlite3OsOpenMalloc(
16640   sqlite3_vfs *pVfs, 
16641   const char *zFile, 
16642   sqlite3_file **ppFile, 
16643   int flags,
16644   int *pOutFlags
16645 ){
16646   int rc = SQLITE_NOMEM;
16647   sqlite3_file *pFile;
16648   pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
16649   if( pFile ){
16650     rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
16651     if( rc!=SQLITE_OK ){
16652       sqlite3_free(pFile);
16653     }else{
16654       *ppFile = pFile;
16655     }
16656   }
16657   return rc;
16658 }
16659 SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
16660   int rc = SQLITE_OK;
16661   assert( pFile );
16662   rc = sqlite3OsClose(pFile);
16663   sqlite3_free(pFile);
16664   return rc;
16665 }
16666
16667 /*
16668 ** This function is a wrapper around the OS specific implementation of
16669 ** sqlite3_os_init(). The purpose of the wrapper is to provide the
16670 ** ability to simulate a malloc failure, so that the handling of an
16671 ** error in sqlite3_os_init() by the upper layers can be tested.
16672 */
16673 SQLITE_PRIVATE int sqlite3OsInit(void){
16674   void *p = sqlite3_malloc(10);
16675   if( p==0 ) return SQLITE_NOMEM;
16676   sqlite3_free(p);
16677   return sqlite3_os_init();
16678 }
16679
16680 /*
16681 ** The list of all registered VFS implementations.
16682 */
16683 static sqlite3_vfs * SQLITE_WSD vfsList = 0;
16684 #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
16685
16686 /*
16687 ** Locate a VFS by name.  If no name is given, simply return the
16688 ** first VFS on the list.
16689 */
16690 SQLITE_API sqlite3_vfs *SQLITE_STDCALL sqlite3_vfs_find(const char *zVfs){
16691   sqlite3_vfs *pVfs = 0;
16692 #if SQLITE_THREADSAFE
16693   sqlite3_mutex *mutex;
16694 #endif
16695 #ifndef SQLITE_OMIT_AUTOINIT
16696   int rc = sqlite3_initialize();
16697   if( rc ) return 0;
16698 #endif
16699 #if SQLITE_THREADSAFE
16700   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
16701 #endif
16702   sqlite3_mutex_enter(mutex);
16703   for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
16704     if( zVfs==0 ) break;
16705     if( strcmp(zVfs, pVfs->zName)==0 ) break;
16706   }
16707   sqlite3_mutex_leave(mutex);
16708   return pVfs;
16709 }
16710
16711 /*
16712 ** Unlink a VFS from the linked list
16713 */
16714 static void vfsUnlink(sqlite3_vfs *pVfs){
16715   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
16716   if( pVfs==0 ){
16717     /* No-op */
16718   }else if( vfsList==pVfs ){
16719     vfsList = pVfs->pNext;
16720   }else if( vfsList ){
16721     sqlite3_vfs *p = vfsList;
16722     while( p->pNext && p->pNext!=pVfs ){
16723       p = p->pNext;
16724     }
16725     if( p->pNext==pVfs ){
16726       p->pNext = pVfs->pNext;
16727     }
16728   }
16729 }
16730
16731 /*
16732 ** Register a VFS with the system.  It is harmless to register the same
16733 ** VFS multiple times.  The new VFS becomes the default if makeDflt is
16734 ** true.
16735 */
16736 SQLITE_API int SQLITE_STDCALL sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
16737   MUTEX_LOGIC(sqlite3_mutex *mutex;)
16738 #ifndef SQLITE_OMIT_AUTOINIT
16739   int rc = sqlite3_initialize();
16740   if( rc ) return rc;
16741 #endif
16742 #ifdef SQLITE_ENABLE_API_ARMOR
16743   if( pVfs==0 ) return SQLITE_MISUSE_BKPT;
16744 #endif
16745
16746   MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
16747   sqlite3_mutex_enter(mutex);
16748   vfsUnlink(pVfs);
16749   if( makeDflt || vfsList==0 ){
16750     pVfs->pNext = vfsList;
16751     vfsList = pVfs;
16752   }else{
16753     pVfs->pNext = vfsList->pNext;
16754     vfsList->pNext = pVfs;
16755   }
16756   assert(vfsList);
16757   sqlite3_mutex_leave(mutex);
16758   return SQLITE_OK;
16759 }
16760
16761 /*
16762 ** Unregister a VFS so that it is no longer accessible.
16763 */
16764 SQLITE_API int SQLITE_STDCALL sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
16765 #if SQLITE_THREADSAFE
16766   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
16767 #endif
16768   sqlite3_mutex_enter(mutex);
16769   vfsUnlink(pVfs);
16770   sqlite3_mutex_leave(mutex);
16771   return SQLITE_OK;
16772 }
16773
16774 /************** End of os.c **************************************************/
16775 /************** Begin file fault.c *******************************************/
16776 /*
16777 ** 2008 Jan 22
16778 **
16779 ** The author disclaims copyright to this source code.  In place of
16780 ** a legal notice, here is a blessing:
16781 **
16782 **    May you do good and not evil.
16783 **    May you find forgiveness for yourself and forgive others.
16784 **    May you share freely, never taking more than you give.
16785 **
16786 *************************************************************************
16787 **
16788 ** This file contains code to support the concept of "benign" 
16789 ** malloc failures (when the xMalloc() or xRealloc() method of the
16790 ** sqlite3_mem_methods structure fails to allocate a block of memory
16791 ** and returns 0). 
16792 **
16793 ** Most malloc failures are non-benign. After they occur, SQLite
16794 ** abandons the current operation and returns an error code (usually
16795 ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
16796 ** fatal. For example, if a malloc fails while resizing a hash table, this 
16797 ** is completely recoverable simply by not carrying out the resize. The 
16798 ** hash table will continue to function normally.  So a malloc failure 
16799 ** during a hash table resize is a benign fault.
16800 */
16801
16802
16803 #ifndef SQLITE_OMIT_BUILTIN_TEST
16804
16805 /*
16806 ** Global variables.
16807 */
16808 typedef struct BenignMallocHooks BenignMallocHooks;
16809 static SQLITE_WSD struct BenignMallocHooks {
16810   void (*xBenignBegin)(void);
16811   void (*xBenignEnd)(void);
16812 } sqlite3Hooks = { 0, 0 };
16813
16814 /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
16815 ** structure.  If writable static data is unsupported on the target,
16816 ** we have to locate the state vector at run-time.  In the more common
16817 ** case where writable static data is supported, wsdHooks can refer directly
16818 ** to the "sqlite3Hooks" state vector declared above.
16819 */
16820 #ifdef SQLITE_OMIT_WSD
16821 # define wsdHooksInit \
16822   BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
16823 # define wsdHooks x[0]
16824 #else
16825 # define wsdHooksInit
16826 # define wsdHooks sqlite3Hooks
16827 #endif
16828
16829
16830 /*
16831 ** Register hooks to call when sqlite3BeginBenignMalloc() and
16832 ** sqlite3EndBenignMalloc() are called, respectively.
16833 */
16834 SQLITE_PRIVATE void sqlite3BenignMallocHooks(
16835   void (*xBenignBegin)(void),
16836   void (*xBenignEnd)(void)
16837 ){
16838   wsdHooksInit;
16839   wsdHooks.xBenignBegin = xBenignBegin;
16840   wsdHooks.xBenignEnd = xBenignEnd;
16841 }
16842
16843 /*
16844 ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
16845 ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
16846 ** indicates that subsequent malloc failures are non-benign.
16847 */
16848 SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
16849   wsdHooksInit;
16850   if( wsdHooks.xBenignBegin ){
16851     wsdHooks.xBenignBegin();
16852   }
16853 }
16854 SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
16855   wsdHooksInit;
16856   if( wsdHooks.xBenignEnd ){
16857     wsdHooks.xBenignEnd();
16858   }
16859 }
16860
16861 #endif   /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
16862
16863 /************** End of fault.c ***********************************************/
16864 /************** Begin file mem0.c ********************************************/
16865 /*
16866 ** 2008 October 28
16867 **
16868 ** The author disclaims copyright to this source code.  In place of
16869 ** a legal notice, here is a blessing:
16870 **
16871 **    May you do good and not evil.
16872 **    May you find forgiveness for yourself and forgive others.
16873 **    May you share freely, never taking more than you give.
16874 **
16875 *************************************************************************
16876 **
16877 ** This file contains a no-op memory allocation drivers for use when
16878 ** SQLITE_ZERO_MALLOC is defined.  The allocation drivers implemented
16879 ** here always fail.  SQLite will not operate with these drivers.  These
16880 ** are merely placeholders.  Real drivers must be substituted using
16881 ** sqlite3_config() before SQLite will operate.
16882 */
16883
16884 /*
16885 ** This version of the memory allocator is the default.  It is
16886 ** used when no other memory allocator is specified using compile-time
16887 ** macros.
16888 */
16889 #ifdef SQLITE_ZERO_MALLOC
16890
16891 /*
16892 ** No-op versions of all memory allocation routines
16893 */
16894 static void *sqlite3MemMalloc(int nByte){ return 0; }
16895 static void sqlite3MemFree(void *pPrior){ return; }
16896 static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
16897 static int sqlite3MemSize(void *pPrior){ return 0; }
16898 static int sqlite3MemRoundup(int n){ return n; }
16899 static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
16900 static void sqlite3MemShutdown(void *NotUsed){ return; }
16901
16902 /*
16903 ** This routine is the only routine in this file with external linkage.
16904 **
16905 ** Populate the low-level memory allocation function pointers in
16906 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
16907 */
16908 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
16909   static const sqlite3_mem_methods defaultMethods = {
16910      sqlite3MemMalloc,
16911      sqlite3MemFree,
16912      sqlite3MemRealloc,
16913      sqlite3MemSize,
16914      sqlite3MemRoundup,
16915      sqlite3MemInit,
16916      sqlite3MemShutdown,
16917      0
16918   };
16919   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
16920 }
16921
16922 #endif /* SQLITE_ZERO_MALLOC */
16923
16924 /************** End of mem0.c ************************************************/
16925 /************** Begin file mem1.c ********************************************/
16926 /*
16927 ** 2007 August 14
16928 **
16929 ** The author disclaims copyright to this source code.  In place of
16930 ** a legal notice, here is a blessing:
16931 **
16932 **    May you do good and not evil.
16933 **    May you find forgiveness for yourself and forgive others.
16934 **    May you share freely, never taking more than you give.
16935 **
16936 *************************************************************************
16937 **
16938 ** This file contains low-level memory allocation drivers for when
16939 ** SQLite will use the standard C-library malloc/realloc/free interface
16940 ** to obtain the memory it needs.
16941 **
16942 ** This file contains implementations of the low-level memory allocation
16943 ** routines specified in the sqlite3_mem_methods object.  The content of
16944 ** this file is only used if SQLITE_SYSTEM_MALLOC is defined.  The
16945 ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
16946 ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined.  The
16947 ** default configuration is to use memory allocation routines in this
16948 ** file.
16949 **
16950 ** C-preprocessor macro summary:
16951 **
16952 **    HAVE_MALLOC_USABLE_SIZE     The configure script sets this symbol if
16953 **                                the malloc_usable_size() interface exists
16954 **                                on the target platform.  Or, this symbol
16955 **                                can be set manually, if desired.
16956 **                                If an equivalent interface exists by
16957 **                                a different name, using a separate -D
16958 **                                option to rename it.
16959 **
16960 **    SQLITE_WITHOUT_ZONEMALLOC   Some older macs lack support for the zone
16961 **                                memory allocator.  Set this symbol to enable
16962 **                                building on older macs.
16963 **
16964 **    SQLITE_WITHOUT_MSIZE        Set this symbol to disable the use of
16965 **                                _msize() on windows systems.  This might
16966 **                                be necessary when compiling for Delphi,
16967 **                                for example.
16968 */
16969
16970 /*
16971 ** This version of the memory allocator is the default.  It is
16972 ** used when no other memory allocator is specified using compile-time
16973 ** macros.
16974 */
16975 #ifdef SQLITE_SYSTEM_MALLOC
16976 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
16977
16978 /*
16979 ** Use the zone allocator available on apple products unless the
16980 ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
16981 */
16982 #include <sys/sysctl.h>
16983 #include <malloc/malloc.h>
16984 #include <libkern/OSAtomic.h>
16985 static malloc_zone_t* _sqliteZone_;
16986 #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
16987 #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
16988 #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
16989 #define SQLITE_MALLOCSIZE(x) \
16990         (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
16991
16992 #else /* if not __APPLE__ */
16993
16994 /*
16995 ** Use standard C library malloc and free on non-Apple systems.  
16996 ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
16997 */
16998 #define SQLITE_MALLOC(x)             malloc(x)
16999 #define SQLITE_FREE(x)               free(x)
17000 #define SQLITE_REALLOC(x,y)          realloc((x),(y))
17001
17002 /*
17003 ** The malloc.h header file is needed for malloc_usable_size() function
17004 ** on some systems (e.g. Linux).
17005 */
17006 #if HAVE_MALLOC_H && HAVE_MALLOC_USABLE_SIZE
17007 #  define SQLITE_USE_MALLOC_H 1
17008 #  define SQLITE_USE_MALLOC_USABLE_SIZE 1
17009 /*
17010 ** The MSVCRT has malloc_usable_size(), but it is called _msize().  The
17011 ** use of _msize() is automatic, but can be disabled by compiling with
17012 ** -DSQLITE_WITHOUT_MSIZE.  Using the _msize() function also requires
17013 ** the malloc.h header file.
17014 */
17015 #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
17016 #  define SQLITE_USE_MALLOC_H
17017 #  define SQLITE_USE_MSIZE
17018 #endif
17019
17020 /*
17021 ** Include the malloc.h header file, if necessary.  Also set define macro
17022 ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
17023 ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
17024 ** The memory size function can always be overridden manually by defining
17025 ** the macro SQLITE_MALLOCSIZE to the desired function name.
17026 */
17027 #if defined(SQLITE_USE_MALLOC_H)
17028 #  include <malloc.h>
17029 #  if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
17030 #    if !defined(SQLITE_MALLOCSIZE)
17031 #      define SQLITE_MALLOCSIZE(x)   malloc_usable_size(x)
17032 #    endif
17033 #  elif defined(SQLITE_USE_MSIZE)
17034 #    if !defined(SQLITE_MALLOCSIZE)
17035 #      define SQLITE_MALLOCSIZE      _msize
17036 #    endif
17037 #  endif
17038 #endif /* defined(SQLITE_USE_MALLOC_H) */
17039
17040 #endif /* __APPLE__ or not __APPLE__ */
17041
17042 /*
17043 ** Like malloc(), but remember the size of the allocation
17044 ** so that we can find it later using sqlite3MemSize().
17045 **
17046 ** For this low-level routine, we are guaranteed that nByte>0 because
17047 ** cases of nByte<=0 will be intercepted and dealt with by higher level
17048 ** routines.
17049 */
17050 static void *sqlite3MemMalloc(int nByte){
17051 #ifdef SQLITE_MALLOCSIZE
17052   void *p = SQLITE_MALLOC( nByte );
17053   if( p==0 ){
17054     testcase( sqlite3GlobalConfig.xLog!=0 );
17055     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
17056   }
17057   return p;
17058 #else
17059   sqlite3_int64 *p;
17060   assert( nByte>0 );
17061   nByte = ROUND8(nByte);
17062   p = SQLITE_MALLOC( nByte+8 );
17063   if( p ){
17064     p[0] = nByte;
17065     p++;
17066   }else{
17067     testcase( sqlite3GlobalConfig.xLog!=0 );
17068     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
17069   }
17070   return (void *)p;
17071 #endif
17072 }
17073
17074 /*
17075 ** Like free() but works for allocations obtained from sqlite3MemMalloc()
17076 ** or sqlite3MemRealloc().
17077 **
17078 ** For this low-level routine, we already know that pPrior!=0 since
17079 ** cases where pPrior==0 will have been intecepted and dealt with
17080 ** by higher-level routines.
17081 */
17082 static void sqlite3MemFree(void *pPrior){
17083 #ifdef SQLITE_MALLOCSIZE
17084   SQLITE_FREE(pPrior);
17085 #else
17086   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
17087   assert( pPrior!=0 );
17088   p--;
17089   SQLITE_FREE(p);
17090 #endif
17091 }
17092
17093 /*
17094 ** Report the allocated size of a prior return from xMalloc()
17095 ** or xRealloc().
17096 */
17097 static int sqlite3MemSize(void *pPrior){
17098 #ifdef SQLITE_MALLOCSIZE
17099   return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
17100 #else
17101   sqlite3_int64 *p;
17102   if( pPrior==0 ) return 0;
17103   p = (sqlite3_int64*)pPrior;
17104   p--;
17105   return (int)p[0];
17106 #endif
17107 }
17108
17109 /*
17110 ** Like realloc().  Resize an allocation previously obtained from
17111 ** sqlite3MemMalloc().
17112 **
17113 ** For this low-level interface, we know that pPrior!=0.  Cases where
17114 ** pPrior==0 while have been intercepted by higher-level routine and
17115 ** redirected to xMalloc.  Similarly, we know that nByte>0 because
17116 ** cases where nByte<=0 will have been intercepted by higher-level
17117 ** routines and redirected to xFree.
17118 */
17119 static void *sqlite3MemRealloc(void *pPrior, int nByte){
17120 #ifdef SQLITE_MALLOCSIZE
17121   void *p = SQLITE_REALLOC(pPrior, nByte);
17122   if( p==0 ){
17123     testcase( sqlite3GlobalConfig.xLog!=0 );
17124     sqlite3_log(SQLITE_NOMEM,
17125       "failed memory resize %u to %u bytes",
17126       SQLITE_MALLOCSIZE(pPrior), nByte);
17127   }
17128   return p;
17129 #else
17130   sqlite3_int64 *p = (sqlite3_int64*)pPrior;
17131   assert( pPrior!=0 && nByte>0 );
17132   assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
17133   p--;
17134   p = SQLITE_REALLOC(p, nByte+8 );
17135   if( p ){
17136     p[0] = nByte;
17137     p++;
17138   }else{
17139     testcase( sqlite3GlobalConfig.xLog!=0 );
17140     sqlite3_log(SQLITE_NOMEM,
17141       "failed memory resize %u to %u bytes",
17142       sqlite3MemSize(pPrior), nByte);
17143   }
17144   return (void*)p;
17145 #endif
17146 }
17147
17148 /*
17149 ** Round up a request size to the next valid allocation size.
17150 */
17151 static int sqlite3MemRoundup(int n){
17152   return ROUND8(n);
17153 }
17154
17155 /*
17156 ** Initialize this module.
17157 */
17158 static int sqlite3MemInit(void *NotUsed){
17159 #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
17160   int cpuCount;
17161   size_t len;
17162   if( _sqliteZone_ ){
17163     return SQLITE_OK;
17164   }
17165   len = sizeof(cpuCount);
17166   /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
17167   sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
17168   if( cpuCount>1 ){
17169     /* defer MT decisions to system malloc */
17170     _sqliteZone_ = malloc_default_zone();
17171   }else{
17172     /* only 1 core, use our own zone to contention over global locks, 
17173     ** e.g. we have our own dedicated locks */
17174     bool success;
17175     malloc_zone_t* newzone = malloc_create_zone(4096, 0);
17176     malloc_set_zone_name(newzone, "Sqlite_Heap");
17177     do{
17178       success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone, 
17179                                  (void * volatile *)&_sqliteZone_);
17180     }while(!_sqliteZone_);
17181     if( !success ){
17182       /* somebody registered a zone first */
17183       malloc_destroy_zone(newzone);
17184     }
17185   }
17186 #endif
17187   UNUSED_PARAMETER(NotUsed);
17188   return SQLITE_OK;
17189 }
17190
17191 /*
17192 ** Deinitialize this module.
17193 */
17194 static void sqlite3MemShutdown(void *NotUsed){
17195   UNUSED_PARAMETER(NotUsed);
17196   return;
17197 }
17198
17199 /*
17200 ** This routine is the only routine in this file with external linkage.
17201 **
17202 ** Populate the low-level memory allocation function pointers in
17203 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
17204 */
17205 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
17206   static const sqlite3_mem_methods defaultMethods = {
17207      sqlite3MemMalloc,
17208      sqlite3MemFree,
17209      sqlite3MemRealloc,
17210      sqlite3MemSize,
17211      sqlite3MemRoundup,
17212      sqlite3MemInit,
17213      sqlite3MemShutdown,
17214      0
17215   };
17216   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
17217 }
17218
17219 #endif /* SQLITE_SYSTEM_MALLOC */
17220
17221 /************** End of mem1.c ************************************************/
17222 /************** Begin file mem2.c ********************************************/
17223 /*
17224 ** 2007 August 15
17225 **
17226 ** The author disclaims copyright to this source code.  In place of
17227 ** a legal notice, here is a blessing:
17228 **
17229 **    May you do good and not evil.
17230 **    May you find forgiveness for yourself and forgive others.
17231 **    May you share freely, never taking more than you give.
17232 **
17233 *************************************************************************
17234 **
17235 ** This file contains low-level memory allocation drivers for when
17236 ** SQLite will use the standard C-library malloc/realloc/free interface
17237 ** to obtain the memory it needs while adding lots of additional debugging
17238 ** information to each allocation in order to help detect and fix memory
17239 ** leaks and memory usage errors.
17240 **
17241 ** This file contains implementations of the low-level memory allocation
17242 ** routines specified in the sqlite3_mem_methods object.
17243 */
17244
17245 /*
17246 ** This version of the memory allocator is used only if the
17247 ** SQLITE_MEMDEBUG macro is defined
17248 */
17249 #ifdef SQLITE_MEMDEBUG
17250
17251 /*
17252 ** The backtrace functionality is only available with GLIBC
17253 */
17254 #ifdef __GLIBC__
17255   extern int backtrace(void**,int);
17256   extern void backtrace_symbols_fd(void*const*,int,int);
17257 #else
17258 # define backtrace(A,B) 1
17259 # define backtrace_symbols_fd(A,B,C)
17260 #endif
17261 /* #include <stdio.h> */
17262
17263 /*
17264 ** Each memory allocation looks like this:
17265 **
17266 **  ------------------------------------------------------------------------
17267 **  | Title |  backtrace pointers |  MemBlockHdr |  allocation |  EndGuard |
17268 **  ------------------------------------------------------------------------
17269 **
17270 ** The application code sees only a pointer to the allocation.  We have
17271 ** to back up from the allocation pointer to find the MemBlockHdr.  The
17272 ** MemBlockHdr tells us the size of the allocation and the number of
17273 ** backtrace pointers.  There is also a guard word at the end of the
17274 ** MemBlockHdr.
17275 */
17276 struct MemBlockHdr {
17277   i64 iSize;                          /* Size of this allocation */
17278   struct MemBlockHdr *pNext, *pPrev;  /* Linked list of all unfreed memory */
17279   char nBacktrace;                    /* Number of backtraces on this alloc */
17280   char nBacktraceSlots;               /* Available backtrace slots */
17281   u8 nTitle;                          /* Bytes of title; includes '\0' */
17282   u8 eType;                           /* Allocation type code */
17283   int iForeGuard;                     /* Guard word for sanity */
17284 };
17285
17286 /*
17287 ** Guard words
17288 */
17289 #define FOREGUARD 0x80F5E153
17290 #define REARGUARD 0xE4676B53
17291
17292 /*
17293 ** Number of malloc size increments to track.
17294 */
17295 #define NCSIZE  1000
17296
17297 /*
17298 ** All of the static variables used by this module are collected
17299 ** into a single structure named "mem".  This is to keep the
17300 ** static variables organized and to reduce namespace pollution
17301 ** when this module is combined with other in the amalgamation.
17302 */
17303 static struct {
17304   
17305   /*
17306   ** Mutex to control access to the memory allocation subsystem.
17307   */
17308   sqlite3_mutex *mutex;
17309
17310   /*
17311   ** Head and tail of a linked list of all outstanding allocations
17312   */
17313   struct MemBlockHdr *pFirst;
17314   struct MemBlockHdr *pLast;
17315   
17316   /*
17317   ** The number of levels of backtrace to save in new allocations.
17318   */
17319   int nBacktrace;
17320   void (*xBacktrace)(int, int, void **);
17321
17322   /*
17323   ** Title text to insert in front of each block
17324   */
17325   int nTitle;        /* Bytes of zTitle to save.  Includes '\0' and padding */
17326   char zTitle[100];  /* The title text */
17327
17328   /* 
17329   ** sqlite3MallocDisallow() increments the following counter.
17330   ** sqlite3MallocAllow() decrements it.
17331   */
17332   int disallow; /* Do not allow memory allocation */
17333
17334   /*
17335   ** Gather statistics on the sizes of memory allocations.
17336   ** nAlloc[i] is the number of allocation attempts of i*8
17337   ** bytes.  i==NCSIZE is the number of allocation attempts for
17338   ** sizes more than NCSIZE*8 bytes.
17339   */
17340   int nAlloc[NCSIZE];      /* Total number of allocations */
17341   int nCurrent[NCSIZE];    /* Current number of allocations */
17342   int mxCurrent[NCSIZE];   /* Highwater mark for nCurrent */
17343
17344 } mem;
17345
17346
17347 /*
17348 ** Adjust memory usage statistics
17349 */
17350 static void adjustStats(int iSize, int increment){
17351   int i = ROUND8(iSize)/8;
17352   if( i>NCSIZE-1 ){
17353     i = NCSIZE - 1;
17354   }
17355   if( increment>0 ){
17356     mem.nAlloc[i]++;
17357     mem.nCurrent[i]++;
17358     if( mem.nCurrent[i]>mem.mxCurrent[i] ){
17359       mem.mxCurrent[i] = mem.nCurrent[i];
17360     }
17361   }else{
17362     mem.nCurrent[i]--;
17363     assert( mem.nCurrent[i]>=0 );
17364   }
17365 }
17366
17367 /*
17368 ** Given an allocation, find the MemBlockHdr for that allocation.
17369 **
17370 ** This routine checks the guards at either end of the allocation and
17371 ** if they are incorrect it asserts.
17372 */
17373 static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
17374   struct MemBlockHdr *p;
17375   int *pInt;
17376   u8 *pU8;
17377   int nReserve;
17378
17379   p = (struct MemBlockHdr*)pAllocation;
17380   p--;
17381   assert( p->iForeGuard==(int)FOREGUARD );
17382   nReserve = ROUND8(p->iSize);
17383   pInt = (int*)pAllocation;
17384   pU8 = (u8*)pAllocation;
17385   assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
17386   /* This checks any of the "extra" bytes allocated due
17387   ** to rounding up to an 8 byte boundary to ensure 
17388   ** they haven't been overwritten.
17389   */
17390   while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
17391   return p;
17392 }
17393
17394 /*
17395 ** Return the number of bytes currently allocated at address p.
17396 */
17397 static int sqlite3MemSize(void *p){
17398   struct MemBlockHdr *pHdr;
17399   if( !p ){
17400     return 0;
17401   }
17402   pHdr = sqlite3MemsysGetHeader(p);
17403   return (int)pHdr->iSize;
17404 }
17405
17406 /*
17407 ** Initialize the memory allocation subsystem.
17408 */
17409 static int sqlite3MemInit(void *NotUsed){
17410   UNUSED_PARAMETER(NotUsed);
17411   assert( (sizeof(struct MemBlockHdr)&7) == 0 );
17412   if( !sqlite3GlobalConfig.bMemstat ){
17413     /* If memory status is enabled, then the malloc.c wrapper will already
17414     ** hold the STATIC_MEM mutex when the routines here are invoked. */
17415     mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17416   }
17417   return SQLITE_OK;
17418 }
17419
17420 /*
17421 ** Deinitialize the memory allocation subsystem.
17422 */
17423 static void sqlite3MemShutdown(void *NotUsed){
17424   UNUSED_PARAMETER(NotUsed);
17425   mem.mutex = 0;
17426 }
17427
17428 /*
17429 ** Round up a request size to the next valid allocation size.
17430 */
17431 static int sqlite3MemRoundup(int n){
17432   return ROUND8(n);
17433 }
17434
17435 /*
17436 ** Fill a buffer with pseudo-random bytes.  This is used to preset
17437 ** the content of a new memory allocation to unpredictable values and
17438 ** to clear the content of a freed allocation to unpredictable values.
17439 */
17440 static void randomFill(char *pBuf, int nByte){
17441   unsigned int x, y, r;
17442   x = SQLITE_PTR_TO_INT(pBuf);
17443   y = nByte | 1;
17444   while( nByte >= 4 ){
17445     x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
17446     y = y*1103515245 + 12345;
17447     r = x ^ y;
17448     *(int*)pBuf = r;
17449     pBuf += 4;
17450     nByte -= 4;
17451   }
17452   while( nByte-- > 0 ){
17453     x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
17454     y = y*1103515245 + 12345;
17455     r = x ^ y;
17456     *(pBuf++) = r & 0xff;
17457   }
17458 }
17459
17460 /*
17461 ** Allocate nByte bytes of memory.
17462 */
17463 static void *sqlite3MemMalloc(int nByte){
17464   struct MemBlockHdr *pHdr;
17465   void **pBt;
17466   char *z;
17467   int *pInt;
17468   void *p = 0;
17469   int totalSize;
17470   int nReserve;
17471   sqlite3_mutex_enter(mem.mutex);
17472   assert( mem.disallow==0 );
17473   nReserve = ROUND8(nByte);
17474   totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
17475                mem.nBacktrace*sizeof(void*) + mem.nTitle;
17476   p = malloc(totalSize);
17477   if( p ){
17478     z = p;
17479     pBt = (void**)&z[mem.nTitle];
17480     pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
17481     pHdr->pNext = 0;
17482     pHdr->pPrev = mem.pLast;
17483     if( mem.pLast ){
17484       mem.pLast->pNext = pHdr;
17485     }else{
17486       mem.pFirst = pHdr;
17487     }
17488     mem.pLast = pHdr;
17489     pHdr->iForeGuard = FOREGUARD;
17490     pHdr->eType = MEMTYPE_HEAP;
17491     pHdr->nBacktraceSlots = mem.nBacktrace;
17492     pHdr->nTitle = mem.nTitle;
17493     if( mem.nBacktrace ){
17494       void *aAddr[40];
17495       pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
17496       memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
17497       assert(pBt[0]);
17498       if( mem.xBacktrace ){
17499         mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
17500       }
17501     }else{
17502       pHdr->nBacktrace = 0;
17503     }
17504     if( mem.nTitle ){
17505       memcpy(z, mem.zTitle, mem.nTitle);
17506     }
17507     pHdr->iSize = nByte;
17508     adjustStats(nByte, +1);
17509     pInt = (int*)&pHdr[1];
17510     pInt[nReserve/sizeof(int)] = REARGUARD;
17511     randomFill((char*)pInt, nByte);
17512     memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
17513     p = (void*)pInt;
17514   }
17515   sqlite3_mutex_leave(mem.mutex);
17516   return p; 
17517 }
17518
17519 /*
17520 ** Free memory.
17521 */
17522 static void sqlite3MemFree(void *pPrior){
17523   struct MemBlockHdr *pHdr;
17524   void **pBt;
17525   char *z;
17526   assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0 
17527        || mem.mutex!=0 );
17528   pHdr = sqlite3MemsysGetHeader(pPrior);
17529   pBt = (void**)pHdr;
17530   pBt -= pHdr->nBacktraceSlots;
17531   sqlite3_mutex_enter(mem.mutex);
17532   if( pHdr->pPrev ){
17533     assert( pHdr->pPrev->pNext==pHdr );
17534     pHdr->pPrev->pNext = pHdr->pNext;
17535   }else{
17536     assert( mem.pFirst==pHdr );
17537     mem.pFirst = pHdr->pNext;
17538   }
17539   if( pHdr->pNext ){
17540     assert( pHdr->pNext->pPrev==pHdr );
17541     pHdr->pNext->pPrev = pHdr->pPrev;
17542   }else{
17543     assert( mem.pLast==pHdr );
17544     mem.pLast = pHdr->pPrev;
17545   }
17546   z = (char*)pBt;
17547   z -= pHdr->nTitle;
17548   adjustStats((int)pHdr->iSize, -1);
17549   randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
17550                 (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
17551   free(z);
17552   sqlite3_mutex_leave(mem.mutex);  
17553 }
17554
17555 /*
17556 ** Change the size of an existing memory allocation.
17557 **
17558 ** For this debugging implementation, we *always* make a copy of the
17559 ** allocation into a new place in memory.  In this way, if the 
17560 ** higher level code is using pointer to the old allocation, it is 
17561 ** much more likely to break and we are much more liking to find
17562 ** the error.
17563 */
17564 static void *sqlite3MemRealloc(void *pPrior, int nByte){
17565   struct MemBlockHdr *pOldHdr;
17566   void *pNew;
17567   assert( mem.disallow==0 );
17568   assert( (nByte & 7)==0 );     /* EV: R-46199-30249 */
17569   pOldHdr = sqlite3MemsysGetHeader(pPrior);
17570   pNew = sqlite3MemMalloc(nByte);
17571   if( pNew ){
17572     memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
17573     if( nByte>pOldHdr->iSize ){
17574       randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
17575     }
17576     sqlite3MemFree(pPrior);
17577   }
17578   return pNew;
17579 }
17580
17581 /*
17582 ** Populate the low-level memory allocation function pointers in
17583 ** sqlite3GlobalConfig.m with pointers to the routines in this file.
17584 */
17585 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
17586   static const sqlite3_mem_methods defaultMethods = {
17587      sqlite3MemMalloc,
17588      sqlite3MemFree,
17589      sqlite3MemRealloc,
17590      sqlite3MemSize,
17591      sqlite3MemRoundup,
17592      sqlite3MemInit,
17593      sqlite3MemShutdown,
17594      0
17595   };
17596   sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
17597 }
17598
17599 /*
17600 ** Set the "type" of an allocation.
17601 */
17602 SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
17603   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
17604     struct MemBlockHdr *pHdr;
17605     pHdr = sqlite3MemsysGetHeader(p);
17606     assert( pHdr->iForeGuard==FOREGUARD );
17607     pHdr->eType = eType;
17608   }
17609 }
17610
17611 /*
17612 ** Return TRUE if the mask of type in eType matches the type of the
17613 ** allocation p.  Also return true if p==NULL.
17614 **
17615 ** This routine is designed for use within an assert() statement, to
17616 ** verify the type of an allocation.  For example:
17617 **
17618 **     assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
17619 */
17620 SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
17621   int rc = 1;
17622   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
17623     struct MemBlockHdr *pHdr;
17624     pHdr = sqlite3MemsysGetHeader(p);
17625     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
17626     if( (pHdr->eType&eType)==0 ){
17627       rc = 0;
17628     }
17629   }
17630   return rc;
17631 }
17632
17633 /*
17634 ** Return TRUE if the mask of type in eType matches no bits of the type of the
17635 ** allocation p.  Also return true if p==NULL.
17636 **
17637 ** This routine is designed for use within an assert() statement, to
17638 ** verify the type of an allocation.  For example:
17639 **
17640 **     assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
17641 */
17642 SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
17643   int rc = 1;
17644   if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
17645     struct MemBlockHdr *pHdr;
17646     pHdr = sqlite3MemsysGetHeader(p);
17647     assert( pHdr->iForeGuard==FOREGUARD );         /* Allocation is valid */
17648     if( (pHdr->eType&eType)!=0 ){
17649       rc = 0;
17650     }
17651   }
17652   return rc;
17653 }
17654
17655 /*
17656 ** Set the number of backtrace levels kept for each allocation.
17657 ** A value of zero turns off backtracing.  The number is always rounded
17658 ** up to a multiple of 2.
17659 */
17660 SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
17661   if( depth<0 ){ depth = 0; }
17662   if( depth>20 ){ depth = 20; }
17663   depth = (depth+1)&0xfe;
17664   mem.nBacktrace = depth;
17665 }
17666
17667 SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
17668   mem.xBacktrace = xBacktrace;
17669 }
17670
17671 /*
17672 ** Set the title string for subsequent allocations.
17673 */
17674 SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
17675   unsigned int n = sqlite3Strlen30(zTitle) + 1;
17676   sqlite3_mutex_enter(mem.mutex);
17677   if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
17678   memcpy(mem.zTitle, zTitle, n);
17679   mem.zTitle[n] = 0;
17680   mem.nTitle = ROUND8(n);
17681   sqlite3_mutex_leave(mem.mutex);
17682 }
17683
17684 SQLITE_PRIVATE void sqlite3MemdebugSync(){
17685   struct MemBlockHdr *pHdr;
17686   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
17687     void **pBt = (void**)pHdr;
17688     pBt -= pHdr->nBacktraceSlots;
17689     mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
17690   }
17691 }
17692
17693 /*
17694 ** Open the file indicated and write a log of all unfreed memory 
17695 ** allocations into that log.
17696 */
17697 SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
17698   FILE *out;
17699   struct MemBlockHdr *pHdr;
17700   void **pBt;
17701   int i;
17702   out = fopen(zFilename, "w");
17703   if( out==0 ){
17704     fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
17705                     zFilename);
17706     return;
17707   }
17708   for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
17709     char *z = (char*)pHdr;
17710     z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
17711     fprintf(out, "**** %lld bytes at %p from %s ****\n", 
17712             pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
17713     if( pHdr->nBacktrace ){
17714       fflush(out);
17715       pBt = (void**)pHdr;
17716       pBt -= pHdr->nBacktraceSlots;
17717       backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
17718       fprintf(out, "\n");
17719     }
17720   }
17721   fprintf(out, "COUNTS:\n");
17722   for(i=0; i<NCSIZE-1; i++){
17723     if( mem.nAlloc[i] ){
17724       fprintf(out, "   %5d: %10d %10d %10d\n", 
17725             i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
17726     }
17727   }
17728   if( mem.nAlloc[NCSIZE-1] ){
17729     fprintf(out, "   %5d: %10d %10d %10d\n",
17730              NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
17731              mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
17732   }
17733   fclose(out);
17734 }
17735
17736 /*
17737 ** Return the number of times sqlite3MemMalloc() has been called.
17738 */
17739 SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
17740   int i;
17741   int nTotal = 0;
17742   for(i=0; i<NCSIZE; i++){
17743     nTotal += mem.nAlloc[i];
17744   }
17745   return nTotal;
17746 }
17747
17748
17749 #endif /* SQLITE_MEMDEBUG */
17750
17751 /************** End of mem2.c ************************************************/
17752 /************** Begin file mem3.c ********************************************/
17753 /*
17754 ** 2007 October 14
17755 **
17756 ** The author disclaims copyright to this source code.  In place of
17757 ** a legal notice, here is a blessing:
17758 **
17759 **    May you do good and not evil.
17760 **    May you find forgiveness for yourself and forgive others.
17761 **    May you share freely, never taking more than you give.
17762 **
17763 *************************************************************************
17764 ** This file contains the C functions that implement a memory
17765 ** allocation subsystem for use by SQLite. 
17766 **
17767 ** This version of the memory allocation subsystem omits all
17768 ** use of malloc(). The SQLite user supplies a block of memory
17769 ** before calling sqlite3_initialize() from which allocations
17770 ** are made and returned by the xMalloc() and xRealloc() 
17771 ** implementations. Once sqlite3_initialize() has been called,
17772 ** the amount of memory available to SQLite is fixed and cannot
17773 ** be changed.
17774 **
17775 ** This version of the memory allocation subsystem is included
17776 ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
17777 */
17778
17779 /*
17780 ** This version of the memory allocator is only built into the library
17781 ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
17782 ** mean that the library will use a memory-pool by default, just that
17783 ** it is available. The mempool allocator is activated by calling
17784 ** sqlite3_config().
17785 */
17786 #ifdef SQLITE_ENABLE_MEMSYS3
17787
17788 /*
17789 ** Maximum size (in Mem3Blocks) of a "small" chunk.
17790 */
17791 #define MX_SMALL 10
17792
17793
17794 /*
17795 ** Number of freelist hash slots
17796 */
17797 #define N_HASH  61
17798
17799 /*
17800 ** A memory allocation (also called a "chunk") consists of two or 
17801 ** more blocks where each block is 8 bytes.  The first 8 bytes are 
17802 ** a header that is not returned to the user.
17803 **
17804 ** A chunk is two or more blocks that is either checked out or
17805 ** free.  The first block has format u.hdr.  u.hdr.size4x is 4 times the
17806 ** size of the allocation in blocks if the allocation is free.
17807 ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
17808 ** false if the chunk is on the freelist.  The u.hdr.size4x&2 bit
17809 ** is true if the previous chunk is checked out and false if the
17810 ** previous chunk is free.  The u.hdr.prevSize field is the size of
17811 ** the previous chunk in blocks if the previous chunk is on the
17812 ** freelist. If the previous chunk is checked out, then
17813 ** u.hdr.prevSize can be part of the data for that chunk and should
17814 ** not be read or written.
17815 **
17816 ** We often identify a chunk by its index in mem3.aPool[].  When
17817 ** this is done, the chunk index refers to the second block of
17818 ** the chunk.  In this way, the first chunk has an index of 1.
17819 ** A chunk index of 0 means "no such chunk" and is the equivalent
17820 ** of a NULL pointer.
17821 **
17822 ** The second block of free chunks is of the form u.list.  The
17823 ** two fields form a double-linked list of chunks of related sizes.
17824 ** Pointers to the head of the list are stored in mem3.aiSmall[] 
17825 ** for smaller chunks and mem3.aiHash[] for larger chunks.
17826 **
17827 ** The second block of a chunk is user data if the chunk is checked 
17828 ** out.  If a chunk is checked out, the user data may extend into
17829 ** the u.hdr.prevSize value of the following chunk.
17830 */
17831 typedef struct Mem3Block Mem3Block;
17832 struct Mem3Block {
17833   union {
17834     struct {
17835       u32 prevSize;   /* Size of previous chunk in Mem3Block elements */
17836       u32 size4x;     /* 4x the size of current chunk in Mem3Block elements */
17837     } hdr;
17838     struct {
17839       u32 next;       /* Index in mem3.aPool[] of next free chunk */
17840       u32 prev;       /* Index in mem3.aPool[] of previous free chunk */
17841     } list;
17842   } u;
17843 };
17844
17845 /*
17846 ** All of the static variables used by this module are collected
17847 ** into a single structure named "mem3".  This is to keep the
17848 ** static variables organized and to reduce namespace pollution
17849 ** when this module is combined with other in the amalgamation.
17850 */
17851 static SQLITE_WSD struct Mem3Global {
17852   /*
17853   ** Memory available for allocation. nPool is the size of the array
17854   ** (in Mem3Blocks) pointed to by aPool less 2.
17855   */
17856   u32 nPool;
17857   Mem3Block *aPool;
17858
17859   /*
17860   ** True if we are evaluating an out-of-memory callback.
17861   */
17862   int alarmBusy;
17863   
17864   /*
17865   ** Mutex to control access to the memory allocation subsystem.
17866   */
17867   sqlite3_mutex *mutex;
17868   
17869   /*
17870   ** The minimum amount of free space that we have seen.
17871   */
17872   u32 mnMaster;
17873
17874   /*
17875   ** iMaster is the index of the master chunk.  Most new allocations
17876   ** occur off of this chunk.  szMaster is the size (in Mem3Blocks)
17877   ** of the current master.  iMaster is 0 if there is not master chunk.
17878   ** The master chunk is not in either the aiHash[] or aiSmall[].
17879   */
17880   u32 iMaster;
17881   u32 szMaster;
17882
17883   /*
17884   ** Array of lists of free blocks according to the block size 
17885   ** for smaller chunks, or a hash on the block size for larger
17886   ** chunks.
17887   */
17888   u32 aiSmall[MX_SMALL-1];   /* For sizes 2 through MX_SMALL, inclusive */
17889   u32 aiHash[N_HASH];        /* For sizes MX_SMALL+1 and larger */
17890 } mem3 = { 97535575 };
17891
17892 #define mem3 GLOBAL(struct Mem3Global, mem3)
17893
17894 /*
17895 ** Unlink the chunk at mem3.aPool[i] from list it is currently
17896 ** on.  *pRoot is the list that i is a member of.
17897 */
17898 static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
17899   u32 next = mem3.aPool[i].u.list.next;
17900   u32 prev = mem3.aPool[i].u.list.prev;
17901   assert( sqlite3_mutex_held(mem3.mutex) );
17902   if( prev==0 ){
17903     *pRoot = next;
17904   }else{
17905     mem3.aPool[prev].u.list.next = next;
17906   }
17907   if( next ){
17908     mem3.aPool[next].u.list.prev = prev;
17909   }
17910   mem3.aPool[i].u.list.next = 0;
17911   mem3.aPool[i].u.list.prev = 0;
17912 }
17913
17914 /*
17915 ** Unlink the chunk at index i from 
17916 ** whatever list is currently a member of.
17917 */
17918 static void memsys3Unlink(u32 i){
17919   u32 size, hash;
17920   assert( sqlite3_mutex_held(mem3.mutex) );
17921   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
17922   assert( i>=1 );
17923   size = mem3.aPool[i-1].u.hdr.size4x/4;
17924   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
17925   assert( size>=2 );
17926   if( size <= MX_SMALL ){
17927     memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
17928   }else{
17929     hash = size % N_HASH;
17930     memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
17931   }
17932 }
17933
17934 /*
17935 ** Link the chunk at mem3.aPool[i] so that is on the list rooted
17936 ** at *pRoot.
17937 */
17938 static void memsys3LinkIntoList(u32 i, u32 *pRoot){
17939   assert( sqlite3_mutex_held(mem3.mutex) );
17940   mem3.aPool[i].u.list.next = *pRoot;
17941   mem3.aPool[i].u.list.prev = 0;
17942   if( *pRoot ){
17943     mem3.aPool[*pRoot].u.list.prev = i;
17944   }
17945   *pRoot = i;
17946 }
17947
17948 /*
17949 ** Link the chunk at index i into either the appropriate
17950 ** small chunk list, or into the large chunk hash table.
17951 */
17952 static void memsys3Link(u32 i){
17953   u32 size, hash;
17954   assert( sqlite3_mutex_held(mem3.mutex) );
17955   assert( i>=1 );
17956   assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
17957   size = mem3.aPool[i-1].u.hdr.size4x/4;
17958   assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
17959   assert( size>=2 );
17960   if( size <= MX_SMALL ){
17961     memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
17962   }else{
17963     hash = size % N_HASH;
17964     memsys3LinkIntoList(i, &mem3.aiHash[hash]);
17965   }
17966 }
17967
17968 /*
17969 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
17970 ** will already be held (obtained by code in malloc.c) if
17971 ** sqlite3GlobalConfig.bMemStat is true.
17972 */
17973 static void memsys3Enter(void){
17974   if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
17975     mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
17976   }
17977   sqlite3_mutex_enter(mem3.mutex);
17978 }
17979 static void memsys3Leave(void){
17980   sqlite3_mutex_leave(mem3.mutex);
17981 }
17982
17983 /*
17984 ** Called when we are unable to satisfy an allocation of nBytes.
17985 */
17986 static void memsys3OutOfMemory(int nByte){
17987   if( !mem3.alarmBusy ){
17988     mem3.alarmBusy = 1;
17989     assert( sqlite3_mutex_held(mem3.mutex) );
17990     sqlite3_mutex_leave(mem3.mutex);
17991     sqlite3_release_memory(nByte);
17992     sqlite3_mutex_enter(mem3.mutex);
17993     mem3.alarmBusy = 0;
17994   }
17995 }
17996
17997
17998 /*
17999 ** Chunk i is a free chunk that has been unlinked.  Adjust its 
18000 ** size parameters for check-out and return a pointer to the 
18001 ** user portion of the chunk.
18002 */
18003 static void *memsys3Checkout(u32 i, u32 nBlock){
18004   u32 x;
18005   assert( sqlite3_mutex_held(mem3.mutex) );
18006   assert( i>=1 );
18007   assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
18008   assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
18009   x = mem3.aPool[i-1].u.hdr.size4x;
18010   mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
18011   mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
18012   mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
18013   return &mem3.aPool[i];
18014 }
18015
18016 /*
18017 ** Carve a piece off of the end of the mem3.iMaster free chunk.
18018 ** Return a pointer to the new allocation.  Or, if the master chunk
18019 ** is not large enough, return 0.
18020 */
18021 static void *memsys3FromMaster(u32 nBlock){
18022   assert( sqlite3_mutex_held(mem3.mutex) );
18023   assert( mem3.szMaster>=nBlock );
18024   if( nBlock>=mem3.szMaster-1 ){
18025     /* Use the entire master */
18026     void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
18027     mem3.iMaster = 0;
18028     mem3.szMaster = 0;
18029     mem3.mnMaster = 0;
18030     return p;
18031   }else{
18032     /* Split the master block.  Return the tail. */
18033     u32 newi, x;
18034     newi = mem3.iMaster + mem3.szMaster - nBlock;
18035     assert( newi > mem3.iMaster+1 );
18036     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
18037     mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
18038     mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
18039     mem3.szMaster -= nBlock;
18040     mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
18041     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
18042     mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
18043     if( mem3.szMaster < mem3.mnMaster ){
18044       mem3.mnMaster = mem3.szMaster;
18045     }
18046     return (void*)&mem3.aPool[newi];
18047   }
18048 }
18049
18050 /*
18051 ** *pRoot is the head of a list of free chunks of the same size
18052 ** or same size hash.  In other words, *pRoot is an entry in either
18053 ** mem3.aiSmall[] or mem3.aiHash[].  
18054 **
18055 ** This routine examines all entries on the given list and tries
18056 ** to coalesce each entries with adjacent free chunks.  
18057 **
18058 ** If it sees a chunk that is larger than mem3.iMaster, it replaces 
18059 ** the current mem3.iMaster with the new larger chunk.  In order for
18060 ** this mem3.iMaster replacement to work, the master chunk must be
18061 ** linked into the hash tables.  That is not the normal state of
18062 ** affairs, of course.  The calling routine must link the master
18063 ** chunk before invoking this routine, then must unlink the (possibly
18064 ** changed) master chunk once this routine has finished.
18065 */
18066 static void memsys3Merge(u32 *pRoot){
18067   u32 iNext, prev, size, i, x;
18068
18069   assert( sqlite3_mutex_held(mem3.mutex) );
18070   for(i=*pRoot; i>0; i=iNext){
18071     iNext = mem3.aPool[i].u.list.next;
18072     size = mem3.aPool[i-1].u.hdr.size4x;
18073     assert( (size&1)==0 );
18074     if( (size&2)==0 ){
18075       memsys3UnlinkFromList(i, pRoot);
18076       assert( i > mem3.aPool[i-1].u.hdr.prevSize );
18077       prev = i - mem3.aPool[i-1].u.hdr.prevSize;
18078       if( prev==iNext ){
18079         iNext = mem3.aPool[prev].u.list.next;
18080       }
18081       memsys3Unlink(prev);
18082       size = i + size/4 - prev;
18083       x = mem3.aPool[prev-1].u.hdr.size4x & 2;
18084       mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
18085       mem3.aPool[prev+size-1].u.hdr.prevSize = size;
18086       memsys3Link(prev);
18087       i = prev;
18088     }else{
18089       size /= 4;
18090     }
18091     if( size>mem3.szMaster ){
18092       mem3.iMaster = i;
18093       mem3.szMaster = size;
18094     }
18095   }
18096 }
18097
18098 /*
18099 ** Return a block of memory of at least nBytes in size.
18100 ** Return NULL if unable.
18101 **
18102 ** This function assumes that the necessary mutexes, if any, are
18103 ** already held by the caller. Hence "Unsafe".
18104 */
18105 static void *memsys3MallocUnsafe(int nByte){
18106   u32 i;
18107   u32 nBlock;
18108   u32 toFree;
18109
18110   assert( sqlite3_mutex_held(mem3.mutex) );
18111   assert( sizeof(Mem3Block)==8 );
18112   if( nByte<=12 ){
18113     nBlock = 2;
18114   }else{
18115     nBlock = (nByte + 11)/8;
18116   }
18117   assert( nBlock>=2 );
18118
18119   /* STEP 1:
18120   ** Look for an entry of the correct size in either the small
18121   ** chunk table or in the large chunk hash table.  This is
18122   ** successful most of the time (about 9 times out of 10).
18123   */
18124   if( nBlock <= MX_SMALL ){
18125     i = mem3.aiSmall[nBlock-2];
18126     if( i>0 ){
18127       memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
18128       return memsys3Checkout(i, nBlock);
18129     }
18130   }else{
18131     int hash = nBlock % N_HASH;
18132     for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
18133       if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
18134         memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
18135         return memsys3Checkout(i, nBlock);
18136       }
18137     }
18138   }
18139
18140   /* STEP 2:
18141   ** Try to satisfy the allocation by carving a piece off of the end
18142   ** of the master chunk.  This step usually works if step 1 fails.
18143   */
18144   if( mem3.szMaster>=nBlock ){
18145     return memsys3FromMaster(nBlock);
18146   }
18147
18148
18149   /* STEP 3:  
18150   ** Loop through the entire memory pool.  Coalesce adjacent free
18151   ** chunks.  Recompute the master chunk as the largest free chunk.
18152   ** Then try again to satisfy the allocation by carving a piece off
18153   ** of the end of the master chunk.  This step happens very
18154   ** rarely (we hope!)
18155   */
18156   for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
18157     memsys3OutOfMemory(toFree);
18158     if( mem3.iMaster ){
18159       memsys3Link(mem3.iMaster);
18160       mem3.iMaster = 0;
18161       mem3.szMaster = 0;
18162     }
18163     for(i=0; i<N_HASH; i++){
18164       memsys3Merge(&mem3.aiHash[i]);
18165     }
18166     for(i=0; i<MX_SMALL-1; i++){
18167       memsys3Merge(&mem3.aiSmall[i]);
18168     }
18169     if( mem3.szMaster ){
18170       memsys3Unlink(mem3.iMaster);
18171       if( mem3.szMaster>=nBlock ){
18172         return memsys3FromMaster(nBlock);
18173       }
18174     }
18175   }
18176
18177   /* If none of the above worked, then we fail. */
18178   return 0;
18179 }
18180
18181 /*
18182 ** Free an outstanding memory allocation.
18183 **
18184 ** This function assumes that the necessary mutexes, if any, are
18185 ** already held by the caller. Hence "Unsafe".
18186 */
18187 static void memsys3FreeUnsafe(void *pOld){
18188   Mem3Block *p = (Mem3Block*)pOld;
18189   int i;
18190   u32 size, x;
18191   assert( sqlite3_mutex_held(mem3.mutex) );
18192   assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
18193   i = p - mem3.aPool;
18194   assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
18195   size = mem3.aPool[i-1].u.hdr.size4x/4;
18196   assert( i+size<=mem3.nPool+1 );
18197   mem3.aPool[i-1].u.hdr.size4x &= ~1;
18198   mem3.aPool[i+size-1].u.hdr.prevSize = size;
18199   mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
18200   memsys3Link(i);
18201
18202   /* Try to expand the master using the newly freed chunk */
18203   if( mem3.iMaster ){
18204     while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
18205       size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
18206       mem3.iMaster -= size;
18207       mem3.szMaster += size;
18208       memsys3Unlink(mem3.iMaster);
18209       x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
18210       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
18211       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
18212     }
18213     x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
18214     while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
18215       memsys3Unlink(mem3.iMaster+mem3.szMaster);
18216       mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
18217       mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
18218       mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
18219     }
18220   }
18221 }
18222
18223 /*
18224 ** Return the size of an outstanding allocation, in bytes.  The
18225 ** size returned omits the 8-byte header overhead.  This only
18226 ** works for chunks that are currently checked out.
18227 */
18228 static int memsys3Size(void *p){
18229   Mem3Block *pBlock;
18230   if( p==0 ) return 0;
18231   pBlock = (Mem3Block*)p;
18232   assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
18233   return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
18234 }
18235
18236 /*
18237 ** Round up a request size to the next valid allocation size.
18238 */
18239 static int memsys3Roundup(int n){
18240   if( n<=12 ){
18241     return 12;
18242   }else{
18243     return ((n+11)&~7) - 4;
18244   }
18245 }
18246
18247 /*
18248 ** Allocate nBytes of memory.
18249 */
18250 static void *memsys3Malloc(int nBytes){
18251   sqlite3_int64 *p;
18252   assert( nBytes>0 );          /* malloc.c filters out 0 byte requests */
18253   memsys3Enter();
18254   p = memsys3MallocUnsafe(nBytes);
18255   memsys3Leave();
18256   return (void*)p; 
18257 }
18258
18259 /*
18260 ** Free memory.
18261 */
18262 static void memsys3Free(void *pPrior){
18263   assert( pPrior );
18264   memsys3Enter();
18265   memsys3FreeUnsafe(pPrior);
18266   memsys3Leave();
18267 }
18268
18269 /*
18270 ** Change the size of an existing memory allocation
18271 */
18272 static void *memsys3Realloc(void *pPrior, int nBytes){
18273   int nOld;
18274   void *p;
18275   if( pPrior==0 ){
18276     return sqlite3_malloc(nBytes);
18277   }
18278   if( nBytes<=0 ){
18279     sqlite3_free(pPrior);
18280     return 0;
18281   }
18282   nOld = memsys3Size(pPrior);
18283   if( nBytes<=nOld && nBytes>=nOld-128 ){
18284     return pPrior;
18285   }
18286   memsys3Enter();
18287   p = memsys3MallocUnsafe(nBytes);
18288   if( p ){
18289     if( nOld<nBytes ){
18290       memcpy(p, pPrior, nOld);
18291     }else{
18292       memcpy(p, pPrior, nBytes);
18293     }
18294     memsys3FreeUnsafe(pPrior);
18295   }
18296   memsys3Leave();
18297   return p;
18298 }
18299
18300 /*
18301 ** Initialize this module.
18302 */
18303 static int memsys3Init(void *NotUsed){
18304   UNUSED_PARAMETER(NotUsed);
18305   if( !sqlite3GlobalConfig.pHeap ){
18306     return SQLITE_ERROR;
18307   }
18308
18309   /* Store a pointer to the memory block in global structure mem3. */
18310   assert( sizeof(Mem3Block)==8 );
18311   mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
18312   mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
18313
18314   /* Initialize the master block. */
18315   mem3.szMaster = mem3.nPool;
18316   mem3.mnMaster = mem3.szMaster;
18317   mem3.iMaster = 1;
18318   mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
18319   mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
18320   mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
18321
18322   return SQLITE_OK;
18323 }
18324
18325 /*
18326 ** Deinitialize this module.
18327 */
18328 static void memsys3Shutdown(void *NotUsed){
18329   UNUSED_PARAMETER(NotUsed);
18330   mem3.mutex = 0;
18331   return;
18332 }
18333
18334
18335
18336 /*
18337 ** Open the file indicated and write a log of all unfreed memory 
18338 ** allocations into that log.
18339 */
18340 SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
18341 #ifdef SQLITE_DEBUG
18342   FILE *out;
18343   u32 i, j;
18344   u32 size;
18345   if( zFilename==0 || zFilename[0]==0 ){
18346     out = stdout;
18347   }else{
18348     out = fopen(zFilename, "w");
18349     if( out==0 ){
18350       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
18351                       zFilename);
18352       return;
18353     }
18354   }
18355   memsys3Enter();
18356   fprintf(out, "CHUNKS:\n");
18357   for(i=1; i<=mem3.nPool; i+=size/4){
18358     size = mem3.aPool[i-1].u.hdr.size4x;
18359     if( size/4<=1 ){
18360       fprintf(out, "%p size error\n", &mem3.aPool[i]);
18361       assert( 0 );
18362       break;
18363     }
18364     if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
18365       fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
18366       assert( 0 );
18367       break;
18368     }
18369     if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
18370       fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
18371       assert( 0 );
18372       break;
18373     }
18374     if( size&1 ){
18375       fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
18376     }else{
18377       fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
18378                   i==mem3.iMaster ? " **master**" : "");
18379     }
18380   }
18381   for(i=0; i<MX_SMALL-1; i++){
18382     if( mem3.aiSmall[i]==0 ) continue;
18383     fprintf(out, "small(%2d):", i);
18384     for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
18385       fprintf(out, " %p(%d)", &mem3.aPool[j],
18386               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
18387     }
18388     fprintf(out, "\n"); 
18389   }
18390   for(i=0; i<N_HASH; i++){
18391     if( mem3.aiHash[i]==0 ) continue;
18392     fprintf(out, "hash(%2d):", i);
18393     for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
18394       fprintf(out, " %p(%d)", &mem3.aPool[j],
18395               (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
18396     }
18397     fprintf(out, "\n"); 
18398   }
18399   fprintf(out, "master=%d\n", mem3.iMaster);
18400   fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
18401   fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
18402   sqlite3_mutex_leave(mem3.mutex);
18403   if( out==stdout ){
18404     fflush(stdout);
18405   }else{
18406     fclose(out);
18407   }
18408 #else
18409   UNUSED_PARAMETER(zFilename);
18410 #endif
18411 }
18412
18413 /*
18414 ** This routine is the only routine in this file with external 
18415 ** linkage.
18416 **
18417 ** Populate the low-level memory allocation function pointers in
18418 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
18419 ** arguments specify the block of memory to manage.
18420 **
18421 ** This routine is only called by sqlite3_config(), and therefore
18422 ** is not required to be threadsafe (it is not).
18423 */
18424 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
18425   static const sqlite3_mem_methods mempoolMethods = {
18426      memsys3Malloc,
18427      memsys3Free,
18428      memsys3Realloc,
18429      memsys3Size,
18430      memsys3Roundup,
18431      memsys3Init,
18432      memsys3Shutdown,
18433      0
18434   };
18435   return &mempoolMethods;
18436 }
18437
18438 #endif /* SQLITE_ENABLE_MEMSYS3 */
18439
18440 /************** End of mem3.c ************************************************/
18441 /************** Begin file mem5.c ********************************************/
18442 /*
18443 ** 2007 October 14
18444 **
18445 ** The author disclaims copyright to this source code.  In place of
18446 ** a legal notice, here is a blessing:
18447 **
18448 **    May you do good and not evil.
18449 **    May you find forgiveness for yourself and forgive others.
18450 **    May you share freely, never taking more than you give.
18451 **
18452 *************************************************************************
18453 ** This file contains the C functions that implement a memory
18454 ** allocation subsystem for use by SQLite. 
18455 **
18456 ** This version of the memory allocation subsystem omits all
18457 ** use of malloc(). The application gives SQLite a block of memory
18458 ** before calling sqlite3_initialize() from which allocations
18459 ** are made and returned by the xMalloc() and xRealloc() 
18460 ** implementations. Once sqlite3_initialize() has been called,
18461 ** the amount of memory available to SQLite is fixed and cannot
18462 ** be changed.
18463 **
18464 ** This version of the memory allocation subsystem is included
18465 ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
18466 **
18467 ** This memory allocator uses the following algorithm:
18468 **
18469 **   1.  All memory allocations sizes are rounded up to a power of 2.
18470 **
18471 **   2.  If two adjacent free blocks are the halves of a larger block,
18472 **       then the two blocks are coalesced into the single larger block.
18473 **
18474 **   3.  New memory is allocated from the first available free block.
18475 **
18476 ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
18477 ** Concerning Dynamic Storage Allocation". Journal of the Association for
18478 ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
18479 ** 
18480 ** Let n be the size of the largest allocation divided by the minimum
18481 ** allocation size (after rounding all sizes up to a power of 2.)  Let M
18482 ** be the maximum amount of memory ever outstanding at one time.  Let
18483 ** N be the total amount of memory available for allocation.  Robson
18484 ** proved that this memory allocator will never breakdown due to 
18485 ** fragmentation as long as the following constraint holds:
18486 **
18487 **      N >=  M*(1 + log2(n)/2) - n + 1
18488 **
18489 ** The sqlite3_status() logic tracks the maximum values of n and M so
18490 ** that an application can, at any time, verify this constraint.
18491 */
18492
18493 /*
18494 ** This version of the memory allocator is used only when 
18495 ** SQLITE_ENABLE_MEMSYS5 is defined.
18496 */
18497 #ifdef SQLITE_ENABLE_MEMSYS5
18498
18499 /*
18500 ** A minimum allocation is an instance of the following structure.
18501 ** Larger allocations are an array of these structures where the
18502 ** size of the array is a power of 2.
18503 **
18504 ** The size of this object must be a power of two.  That fact is
18505 ** verified in memsys5Init().
18506 */
18507 typedef struct Mem5Link Mem5Link;
18508 struct Mem5Link {
18509   int next;       /* Index of next free chunk */
18510   int prev;       /* Index of previous free chunk */
18511 };
18512
18513 /*
18514 ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
18515 ** mem5.szAtom is always at least 8 and 32-bit integers are used,
18516 ** it is not actually possible to reach this limit.
18517 */
18518 #define LOGMAX 30
18519
18520 /*
18521 ** Masks used for mem5.aCtrl[] elements.
18522 */
18523 #define CTRL_LOGSIZE  0x1f    /* Log2 Size of this block */
18524 #define CTRL_FREE     0x20    /* True if not checked out */
18525
18526 /*
18527 ** All of the static variables used by this module are collected
18528 ** into a single structure named "mem5".  This is to keep the
18529 ** static variables organized and to reduce namespace pollution
18530 ** when this module is combined with other in the amalgamation.
18531 */
18532 static SQLITE_WSD struct Mem5Global {
18533   /*
18534   ** Memory available for allocation
18535   */
18536   int szAtom;      /* Smallest possible allocation in bytes */
18537   int nBlock;      /* Number of szAtom sized blocks in zPool */
18538   u8 *zPool;       /* Memory available to be allocated */
18539   
18540   /*
18541   ** Mutex to control access to the memory allocation subsystem.
18542   */
18543   sqlite3_mutex *mutex;
18544
18545   /*
18546   ** Performance statistics
18547   */
18548   u64 nAlloc;         /* Total number of calls to malloc */
18549   u64 totalAlloc;     /* Total of all malloc calls - includes internal frag */
18550   u64 totalExcess;    /* Total internal fragmentation */
18551   u32 currentOut;     /* Current checkout, including internal fragmentation */
18552   u32 currentCount;   /* Current number of distinct checkouts */
18553   u32 maxOut;         /* Maximum instantaneous currentOut */
18554   u32 maxCount;       /* Maximum instantaneous currentCount */
18555   u32 maxRequest;     /* Largest allocation (exclusive of internal frag) */
18556   
18557   /*
18558   ** Lists of free blocks.  aiFreelist[0] is a list of free blocks of
18559   ** size mem5.szAtom.  aiFreelist[1] holds blocks of size szAtom*2.
18560   ** and so forth.
18561   */
18562   int aiFreelist[LOGMAX+1];
18563
18564   /*
18565   ** Space for tracking which blocks are checked out and the size
18566   ** of each block.  One byte per block.
18567   */
18568   u8 *aCtrl;
18569
18570 } mem5;
18571
18572 /*
18573 ** Access the static variable through a macro for SQLITE_OMIT_WSD.
18574 */
18575 #define mem5 GLOBAL(struct Mem5Global, mem5)
18576
18577 /*
18578 ** Assuming mem5.zPool is divided up into an array of Mem5Link
18579 ** structures, return a pointer to the idx-th such link.
18580 */
18581 #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
18582
18583 /*
18584 ** Unlink the chunk at mem5.aPool[i] from list it is currently
18585 ** on.  It should be found on mem5.aiFreelist[iLogsize].
18586 */
18587 static void memsys5Unlink(int i, int iLogsize){
18588   int next, prev;
18589   assert( i>=0 && i<mem5.nBlock );
18590   assert( iLogsize>=0 && iLogsize<=LOGMAX );
18591   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
18592
18593   next = MEM5LINK(i)->next;
18594   prev = MEM5LINK(i)->prev;
18595   if( prev<0 ){
18596     mem5.aiFreelist[iLogsize] = next;
18597   }else{
18598     MEM5LINK(prev)->next = next;
18599   }
18600   if( next>=0 ){
18601     MEM5LINK(next)->prev = prev;
18602   }
18603 }
18604
18605 /*
18606 ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
18607 ** free list.
18608 */
18609 static void memsys5Link(int i, int iLogsize){
18610   int x;
18611   assert( sqlite3_mutex_held(mem5.mutex) );
18612   assert( i>=0 && i<mem5.nBlock );
18613   assert( iLogsize>=0 && iLogsize<=LOGMAX );
18614   assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
18615
18616   x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
18617   MEM5LINK(i)->prev = -1;
18618   if( x>=0 ){
18619     assert( x<mem5.nBlock );
18620     MEM5LINK(x)->prev = i;
18621   }
18622   mem5.aiFreelist[iLogsize] = i;
18623 }
18624
18625 /*
18626 ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
18627 ** will already be held (obtained by code in malloc.c) if
18628 ** sqlite3GlobalConfig.bMemStat is true.
18629 */
18630 static void memsys5Enter(void){
18631   sqlite3_mutex_enter(mem5.mutex);
18632 }
18633 static void memsys5Leave(void){
18634   sqlite3_mutex_leave(mem5.mutex);
18635 }
18636
18637 /*
18638 ** Return the size of an outstanding allocation, in bytes.  The
18639 ** size returned omits the 8-byte header overhead.  This only
18640 ** works for chunks that are currently checked out.
18641 */
18642 static int memsys5Size(void *p){
18643   int iSize = 0;
18644   if( p ){
18645     int i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
18646     assert( i>=0 && i<mem5.nBlock );
18647     iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
18648   }
18649   return iSize;
18650 }
18651
18652 /*
18653 ** Return a block of memory of at least nBytes in size.
18654 ** Return NULL if unable.  Return NULL if nBytes==0.
18655 **
18656 ** The caller guarantees that nByte is positive.
18657 **
18658 ** The caller has obtained a mutex prior to invoking this
18659 ** routine so there is never any chance that two or more
18660 ** threads can be in this routine at the same time.
18661 */
18662 static void *memsys5MallocUnsafe(int nByte){
18663   int i;           /* Index of a mem5.aPool[] slot */
18664   int iBin;        /* Index into mem5.aiFreelist[] */
18665   int iFullSz;     /* Size of allocation rounded up to power of 2 */
18666   int iLogsize;    /* Log2 of iFullSz/POW2_MIN */
18667
18668   /* nByte must be a positive */
18669   assert( nByte>0 );
18670
18671   /* Keep track of the maximum allocation request.  Even unfulfilled
18672   ** requests are counted */
18673   if( (u32)nByte>mem5.maxRequest ){
18674     mem5.maxRequest = nByte;
18675   }
18676
18677   /* Abort if the requested allocation size is larger than the largest
18678   ** power of two that we can represent using 32-bit signed integers.
18679   */
18680   if( nByte > 0x40000000 ){
18681     return 0;
18682   }
18683
18684   /* Round nByte up to the next valid power of two */
18685   for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
18686
18687   /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
18688   ** block.  If not, then split a block of the next larger power of
18689   ** two in order to create a new free block of size iLogsize.
18690   */
18691   for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
18692   if( iBin>LOGMAX ){
18693     testcase( sqlite3GlobalConfig.xLog!=0 );
18694     sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
18695     return 0;
18696   }
18697   i = mem5.aiFreelist[iBin];
18698   memsys5Unlink(i, iBin);
18699   while( iBin>iLogsize ){
18700     int newSize;
18701
18702     iBin--;
18703     newSize = 1 << iBin;
18704     mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
18705     memsys5Link(i+newSize, iBin);
18706   }
18707   mem5.aCtrl[i] = iLogsize;
18708
18709   /* Update allocator performance statistics. */
18710   mem5.nAlloc++;
18711   mem5.totalAlloc += iFullSz;
18712   mem5.totalExcess += iFullSz - nByte;
18713   mem5.currentCount++;
18714   mem5.currentOut += iFullSz;
18715   if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
18716   if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
18717
18718 #ifdef SQLITE_DEBUG
18719   /* Make sure the allocated memory does not assume that it is set to zero
18720   ** or retains a value from a previous allocation */
18721   memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
18722 #endif
18723
18724   /* Return a pointer to the allocated memory. */
18725   return (void*)&mem5.zPool[i*mem5.szAtom];
18726 }
18727
18728 /*
18729 ** Free an outstanding memory allocation.
18730 */
18731 static void memsys5FreeUnsafe(void *pOld){
18732   u32 size, iLogsize;
18733   int iBlock;
18734
18735   /* Set iBlock to the index of the block pointed to by pOld in 
18736   ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
18737   */
18738   iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
18739
18740   /* Check that the pointer pOld points to a valid, non-free block. */
18741   assert( iBlock>=0 && iBlock<mem5.nBlock );
18742   assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
18743   assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
18744
18745   iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
18746   size = 1<<iLogsize;
18747   assert( iBlock+size-1<(u32)mem5.nBlock );
18748
18749   mem5.aCtrl[iBlock] |= CTRL_FREE;
18750   mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
18751   assert( mem5.currentCount>0 );
18752   assert( mem5.currentOut>=(size*mem5.szAtom) );
18753   mem5.currentCount--;
18754   mem5.currentOut -= size*mem5.szAtom;
18755   assert( mem5.currentOut>0 || mem5.currentCount==0 );
18756   assert( mem5.currentCount>0 || mem5.currentOut==0 );
18757
18758   mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
18759   while( ALWAYS(iLogsize<LOGMAX) ){
18760     int iBuddy;
18761     if( (iBlock>>iLogsize) & 1 ){
18762       iBuddy = iBlock - size;
18763     }else{
18764       iBuddy = iBlock + size;
18765     }
18766     assert( iBuddy>=0 );
18767     if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
18768     if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
18769     memsys5Unlink(iBuddy, iLogsize);
18770     iLogsize++;
18771     if( iBuddy<iBlock ){
18772       mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
18773       mem5.aCtrl[iBlock] = 0;
18774       iBlock = iBuddy;
18775     }else{
18776       mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
18777       mem5.aCtrl[iBuddy] = 0;
18778     }
18779     size *= 2;
18780   }
18781
18782 #ifdef SQLITE_DEBUG
18783   /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
18784   ** not used after being freed */
18785   memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
18786 #endif
18787
18788   memsys5Link(iBlock, iLogsize);
18789 }
18790
18791 /*
18792 ** Allocate nBytes of memory.
18793 */
18794 static void *memsys5Malloc(int nBytes){
18795   sqlite3_int64 *p = 0;
18796   if( nBytes>0 ){
18797     memsys5Enter();
18798     p = memsys5MallocUnsafe(nBytes);
18799     memsys5Leave();
18800   }
18801   return (void*)p; 
18802 }
18803
18804 /*
18805 ** Free memory.
18806 **
18807 ** The outer layer memory allocator prevents this routine from
18808 ** being called with pPrior==0.
18809 */
18810 static void memsys5Free(void *pPrior){
18811   assert( pPrior!=0 );
18812   memsys5Enter();
18813   memsys5FreeUnsafe(pPrior);
18814   memsys5Leave();  
18815 }
18816
18817 /*
18818 ** Change the size of an existing memory allocation.
18819 **
18820 ** The outer layer memory allocator prevents this routine from
18821 ** being called with pPrior==0.  
18822 **
18823 ** nBytes is always a value obtained from a prior call to
18824 ** memsys5Round().  Hence nBytes is always a non-negative power
18825 ** of two.  If nBytes==0 that means that an oversize allocation
18826 ** (an allocation larger than 0x40000000) was requested and this
18827 ** routine should return 0 without freeing pPrior.
18828 */
18829 static void *memsys5Realloc(void *pPrior, int nBytes){
18830   int nOld;
18831   void *p;
18832   assert( pPrior!=0 );
18833   assert( (nBytes&(nBytes-1))==0 );  /* EV: R-46199-30249 */
18834   assert( nBytes>=0 );
18835   if( nBytes==0 ){
18836     return 0;
18837   }
18838   nOld = memsys5Size(pPrior);
18839   if( nBytes<=nOld ){
18840     return pPrior;
18841   }
18842   memsys5Enter();
18843   p = memsys5MallocUnsafe(nBytes);
18844   if( p ){
18845     memcpy(p, pPrior, nOld);
18846     memsys5FreeUnsafe(pPrior);
18847   }
18848   memsys5Leave();
18849   return p;
18850 }
18851
18852 /*
18853 ** Round up a request size to the next valid allocation size.  If
18854 ** the allocation is too large to be handled by this allocation system,
18855 ** return 0.
18856 **
18857 ** All allocations must be a power of two and must be expressed by a
18858 ** 32-bit signed integer.  Hence the largest allocation is 0x40000000
18859 ** or 1073741824 bytes.
18860 */
18861 static int memsys5Roundup(int n){
18862   int iFullSz;
18863   if( n > 0x40000000 ) return 0;
18864   for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
18865   return iFullSz;
18866 }
18867
18868 /*
18869 ** Return the ceiling of the logarithm base 2 of iValue.
18870 **
18871 ** Examples:   memsys5Log(1) -> 0
18872 **             memsys5Log(2) -> 1
18873 **             memsys5Log(4) -> 2
18874 **             memsys5Log(5) -> 3
18875 **             memsys5Log(8) -> 3
18876 **             memsys5Log(9) -> 4
18877 */
18878 static int memsys5Log(int iValue){
18879   int iLog;
18880   for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
18881   return iLog;
18882 }
18883
18884 /*
18885 ** Initialize the memory allocator.
18886 **
18887 ** This routine is not threadsafe.  The caller must be holding a mutex
18888 ** to prevent multiple threads from entering at the same time.
18889 */
18890 static int memsys5Init(void *NotUsed){
18891   int ii;            /* Loop counter */
18892   int nByte;         /* Number of bytes of memory available to this allocator */
18893   u8 *zByte;         /* Memory usable by this allocator */
18894   int nMinLog;       /* Log base 2 of minimum allocation size in bytes */
18895   int iOffset;       /* An offset into mem5.aCtrl[] */
18896
18897   UNUSED_PARAMETER(NotUsed);
18898
18899   /* For the purposes of this routine, disable the mutex */
18900   mem5.mutex = 0;
18901
18902   /* The size of a Mem5Link object must be a power of two.  Verify that
18903   ** this is case.
18904   */
18905   assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
18906
18907   nByte = sqlite3GlobalConfig.nHeap;
18908   zByte = (u8*)sqlite3GlobalConfig.pHeap;
18909   assert( zByte!=0 );  /* sqlite3_config() does not allow otherwise */
18910
18911   /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
18912   nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
18913   mem5.szAtom = (1<<nMinLog);
18914   while( (int)sizeof(Mem5Link)>mem5.szAtom ){
18915     mem5.szAtom = mem5.szAtom << 1;
18916   }
18917
18918   mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
18919   mem5.zPool = zByte;
18920   mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
18921
18922   for(ii=0; ii<=LOGMAX; ii++){
18923     mem5.aiFreelist[ii] = -1;
18924   }
18925
18926   iOffset = 0;
18927   for(ii=LOGMAX; ii>=0; ii--){
18928     int nAlloc = (1<<ii);
18929     if( (iOffset+nAlloc)<=mem5.nBlock ){
18930       mem5.aCtrl[iOffset] = ii | CTRL_FREE;
18931       memsys5Link(iOffset, ii);
18932       iOffset += nAlloc;
18933     }
18934     assert((iOffset+nAlloc)>mem5.nBlock);
18935   }
18936
18937   /* If a mutex is required for normal operation, allocate one */
18938   if( sqlite3GlobalConfig.bMemstat==0 ){
18939     mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
18940   }
18941
18942   return SQLITE_OK;
18943 }
18944
18945 /*
18946 ** Deinitialize this module.
18947 */
18948 static void memsys5Shutdown(void *NotUsed){
18949   UNUSED_PARAMETER(NotUsed);
18950   mem5.mutex = 0;
18951   return;
18952 }
18953
18954 #ifdef SQLITE_TEST
18955 /*
18956 ** Open the file indicated and write a log of all unfreed memory 
18957 ** allocations into that log.
18958 */
18959 SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
18960   FILE *out;
18961   int i, j, n;
18962   int nMinLog;
18963
18964   if( zFilename==0 || zFilename[0]==0 ){
18965     out = stdout;
18966   }else{
18967     out = fopen(zFilename, "w");
18968     if( out==0 ){
18969       fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
18970                       zFilename);
18971       return;
18972     }
18973   }
18974   memsys5Enter();
18975   nMinLog = memsys5Log(mem5.szAtom);
18976   for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
18977     for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
18978     fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
18979   }
18980   fprintf(out, "mem5.nAlloc       = %llu\n", mem5.nAlloc);
18981   fprintf(out, "mem5.totalAlloc   = %llu\n", mem5.totalAlloc);
18982   fprintf(out, "mem5.totalExcess  = %llu\n", mem5.totalExcess);
18983   fprintf(out, "mem5.currentOut   = %u\n", mem5.currentOut);
18984   fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
18985   fprintf(out, "mem5.maxOut       = %u\n", mem5.maxOut);
18986   fprintf(out, "mem5.maxCount     = %u\n", mem5.maxCount);
18987   fprintf(out, "mem5.maxRequest   = %u\n", mem5.maxRequest);
18988   memsys5Leave();
18989   if( out==stdout ){
18990     fflush(stdout);
18991   }else{
18992     fclose(out);
18993   }
18994 }
18995 #endif
18996
18997 /*
18998 ** This routine is the only routine in this file with external 
18999 ** linkage. It returns a pointer to a static sqlite3_mem_methods
19000 ** struct populated with the memsys5 methods.
19001 */
19002 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
19003   static const sqlite3_mem_methods memsys5Methods = {
19004      memsys5Malloc,
19005      memsys5Free,
19006      memsys5Realloc,
19007      memsys5Size,
19008      memsys5Roundup,
19009      memsys5Init,
19010      memsys5Shutdown,
19011      0
19012   };
19013   return &memsys5Methods;
19014 }
19015
19016 #endif /* SQLITE_ENABLE_MEMSYS5 */
19017
19018 /************** End of mem5.c ************************************************/
19019 /************** Begin file mutex.c *******************************************/
19020 /*
19021 ** 2007 August 14
19022 **
19023 ** The author disclaims copyright to this source code.  In place of
19024 ** a legal notice, here is a blessing:
19025 **
19026 **    May you do good and not evil.
19027 **    May you find forgiveness for yourself and forgive others.
19028 **    May you share freely, never taking more than you give.
19029 **
19030 *************************************************************************
19031 ** This file contains the C functions that implement mutexes.
19032 **
19033 ** This file contains code that is common across all mutex implementations.
19034 */
19035
19036 #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
19037 /*
19038 ** For debugging purposes, record when the mutex subsystem is initialized
19039 ** and uninitialized so that we can assert() if there is an attempt to
19040 ** allocate a mutex while the system is uninitialized.
19041 */
19042 static SQLITE_WSD int mutexIsInit = 0;
19043 #endif /* SQLITE_DEBUG */
19044
19045
19046 #ifndef SQLITE_MUTEX_OMIT
19047 /*
19048 ** Initialize the mutex system.
19049 */
19050 SQLITE_PRIVATE int sqlite3MutexInit(void){ 
19051   int rc = SQLITE_OK;
19052   if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
19053     /* If the xMutexAlloc method has not been set, then the user did not
19054     ** install a mutex implementation via sqlite3_config() prior to 
19055     ** sqlite3_initialize() being called. This block copies pointers to
19056     ** the default implementation into the sqlite3GlobalConfig structure.
19057     */
19058     sqlite3_mutex_methods const *pFrom;
19059     sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
19060
19061     if( sqlite3GlobalConfig.bCoreMutex ){
19062       pFrom = sqlite3DefaultMutex();
19063     }else{
19064       pFrom = sqlite3NoopMutex();
19065     }
19066     memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
19067     memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
19068            sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
19069     pTo->xMutexAlloc = pFrom->xMutexAlloc;
19070   }
19071   rc = sqlite3GlobalConfig.mutex.xMutexInit();
19072
19073 #ifdef SQLITE_DEBUG
19074   GLOBAL(int, mutexIsInit) = 1;
19075 #endif
19076
19077   return rc;
19078 }
19079
19080 /*
19081 ** Shutdown the mutex system. This call frees resources allocated by
19082 ** sqlite3MutexInit().
19083 */
19084 SQLITE_PRIVATE int sqlite3MutexEnd(void){
19085   int rc = SQLITE_OK;
19086   if( sqlite3GlobalConfig.mutex.xMutexEnd ){
19087     rc = sqlite3GlobalConfig.mutex.xMutexEnd();
19088   }
19089
19090 #ifdef SQLITE_DEBUG
19091   GLOBAL(int, mutexIsInit) = 0;
19092 #endif
19093
19094   return rc;
19095 }
19096
19097 /*
19098 ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
19099 */
19100 SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_mutex_alloc(int id){
19101 #ifndef SQLITE_OMIT_AUTOINIT
19102   if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
19103   if( id>SQLITE_MUTEX_RECURSIVE && sqlite3MutexInit() ) return 0;
19104 #endif
19105   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
19106 }
19107
19108 SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
19109   if( !sqlite3GlobalConfig.bCoreMutex ){
19110     return 0;
19111   }
19112   assert( GLOBAL(int, mutexIsInit) );
19113   return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
19114 }
19115
19116 /*
19117 ** Free a dynamic mutex.
19118 */
19119 SQLITE_API void SQLITE_STDCALL sqlite3_mutex_free(sqlite3_mutex *p){
19120   if( p ){
19121     sqlite3GlobalConfig.mutex.xMutexFree(p);
19122   }
19123 }
19124
19125 /*
19126 ** Obtain the mutex p. If some other thread already has the mutex, block
19127 ** until it can be obtained.
19128 */
19129 SQLITE_API void SQLITE_STDCALL sqlite3_mutex_enter(sqlite3_mutex *p){
19130   if( p ){
19131     sqlite3GlobalConfig.mutex.xMutexEnter(p);
19132   }
19133 }
19134
19135 /*
19136 ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
19137 ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
19138 */
19139 SQLITE_API int SQLITE_STDCALL sqlite3_mutex_try(sqlite3_mutex *p){
19140   int rc = SQLITE_OK;
19141   if( p ){
19142     return sqlite3GlobalConfig.mutex.xMutexTry(p);
19143   }
19144   return rc;
19145 }
19146
19147 /*
19148 ** The sqlite3_mutex_leave() routine exits a mutex that was previously
19149 ** entered by the same thread.  The behavior is undefined if the mutex 
19150 ** is not currently entered. If a NULL pointer is passed as an argument
19151 ** this function is a no-op.
19152 */
19153 SQLITE_API void SQLITE_STDCALL sqlite3_mutex_leave(sqlite3_mutex *p){
19154   if( p ){
19155     sqlite3GlobalConfig.mutex.xMutexLeave(p);
19156   }
19157 }
19158
19159 #ifndef NDEBUG
19160 /*
19161 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
19162 ** intended for use inside assert() statements.
19163 */
19164 SQLITE_API int SQLITE_STDCALL sqlite3_mutex_held(sqlite3_mutex *p){
19165   return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
19166 }
19167 SQLITE_API int SQLITE_STDCALL sqlite3_mutex_notheld(sqlite3_mutex *p){
19168   return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
19169 }
19170 #endif
19171
19172 #endif /* !defined(SQLITE_MUTEX_OMIT) */
19173
19174 /************** End of mutex.c ***********************************************/
19175 /************** Begin file mutex_noop.c **************************************/
19176 /*
19177 ** 2008 October 07
19178 **
19179 ** The author disclaims copyright to this source code.  In place of
19180 ** a legal notice, here is a blessing:
19181 **
19182 **    May you do good and not evil.
19183 **    May you find forgiveness for yourself and forgive others.
19184 **    May you share freely, never taking more than you give.
19185 **
19186 *************************************************************************
19187 ** This file contains the C functions that implement mutexes.
19188 **
19189 ** This implementation in this file does not provide any mutual
19190 ** exclusion and is thus suitable for use only in applications
19191 ** that use SQLite in a single thread.  The routines defined
19192 ** here are place-holders.  Applications can substitute working
19193 ** mutex routines at start-time using the
19194 **
19195 **     sqlite3_config(SQLITE_CONFIG_MUTEX,...)
19196 **
19197 ** interface.
19198 **
19199 ** If compiled with SQLITE_DEBUG, then additional logic is inserted
19200 ** that does error checking on mutexes to make sure they are being
19201 ** called correctly.
19202 */
19203
19204 #ifndef SQLITE_MUTEX_OMIT
19205
19206 #ifndef SQLITE_DEBUG
19207 /*
19208 ** Stub routines for all mutex methods.
19209 **
19210 ** This routines provide no mutual exclusion or error checking.
19211 */
19212 static int noopMutexInit(void){ return SQLITE_OK; }
19213 static int noopMutexEnd(void){ return SQLITE_OK; }
19214 static sqlite3_mutex *noopMutexAlloc(int id){ 
19215   UNUSED_PARAMETER(id);
19216   return (sqlite3_mutex*)8; 
19217 }
19218 static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
19219 static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
19220 static int noopMutexTry(sqlite3_mutex *p){
19221   UNUSED_PARAMETER(p);
19222   return SQLITE_OK;
19223 }
19224 static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
19225
19226 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
19227   static const sqlite3_mutex_methods sMutex = {
19228     noopMutexInit,
19229     noopMutexEnd,
19230     noopMutexAlloc,
19231     noopMutexFree,
19232     noopMutexEnter,
19233     noopMutexTry,
19234     noopMutexLeave,
19235
19236     0,
19237     0,
19238   };
19239
19240   return &sMutex;
19241 }
19242 #endif /* !SQLITE_DEBUG */
19243
19244 #ifdef SQLITE_DEBUG
19245 /*
19246 ** In this implementation, error checking is provided for testing
19247 ** and debugging purposes.  The mutexes still do not provide any
19248 ** mutual exclusion.
19249 */
19250
19251 /*
19252 ** The mutex object
19253 */
19254 typedef struct sqlite3_debug_mutex {
19255   int id;     /* The mutex type */
19256   int cnt;    /* Number of entries without a matching leave */
19257 } sqlite3_debug_mutex;
19258
19259 /*
19260 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
19261 ** intended for use inside assert() statements.
19262 */
19263 static int debugMutexHeld(sqlite3_mutex *pX){
19264   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
19265   return p==0 || p->cnt>0;
19266 }
19267 static int debugMutexNotheld(sqlite3_mutex *pX){
19268   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
19269   return p==0 || p->cnt==0;
19270 }
19271
19272 /*
19273 ** Initialize and deinitialize the mutex subsystem.
19274 */
19275 static int debugMutexInit(void){ return SQLITE_OK; }
19276 static int debugMutexEnd(void){ return SQLITE_OK; }
19277
19278 /*
19279 ** The sqlite3_mutex_alloc() routine allocates a new
19280 ** mutex and returns a pointer to it.  If it returns NULL
19281 ** that means that a mutex could not be allocated. 
19282 */
19283 static sqlite3_mutex *debugMutexAlloc(int id){
19284   static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_APP3 - 1];
19285   sqlite3_debug_mutex *pNew = 0;
19286   switch( id ){
19287     case SQLITE_MUTEX_FAST:
19288     case SQLITE_MUTEX_RECURSIVE: {
19289       pNew = sqlite3Malloc(sizeof(*pNew));
19290       if( pNew ){
19291         pNew->id = id;
19292         pNew->cnt = 0;
19293       }
19294       break;
19295     }
19296     default: {
19297 #ifdef SQLITE_ENABLE_API_ARMOR
19298       if( id-2<0 || id-2>=ArraySize(aStatic) ){
19299         (void)SQLITE_MISUSE_BKPT;
19300         return 0;
19301       }
19302 #endif
19303       pNew = &aStatic[id-2];
19304       pNew->id = id;
19305       break;
19306     }
19307   }
19308   return (sqlite3_mutex*)pNew;
19309 }
19310
19311 /*
19312 ** This routine deallocates a previously allocated mutex.
19313 */
19314 static void debugMutexFree(sqlite3_mutex *pX){
19315   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
19316   assert( p->cnt==0 );
19317   if( p->id==SQLITE_MUTEX_RECURSIVE || p->id==SQLITE_MUTEX_FAST ){
19318     sqlite3_free(p);
19319   }else{
19320 #ifdef SQLITE_ENABLE_API_ARMOR
19321     (void)SQLITE_MISUSE_BKPT;
19322 #endif
19323   }
19324 }
19325
19326 /*
19327 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
19328 ** to enter a mutex.  If another thread is already within the mutex,
19329 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
19330 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
19331 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
19332 ** be entered multiple times by the same thread.  In such cases the,
19333 ** mutex must be exited an equal number of times before another thread
19334 ** can enter.  If the same thread tries to enter any other kind of mutex
19335 ** more than once, the behavior is undefined.
19336 */
19337 static void debugMutexEnter(sqlite3_mutex *pX){
19338   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
19339   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
19340   p->cnt++;
19341 }
19342 static int debugMutexTry(sqlite3_mutex *pX){
19343   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
19344   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
19345   p->cnt++;
19346   return SQLITE_OK;
19347 }
19348
19349 /*
19350 ** The sqlite3_mutex_leave() routine exits a mutex that was
19351 ** previously entered by the same thread.  The behavior
19352 ** is undefined if the mutex is not currently entered or
19353 ** is not currently allocated.  SQLite will never do either.
19354 */
19355 static void debugMutexLeave(sqlite3_mutex *pX){
19356   sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
19357   assert( debugMutexHeld(pX) );
19358   p->cnt--;
19359   assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
19360 }
19361
19362 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
19363   static const sqlite3_mutex_methods sMutex = {
19364     debugMutexInit,
19365     debugMutexEnd,
19366     debugMutexAlloc,
19367     debugMutexFree,
19368     debugMutexEnter,
19369     debugMutexTry,
19370     debugMutexLeave,
19371
19372     debugMutexHeld,
19373     debugMutexNotheld
19374   };
19375
19376   return &sMutex;
19377 }
19378 #endif /* SQLITE_DEBUG */
19379
19380 /*
19381 ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
19382 ** is used regardless of the run-time threadsafety setting.
19383 */
19384 #ifdef SQLITE_MUTEX_NOOP
19385 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
19386   return sqlite3NoopMutex();
19387 }
19388 #endif /* defined(SQLITE_MUTEX_NOOP) */
19389 #endif /* !defined(SQLITE_MUTEX_OMIT) */
19390
19391 /************** End of mutex_noop.c ******************************************/
19392 /************** Begin file mutex_unix.c **************************************/
19393 /*
19394 ** 2007 August 28
19395 **
19396 ** The author disclaims copyright to this source code.  In place of
19397 ** a legal notice, here is a blessing:
19398 **
19399 **    May you do good and not evil.
19400 **    May you find forgiveness for yourself and forgive others.
19401 **    May you share freely, never taking more than you give.
19402 **
19403 *************************************************************************
19404 ** This file contains the C functions that implement mutexes for pthreads
19405 */
19406
19407 /*
19408 ** The code in this file is only used if we are compiling threadsafe
19409 ** under unix with pthreads.
19410 **
19411 ** Note that this implementation requires a version of pthreads that
19412 ** supports recursive mutexes.
19413 */
19414 #ifdef SQLITE_MUTEX_PTHREADS
19415
19416 #include <pthread.h>
19417
19418 /*
19419 ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
19420 ** are necessary under two condidtions:  (1) Debug builds and (2) using
19421 ** home-grown mutexes.  Encapsulate these conditions into a single #define.
19422 */
19423 #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
19424 # define SQLITE_MUTEX_NREF 1
19425 #else
19426 # define SQLITE_MUTEX_NREF 0
19427 #endif
19428
19429 /*
19430 ** Each recursive mutex is an instance of the following structure.
19431 */
19432 struct sqlite3_mutex {
19433   pthread_mutex_t mutex;     /* Mutex controlling the lock */
19434 #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
19435   int id;                    /* Mutex type */
19436 #endif
19437 #if SQLITE_MUTEX_NREF
19438   volatile int nRef;         /* Number of entrances */
19439   volatile pthread_t owner;  /* Thread that is within this mutex */
19440   int trace;                 /* True to trace changes */
19441 #endif
19442 };
19443 #if SQLITE_MUTEX_NREF
19444 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
19445 #else
19446 #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
19447 #endif
19448
19449 /*
19450 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
19451 ** intended for use only inside assert() statements.  On some platforms,
19452 ** there might be race conditions that can cause these routines to
19453 ** deliver incorrect results.  In particular, if pthread_equal() is
19454 ** not an atomic operation, then these routines might delivery
19455 ** incorrect results.  On most platforms, pthread_equal() is a 
19456 ** comparison of two integers and is therefore atomic.  But we are
19457 ** told that HPUX is not such a platform.  If so, then these routines
19458 ** will not always work correctly on HPUX.
19459 **
19460 ** On those platforms where pthread_equal() is not atomic, SQLite
19461 ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
19462 ** make sure no assert() statements are evaluated and hence these
19463 ** routines are never called.
19464 */
19465 #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
19466 static int pthreadMutexHeld(sqlite3_mutex *p){
19467   return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
19468 }
19469 static int pthreadMutexNotheld(sqlite3_mutex *p){
19470   return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
19471 }
19472 #endif
19473
19474 /*
19475 ** Initialize and deinitialize the mutex subsystem.
19476 */
19477 static int pthreadMutexInit(void){ return SQLITE_OK; }
19478 static int pthreadMutexEnd(void){ return SQLITE_OK; }
19479
19480 /*
19481 ** The sqlite3_mutex_alloc() routine allocates a new
19482 ** mutex and returns a pointer to it.  If it returns NULL
19483 ** that means that a mutex could not be allocated.  SQLite
19484 ** will unwind its stack and return an error.  The argument
19485 ** to sqlite3_mutex_alloc() is one of these integer constants:
19486 **
19487 ** <ul>
19488 ** <li>  SQLITE_MUTEX_FAST
19489 ** <li>  SQLITE_MUTEX_RECURSIVE
19490 ** <li>  SQLITE_MUTEX_STATIC_MASTER
19491 ** <li>  SQLITE_MUTEX_STATIC_MEM
19492 ** <li>  SQLITE_MUTEX_STATIC_OPEN
19493 ** <li>  SQLITE_MUTEX_STATIC_PRNG
19494 ** <li>  SQLITE_MUTEX_STATIC_LRU
19495 ** <li>  SQLITE_MUTEX_STATIC_PMEM
19496 ** <li>  SQLITE_MUTEX_STATIC_APP1
19497 ** <li>  SQLITE_MUTEX_STATIC_APP2
19498 ** <li>  SQLITE_MUTEX_STATIC_APP3
19499 ** </ul>
19500 **
19501 ** The first two constants cause sqlite3_mutex_alloc() to create
19502 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
19503 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
19504 ** The mutex implementation does not need to make a distinction
19505 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
19506 ** not want to.  But SQLite will only request a recursive mutex in
19507 ** cases where it really needs one.  If a faster non-recursive mutex
19508 ** implementation is available on the host platform, the mutex subsystem
19509 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
19510 **
19511 ** The other allowed parameters to sqlite3_mutex_alloc() each return
19512 ** a pointer to a static preexisting mutex.  Six static mutexes are
19513 ** used by the current version of SQLite.  Future versions of SQLite
19514 ** may add additional static mutexes.  Static mutexes are for internal
19515 ** use by SQLite only.  Applications that use SQLite mutexes should
19516 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
19517 ** SQLITE_MUTEX_RECURSIVE.
19518 **
19519 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
19520 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
19521 ** returns a different mutex on every call.  But for the static 
19522 ** mutex types, the same mutex is returned on every call that has
19523 ** the same type number.
19524 */
19525 static sqlite3_mutex *pthreadMutexAlloc(int iType){
19526   static sqlite3_mutex staticMutexes[] = {
19527     SQLITE3_MUTEX_INITIALIZER,
19528     SQLITE3_MUTEX_INITIALIZER,
19529     SQLITE3_MUTEX_INITIALIZER,
19530     SQLITE3_MUTEX_INITIALIZER,
19531     SQLITE3_MUTEX_INITIALIZER,
19532     SQLITE3_MUTEX_INITIALIZER,
19533     SQLITE3_MUTEX_INITIALIZER,
19534     SQLITE3_MUTEX_INITIALIZER,
19535     SQLITE3_MUTEX_INITIALIZER
19536   };
19537   sqlite3_mutex *p;
19538   switch( iType ){
19539     case SQLITE_MUTEX_RECURSIVE: {
19540       p = sqlite3MallocZero( sizeof(*p) );
19541       if( p ){
19542 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
19543         /* If recursive mutexes are not available, we will have to
19544         ** build our own.  See below. */
19545         pthread_mutex_init(&p->mutex, 0);
19546 #else
19547         /* Use a recursive mutex if it is available */
19548         pthread_mutexattr_t recursiveAttr;
19549         pthread_mutexattr_init(&recursiveAttr);
19550         pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
19551         pthread_mutex_init(&p->mutex, &recursiveAttr);
19552         pthread_mutexattr_destroy(&recursiveAttr);
19553 #endif
19554       }
19555       break;
19556     }
19557     case SQLITE_MUTEX_FAST: {
19558       p = sqlite3MallocZero( sizeof(*p) );
19559       if( p ){
19560         pthread_mutex_init(&p->mutex, 0);
19561       }
19562       break;
19563     }
19564     default: {
19565 #ifdef SQLITE_ENABLE_API_ARMOR
19566       if( iType-2<0 || iType-2>=ArraySize(staticMutexes) ){
19567         (void)SQLITE_MISUSE_BKPT;
19568         return 0;
19569       }
19570 #endif
19571       p = &staticMutexes[iType-2];
19572       break;
19573     }
19574   }
19575 #if SQLITE_MUTEX_NREF || defined(SQLITE_ENABLE_API_ARMOR)
19576   if( p ) p->id = iType;
19577 #endif
19578   return p;
19579 }
19580
19581
19582 /*
19583 ** This routine deallocates a previously
19584 ** allocated mutex.  SQLite is careful to deallocate every
19585 ** mutex that it allocates.
19586 */
19587 static void pthreadMutexFree(sqlite3_mutex *p){
19588   assert( p->nRef==0 );
19589 #if SQLITE_ENABLE_API_ARMOR
19590   if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE )
19591 #endif
19592   {
19593     pthread_mutex_destroy(&p->mutex);
19594     sqlite3_free(p);
19595   }
19596 #ifdef SQLITE_ENABLE_API_ARMOR
19597   else{
19598     (void)SQLITE_MISUSE_BKPT;
19599   }
19600 #endif
19601 }
19602
19603 /*
19604 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
19605 ** to enter a mutex.  If another thread is already within the mutex,
19606 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
19607 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
19608 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
19609 ** be entered multiple times by the same thread.  In such cases the,
19610 ** mutex must be exited an equal number of times before another thread
19611 ** can enter.  If the same thread tries to enter any other kind of mutex
19612 ** more than once, the behavior is undefined.
19613 */
19614 static void pthreadMutexEnter(sqlite3_mutex *p){
19615   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
19616
19617 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
19618   /* If recursive mutexes are not available, then we have to grow
19619   ** our own.  This implementation assumes that pthread_equal()
19620   ** is atomic - that it cannot be deceived into thinking self
19621   ** and p->owner are equal if p->owner changes between two values
19622   ** that are not equal to self while the comparison is taking place.
19623   ** This implementation also assumes a coherent cache - that 
19624   ** separate processes cannot read different values from the same
19625   ** address at the same time.  If either of these two conditions
19626   ** are not met, then the mutexes will fail and problems will result.
19627   */
19628   {
19629     pthread_t self = pthread_self();
19630     if( p->nRef>0 && pthread_equal(p->owner, self) ){
19631       p->nRef++;
19632     }else{
19633       pthread_mutex_lock(&p->mutex);
19634       assert( p->nRef==0 );
19635       p->owner = self;
19636       p->nRef = 1;
19637     }
19638   }
19639 #else
19640   /* Use the built-in recursive mutexes if they are available.
19641   */
19642   pthread_mutex_lock(&p->mutex);
19643 #if SQLITE_MUTEX_NREF
19644   assert( p->nRef>0 || p->owner==0 );
19645   p->owner = pthread_self();
19646   p->nRef++;
19647 #endif
19648 #endif
19649
19650 #ifdef SQLITE_DEBUG
19651   if( p->trace ){
19652     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19653   }
19654 #endif
19655 }
19656 static int pthreadMutexTry(sqlite3_mutex *p){
19657   int rc;
19658   assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
19659
19660 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
19661   /* If recursive mutexes are not available, then we have to grow
19662   ** our own.  This implementation assumes that pthread_equal()
19663   ** is atomic - that it cannot be deceived into thinking self
19664   ** and p->owner are equal if p->owner changes between two values
19665   ** that are not equal to self while the comparison is taking place.
19666   ** This implementation also assumes a coherent cache - that 
19667   ** separate processes cannot read different values from the same
19668   ** address at the same time.  If either of these two conditions
19669   ** are not met, then the mutexes will fail and problems will result.
19670   */
19671   {
19672     pthread_t self = pthread_self();
19673     if( p->nRef>0 && pthread_equal(p->owner, self) ){
19674       p->nRef++;
19675       rc = SQLITE_OK;
19676     }else if( pthread_mutex_trylock(&p->mutex)==0 ){
19677       assert( p->nRef==0 );
19678       p->owner = self;
19679       p->nRef = 1;
19680       rc = SQLITE_OK;
19681     }else{
19682       rc = SQLITE_BUSY;
19683     }
19684   }
19685 #else
19686   /* Use the built-in recursive mutexes if they are available.
19687   */
19688   if( pthread_mutex_trylock(&p->mutex)==0 ){
19689 #if SQLITE_MUTEX_NREF
19690     p->owner = pthread_self();
19691     p->nRef++;
19692 #endif
19693     rc = SQLITE_OK;
19694   }else{
19695     rc = SQLITE_BUSY;
19696   }
19697 #endif
19698
19699 #ifdef SQLITE_DEBUG
19700   if( rc==SQLITE_OK && p->trace ){
19701     printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19702   }
19703 #endif
19704   return rc;
19705 }
19706
19707 /*
19708 ** The sqlite3_mutex_leave() routine exits a mutex that was
19709 ** previously entered by the same thread.  The behavior
19710 ** is undefined if the mutex is not currently entered or
19711 ** is not currently allocated.  SQLite will never do either.
19712 */
19713 static void pthreadMutexLeave(sqlite3_mutex *p){
19714   assert( pthreadMutexHeld(p) );
19715 #if SQLITE_MUTEX_NREF
19716   p->nRef--;
19717   if( p->nRef==0 ) p->owner = 0;
19718 #endif
19719   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
19720
19721 #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
19722   if( p->nRef==0 ){
19723     pthread_mutex_unlock(&p->mutex);
19724   }
19725 #else
19726   pthread_mutex_unlock(&p->mutex);
19727 #endif
19728
19729 #ifdef SQLITE_DEBUG
19730   if( p->trace ){
19731     printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
19732   }
19733 #endif
19734 }
19735
19736 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
19737   static const sqlite3_mutex_methods sMutex = {
19738     pthreadMutexInit,
19739     pthreadMutexEnd,
19740     pthreadMutexAlloc,
19741     pthreadMutexFree,
19742     pthreadMutexEnter,
19743     pthreadMutexTry,
19744     pthreadMutexLeave,
19745 #ifdef SQLITE_DEBUG
19746     pthreadMutexHeld,
19747     pthreadMutexNotheld
19748 #else
19749     0,
19750     0
19751 #endif
19752   };
19753
19754   return &sMutex;
19755 }
19756
19757 #endif /* SQLITE_MUTEX_PTHREADS */
19758
19759 /************** End of mutex_unix.c ******************************************/
19760 /************** Begin file mutex_w32.c ***************************************/
19761 /*
19762 ** 2007 August 14
19763 **
19764 ** The author disclaims copyright to this source code.  In place of
19765 ** a legal notice, here is a blessing:
19766 **
19767 **    May you do good and not evil.
19768 **    May you find forgiveness for yourself and forgive others.
19769 **    May you share freely, never taking more than you give.
19770 **
19771 *************************************************************************
19772 ** This file contains the C functions that implement mutexes for Win32.
19773 */
19774
19775 #if SQLITE_OS_WIN
19776 /*
19777 ** Include code that is common to all os_*.c files
19778 */
19779 /************** Include os_common.h in the middle of mutex_w32.c *************/
19780 /************** Begin file os_common.h ***************************************/
19781 /*
19782 ** 2004 May 22
19783 **
19784 ** The author disclaims copyright to this source code.  In place of
19785 ** a legal notice, here is a blessing:
19786 **
19787 **    May you do good and not evil.
19788 **    May you find forgiveness for yourself and forgive others.
19789 **    May you share freely, never taking more than you give.
19790 **
19791 ******************************************************************************
19792 **
19793 ** This file contains macros and a little bit of code that is common to
19794 ** all of the platform-specific files (os_*.c) and is #included into those
19795 ** files.
19796 **
19797 ** This file should be #included by the os_*.c files only.  It is not a
19798 ** general purpose header file.
19799 */
19800 #ifndef _OS_COMMON_H_
19801 #define _OS_COMMON_H_
19802
19803 /*
19804 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
19805 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
19806 ** switch.  The following code should catch this problem at compile-time.
19807 */
19808 #ifdef MEMORY_DEBUG
19809 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
19810 #endif
19811
19812 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
19813 # ifndef SQLITE_DEBUG_OS_TRACE
19814 #   define SQLITE_DEBUG_OS_TRACE 0
19815 # endif
19816   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
19817 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
19818 #else
19819 # define OSTRACE(X)
19820 #endif
19821
19822 /*
19823 ** Macros for performance tracing.  Normally turned off.  Only works
19824 ** on i486 hardware.
19825 */
19826 #ifdef SQLITE_PERFORMANCE_TRACE
19827
19828 /* 
19829 ** hwtime.h contains inline assembler code for implementing 
19830 ** high-performance timing routines.
19831 */
19832 /************** Include hwtime.h in the middle of os_common.h ****************/
19833 /************** Begin file hwtime.h ******************************************/
19834 /*
19835 ** 2008 May 27
19836 **
19837 ** The author disclaims copyright to this source code.  In place of
19838 ** a legal notice, here is a blessing:
19839 **
19840 **    May you do good and not evil.
19841 **    May you find forgiveness for yourself and forgive others.
19842 **    May you share freely, never taking more than you give.
19843 **
19844 ******************************************************************************
19845 **
19846 ** This file contains inline asm code for retrieving "high-performance"
19847 ** counters for x86 class CPUs.
19848 */
19849 #ifndef _HWTIME_H_
19850 #define _HWTIME_H_
19851
19852 /*
19853 ** The following routine only works on pentium-class (or newer) processors.
19854 ** It uses the RDTSC opcode to read the cycle count value out of the
19855 ** processor and returns that value.  This can be used for high-res
19856 ** profiling.
19857 */
19858 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
19859       (defined(i386) || defined(__i386__) || defined(_M_IX86))
19860
19861   #if defined(__GNUC__)
19862
19863   __inline__ sqlite_uint64 sqlite3Hwtime(void){
19864      unsigned int lo, hi;
19865      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
19866      return (sqlite_uint64)hi << 32 | lo;
19867   }
19868
19869   #elif defined(_MSC_VER)
19870
19871   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
19872      __asm {
19873         rdtsc
19874         ret       ; return value at EDX:EAX
19875      }
19876   }
19877
19878   #endif
19879
19880 #elif (defined(__GNUC__) && defined(__x86_64__))
19881
19882   __inline__ sqlite_uint64 sqlite3Hwtime(void){
19883       unsigned long val;
19884       __asm__ __volatile__ ("rdtsc" : "=A" (val));
19885       return val;
19886   }
19887  
19888 #elif (defined(__GNUC__) && defined(__ppc__))
19889
19890   __inline__ sqlite_uint64 sqlite3Hwtime(void){
19891       unsigned long long retval;
19892       unsigned long junk;
19893       __asm__ __volatile__ ("\n\
19894           1:      mftbu   %1\n\
19895                   mftb    %L0\n\
19896                   mftbu   %0\n\
19897                   cmpw    %0,%1\n\
19898                   bne     1b"
19899                   : "=r" (retval), "=r" (junk));
19900       return retval;
19901   }
19902
19903 #else
19904
19905   #error Need implementation of sqlite3Hwtime() for your platform.
19906
19907   /*
19908   ** To compile without implementing sqlite3Hwtime() for your platform,
19909   ** you can remove the above #error and use the following
19910   ** stub function.  You will lose timing support for many
19911   ** of the debugging and testing utilities, but it should at
19912   ** least compile and run.
19913   */
19914 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
19915
19916 #endif
19917
19918 #endif /* !defined(_HWTIME_H_) */
19919
19920 /************** End of hwtime.h **********************************************/
19921 /************** Continuing where we left off in os_common.h ******************/
19922
19923 static sqlite_uint64 g_start;
19924 static sqlite_uint64 g_elapsed;
19925 #define TIMER_START       g_start=sqlite3Hwtime()
19926 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
19927 #define TIMER_ELAPSED     g_elapsed
19928 #else
19929 #define TIMER_START
19930 #define TIMER_END
19931 #define TIMER_ELAPSED     ((sqlite_uint64)0)
19932 #endif
19933
19934 /*
19935 ** If we compile with the SQLITE_TEST macro set, then the following block
19936 ** of code will give us the ability to simulate a disk I/O error.  This
19937 ** is used for testing the I/O recovery logic.
19938 */
19939 #ifdef SQLITE_TEST
19940 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
19941 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
19942 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
19943 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
19944 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
19945 SQLITE_API int sqlite3_diskfull_pending = 0;
19946 SQLITE_API int sqlite3_diskfull = 0;
19947 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
19948 #define SimulateIOError(CODE)  \
19949   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
19950        || sqlite3_io_error_pending-- == 1 )  \
19951               { local_ioerr(); CODE; }
19952 static void local_ioerr(){
19953   IOTRACE(("IOERR\n"));
19954   sqlite3_io_error_hit++;
19955   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
19956 }
19957 #define SimulateDiskfullError(CODE) \
19958    if( sqlite3_diskfull_pending ){ \
19959      if( sqlite3_diskfull_pending == 1 ){ \
19960        local_ioerr(); \
19961        sqlite3_diskfull = 1; \
19962        sqlite3_io_error_hit = 1; \
19963        CODE; \
19964      }else{ \
19965        sqlite3_diskfull_pending--; \
19966      } \
19967    }
19968 #else
19969 #define SimulateIOErrorBenign(X)
19970 #define SimulateIOError(A)
19971 #define SimulateDiskfullError(A)
19972 #endif
19973
19974 /*
19975 ** When testing, keep a count of the number of open files.
19976 */
19977 #ifdef SQLITE_TEST
19978 SQLITE_API int sqlite3_open_file_count = 0;
19979 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
19980 #else
19981 #define OpenCounter(X)
19982 #endif
19983
19984 #endif /* !defined(_OS_COMMON_H_) */
19985
19986 /************** End of os_common.h *******************************************/
19987 /************** Continuing where we left off in mutex_w32.c ******************/
19988
19989 /*
19990 ** Include the header file for the Windows VFS.
19991 */
19992 /************** Include os_win.h in the middle of mutex_w32.c ****************/
19993 /************** Begin file os_win.h ******************************************/
19994 /*
19995 ** 2013 November 25
19996 **
19997 ** The author disclaims copyright to this source code.  In place of
19998 ** a legal notice, here is a blessing:
19999 **
20000 **    May you do good and not evil.
20001 **    May you find forgiveness for yourself and forgive others.
20002 **    May you share freely, never taking more than you give.
20003 **
20004 ******************************************************************************
20005 **
20006 ** This file contains code that is specific to Windows.
20007 */
20008 #ifndef _OS_WIN_H_
20009 #define _OS_WIN_H_
20010
20011 /*
20012 ** Include the primary Windows SDK header file.
20013 */
20014 #include "windows.h"
20015
20016 #ifdef __CYGWIN__
20017 # include <sys/cygwin.h>
20018 # include <errno.h> /* amalgamator: dontcache */
20019 #endif
20020
20021 /*
20022 ** Determine if we are dealing with Windows NT.
20023 **
20024 ** We ought to be able to determine if we are compiling for Windows 9x or
20025 ** Windows NT using the _WIN32_WINNT macro as follows:
20026 **
20027 ** #if defined(_WIN32_WINNT)
20028 ** # define SQLITE_OS_WINNT 1
20029 ** #else
20030 ** # define SQLITE_OS_WINNT 0
20031 ** #endif
20032 **
20033 ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
20034 ** it ought to, so the above test does not work.  We'll just assume that
20035 ** everything is Windows NT unless the programmer explicitly says otherwise
20036 ** by setting SQLITE_OS_WINNT to 0.
20037 */
20038 #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
20039 # define SQLITE_OS_WINNT 1
20040 #endif
20041
20042 /*
20043 ** Determine if we are dealing with Windows CE - which has a much reduced
20044 ** API.
20045 */
20046 #if defined(_WIN32_WCE)
20047 # define SQLITE_OS_WINCE 1
20048 #else
20049 # define SQLITE_OS_WINCE 0
20050 #endif
20051
20052 /*
20053 ** Determine if we are dealing with WinRT, which provides only a subset of
20054 ** the full Win32 API.
20055 */
20056 #if !defined(SQLITE_OS_WINRT)
20057 # define SQLITE_OS_WINRT 0
20058 #endif
20059
20060 /*
20061 ** For WinCE, some API function parameters do not appear to be declared as
20062 ** volatile.
20063 */
20064 #if SQLITE_OS_WINCE
20065 # define SQLITE_WIN32_VOLATILE
20066 #else
20067 # define SQLITE_WIN32_VOLATILE volatile
20068 #endif
20069
20070 /*
20071 ** For some Windows sub-platforms, the _beginthreadex() / _endthreadex()
20072 ** functions are not available (e.g. those not using MSVC, Cygwin, etc).
20073 */
20074 #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
20075     SQLITE_THREADSAFE>0 && !defined(__CYGWIN__)
20076 # define SQLITE_OS_WIN_THREADS 1
20077 #else
20078 # define SQLITE_OS_WIN_THREADS 0
20079 #endif
20080
20081 #endif /* _OS_WIN_H_ */
20082
20083 /************** End of os_win.h **********************************************/
20084 /************** Continuing where we left off in mutex_w32.c ******************/
20085 #endif
20086
20087 /*
20088 ** The code in this file is only used if we are compiling multithreaded
20089 ** on a Win32 system.
20090 */
20091 #ifdef SQLITE_MUTEX_W32
20092
20093 /*
20094 ** Each recursive mutex is an instance of the following structure.
20095 */
20096 struct sqlite3_mutex {
20097   CRITICAL_SECTION mutex;    /* Mutex controlling the lock */
20098   int id;                    /* Mutex type */
20099 #ifdef SQLITE_DEBUG
20100   volatile int nRef;         /* Number of enterances */
20101   volatile DWORD owner;      /* Thread holding this mutex */
20102   volatile int trace;        /* True to trace changes */
20103 #endif
20104 };
20105
20106 /*
20107 ** These are the initializer values used when declaring a "static" mutex
20108 ** on Win32.  It should be noted that all mutexes require initialization
20109 ** on the Win32 platform.
20110 */
20111 #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
20112
20113 #ifdef SQLITE_DEBUG
20114 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
20115                                     0L, (DWORD)0, 0 }
20116 #else
20117 #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
20118 #endif
20119
20120 #ifdef SQLITE_DEBUG
20121 /*
20122 ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
20123 ** intended for use only inside assert() statements.
20124 */
20125 static int winMutexHeld(sqlite3_mutex *p){
20126   return p->nRef!=0 && p->owner==GetCurrentThreadId();
20127 }
20128
20129 static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
20130   return p->nRef==0 || p->owner!=tid;
20131 }
20132
20133 static int winMutexNotheld(sqlite3_mutex *p){
20134   DWORD tid = GetCurrentThreadId();
20135   return winMutexNotheld2(p, tid);
20136 }
20137 #endif
20138
20139 /*
20140 ** Initialize and deinitialize the mutex subsystem.
20141 */
20142 static sqlite3_mutex winMutex_staticMutexes[] = {
20143   SQLITE3_MUTEX_INITIALIZER,
20144   SQLITE3_MUTEX_INITIALIZER,
20145   SQLITE3_MUTEX_INITIALIZER,
20146   SQLITE3_MUTEX_INITIALIZER,
20147   SQLITE3_MUTEX_INITIALIZER,
20148   SQLITE3_MUTEX_INITIALIZER,
20149   SQLITE3_MUTEX_INITIALIZER,
20150   SQLITE3_MUTEX_INITIALIZER,
20151   SQLITE3_MUTEX_INITIALIZER
20152 };
20153
20154 static int winMutex_isInit = 0;
20155 static int winMutex_isNt = -1; /* <0 means "need to query" */
20156
20157 /* As the winMutexInit() and winMutexEnd() functions are called as part
20158 ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
20159 ** "interlocked" magic used here is probably not strictly necessary.
20160 */
20161 static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
20162
20163 SQLITE_API int SQLITE_STDCALL sqlite3_win32_is_nt(void); /* os_win.c */
20164 SQLITE_API void SQLITE_STDCALL sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
20165
20166 static int winMutexInit(void){
20167   /* The first to increment to 1 does actual initialization */
20168   if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
20169     int i;
20170     for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
20171 #if SQLITE_OS_WINRT
20172       InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
20173 #else
20174       InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
20175 #endif
20176     }
20177     winMutex_isInit = 1;
20178   }else{
20179     /* Another thread is (in the process of) initializing the static
20180     ** mutexes */
20181     while( !winMutex_isInit ){
20182       sqlite3_win32_sleep(1);
20183     }
20184   }
20185   return SQLITE_OK;
20186 }
20187
20188 static int winMutexEnd(void){
20189   /* The first to decrement to 0 does actual shutdown
20190   ** (which should be the last to shutdown.) */
20191   if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
20192     if( winMutex_isInit==1 ){
20193       int i;
20194       for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
20195         DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
20196       }
20197       winMutex_isInit = 0;
20198     }
20199   }
20200   return SQLITE_OK;
20201 }
20202
20203 /*
20204 ** The sqlite3_mutex_alloc() routine allocates a new
20205 ** mutex and returns a pointer to it.  If it returns NULL
20206 ** that means that a mutex could not be allocated.  SQLite
20207 ** will unwind its stack and return an error.  The argument
20208 ** to sqlite3_mutex_alloc() is one of these integer constants:
20209 **
20210 ** <ul>
20211 ** <li>  SQLITE_MUTEX_FAST
20212 ** <li>  SQLITE_MUTEX_RECURSIVE
20213 ** <li>  SQLITE_MUTEX_STATIC_MASTER
20214 ** <li>  SQLITE_MUTEX_STATIC_MEM
20215 ** <li>  SQLITE_MUTEX_STATIC_OPEN
20216 ** <li>  SQLITE_MUTEX_STATIC_PRNG
20217 ** <li>  SQLITE_MUTEX_STATIC_LRU
20218 ** <li>  SQLITE_MUTEX_STATIC_PMEM
20219 ** <li>  SQLITE_MUTEX_STATIC_APP1
20220 ** <li>  SQLITE_MUTEX_STATIC_APP2
20221 ** <li>  SQLITE_MUTEX_STATIC_APP3
20222 ** </ul>
20223 **
20224 ** The first two constants cause sqlite3_mutex_alloc() to create
20225 ** a new mutex.  The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
20226 ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
20227 ** The mutex implementation does not need to make a distinction
20228 ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
20229 ** not want to.  But SQLite will only request a recursive mutex in
20230 ** cases where it really needs one.  If a faster non-recursive mutex
20231 ** implementation is available on the host platform, the mutex subsystem
20232 ** might return such a mutex in response to SQLITE_MUTEX_FAST.
20233 **
20234 ** The other allowed parameters to sqlite3_mutex_alloc() each return
20235 ** a pointer to a static preexisting mutex.  Six static mutexes are
20236 ** used by the current version of SQLite.  Future versions of SQLite
20237 ** may add additional static mutexes.  Static mutexes are for internal
20238 ** use by SQLite only.  Applications that use SQLite mutexes should
20239 ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
20240 ** SQLITE_MUTEX_RECURSIVE.
20241 **
20242 ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
20243 ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
20244 ** returns a different mutex on every call.  But for the static
20245 ** mutex types, the same mutex is returned on every call that has
20246 ** the same type number.
20247 */
20248 static sqlite3_mutex *winMutexAlloc(int iType){
20249   sqlite3_mutex *p;
20250
20251   switch( iType ){
20252     case SQLITE_MUTEX_FAST:
20253     case SQLITE_MUTEX_RECURSIVE: {
20254       p = sqlite3MallocZero( sizeof(*p) );
20255       if( p ){
20256         p->id = iType;
20257 #ifdef SQLITE_DEBUG
20258 #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
20259         p->trace = 1;
20260 #endif
20261 #endif
20262 #if SQLITE_OS_WINRT
20263         InitializeCriticalSectionEx(&p->mutex, 0, 0);
20264 #else
20265         InitializeCriticalSection(&p->mutex);
20266 #endif
20267       }
20268       break;
20269     }
20270     default: {
20271 #ifdef SQLITE_ENABLE_API_ARMOR
20272       if( iType-2<0 || iType-2>=ArraySize(winMutex_staticMutexes) ){
20273         (void)SQLITE_MISUSE_BKPT;
20274         return 0;
20275       }
20276 #endif
20277       p = &winMutex_staticMutexes[iType-2];
20278       p->id = iType;
20279 #ifdef SQLITE_DEBUG
20280 #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
20281       p->trace = 1;
20282 #endif
20283 #endif
20284       break;
20285     }
20286   }
20287   return p;
20288 }
20289
20290
20291 /*
20292 ** This routine deallocates a previously
20293 ** allocated mutex.  SQLite is careful to deallocate every
20294 ** mutex that it allocates.
20295 */
20296 static void winMutexFree(sqlite3_mutex *p){
20297   assert( p );
20298   assert( p->nRef==0 && p->owner==0 );
20299   if( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE ){
20300     DeleteCriticalSection(&p->mutex);
20301     sqlite3_free(p);
20302   }else{
20303 #ifdef SQLITE_ENABLE_API_ARMOR
20304     (void)SQLITE_MISUSE_BKPT;
20305 #endif
20306   }
20307 }
20308
20309 /*
20310 ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
20311 ** to enter a mutex.  If another thread is already within the mutex,
20312 ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
20313 ** SQLITE_BUSY.  The sqlite3_mutex_try() interface returns SQLITE_OK
20314 ** upon successful entry.  Mutexes created using SQLITE_MUTEX_RECURSIVE can
20315 ** be entered multiple times by the same thread.  In such cases the,
20316 ** mutex must be exited an equal number of times before another thread
20317 ** can enter.  If the same thread tries to enter any other kind of mutex
20318 ** more than once, the behavior is undefined.
20319 */
20320 static void winMutexEnter(sqlite3_mutex *p){
20321 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
20322   DWORD tid = GetCurrentThreadId();
20323 #endif
20324 #ifdef SQLITE_DEBUG
20325   assert( p );
20326   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
20327 #else
20328   assert( p );
20329 #endif
20330   assert( winMutex_isInit==1 );
20331   EnterCriticalSection(&p->mutex);
20332 #ifdef SQLITE_DEBUG
20333   assert( p->nRef>0 || p->owner==0 );
20334   p->owner = tid;
20335   p->nRef++;
20336   if( p->trace ){
20337     OSTRACE(("ENTER-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
20338              tid, p, p->trace, p->nRef));
20339   }
20340 #endif
20341 }
20342
20343 static int winMutexTry(sqlite3_mutex *p){
20344 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
20345   DWORD tid = GetCurrentThreadId();
20346 #endif
20347   int rc = SQLITE_BUSY;
20348   assert( p );
20349   assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
20350   /*
20351   ** The sqlite3_mutex_try() routine is very rarely used, and when it
20352   ** is used it is merely an optimization.  So it is OK for it to always
20353   ** fail.
20354   **
20355   ** The TryEnterCriticalSection() interface is only available on WinNT.
20356   ** And some windows compilers complain if you try to use it without
20357   ** first doing some #defines that prevent SQLite from building on Win98.
20358   ** For that reason, we will omit this optimization for now.  See
20359   ** ticket #2685.
20360   */
20361 #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
20362   assert( winMutex_isInit==1 );
20363   assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
20364   if( winMutex_isNt<0 ){
20365     winMutex_isNt = sqlite3_win32_is_nt();
20366   }
20367   assert( winMutex_isNt==0 || winMutex_isNt==1 );
20368   if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
20369 #ifdef SQLITE_DEBUG
20370     p->owner = tid;
20371     p->nRef++;
20372 #endif
20373     rc = SQLITE_OK;
20374   }
20375 #else
20376   UNUSED_PARAMETER(p);
20377 #endif
20378 #ifdef SQLITE_DEBUG
20379   if( p->trace ){
20380     OSTRACE(("TRY-MUTEX tid=%lu, mutex=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
20381              tid, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
20382   }
20383 #endif
20384   return rc;
20385 }
20386
20387 /*
20388 ** The sqlite3_mutex_leave() routine exits a mutex that was
20389 ** previously entered by the same thread.  The behavior
20390 ** is undefined if the mutex is not currently entered or
20391 ** is not currently allocated.  SQLite will never do either.
20392 */
20393 static void winMutexLeave(sqlite3_mutex *p){
20394 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
20395   DWORD tid = GetCurrentThreadId();
20396 #endif
20397   assert( p );
20398 #ifdef SQLITE_DEBUG
20399   assert( p->nRef>0 );
20400   assert( p->owner==tid );
20401   p->nRef--;
20402   if( p->nRef==0 ) p->owner = 0;
20403   assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
20404 #endif
20405   assert( winMutex_isInit==1 );
20406   LeaveCriticalSection(&p->mutex);
20407 #ifdef SQLITE_DEBUG
20408   if( p->trace ){
20409     OSTRACE(("LEAVE-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
20410              tid, p, p->trace, p->nRef));
20411   }
20412 #endif
20413 }
20414
20415 SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
20416   static const sqlite3_mutex_methods sMutex = {
20417     winMutexInit,
20418     winMutexEnd,
20419     winMutexAlloc,
20420     winMutexFree,
20421     winMutexEnter,
20422     winMutexTry,
20423     winMutexLeave,
20424 #ifdef SQLITE_DEBUG
20425     winMutexHeld,
20426     winMutexNotheld
20427 #else
20428     0,
20429     0
20430 #endif
20431   };
20432   return &sMutex;
20433 }
20434
20435 #endif /* SQLITE_MUTEX_W32 */
20436
20437 /************** End of mutex_w32.c *******************************************/
20438 /************** Begin file malloc.c ******************************************/
20439 /*
20440 ** 2001 September 15
20441 **
20442 ** The author disclaims copyright to this source code.  In place of
20443 ** a legal notice, here is a blessing:
20444 **
20445 **    May you do good and not evil.
20446 **    May you find forgiveness for yourself and forgive others.
20447 **    May you share freely, never taking more than you give.
20448 **
20449 *************************************************************************
20450 **
20451 ** Memory allocation functions used throughout sqlite.
20452 */
20453 /* #include <stdarg.h> */
20454
20455 /*
20456 ** Attempt to release up to n bytes of non-essential memory currently
20457 ** held by SQLite. An example of non-essential memory is memory used to
20458 ** cache database pages that are not currently in use.
20459 */
20460 SQLITE_API int SQLITE_STDCALL sqlite3_release_memory(int n){
20461 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
20462   return sqlite3PcacheReleaseMemory(n);
20463 #else
20464   /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
20465   ** is a no-op returning zero if SQLite is not compiled with
20466   ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
20467   UNUSED_PARAMETER(n);
20468   return 0;
20469 #endif
20470 }
20471
20472 /*
20473 ** An instance of the following object records the location of
20474 ** each unused scratch buffer.
20475 */
20476 typedef struct ScratchFreeslot {
20477   struct ScratchFreeslot *pNext;   /* Next unused scratch buffer */
20478 } ScratchFreeslot;
20479
20480 /*
20481 ** State information local to the memory allocation subsystem.
20482 */
20483 static SQLITE_WSD struct Mem0Global {
20484   sqlite3_mutex *mutex;         /* Mutex to serialize access */
20485
20486   /*
20487   ** The alarm callback and its arguments.  The mem0.mutex lock will
20488   ** be held while the callback is running.  Recursive calls into
20489   ** the memory subsystem are allowed, but no new callbacks will be
20490   ** issued.
20491   */
20492   sqlite3_int64 alarmThreshold;
20493   void (*alarmCallback)(void*, sqlite3_int64,int);
20494   void *alarmArg;
20495
20496   /*
20497   ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
20498   ** (so that a range test can be used to determine if an allocation
20499   ** being freed came from pScratch) and a pointer to the list of
20500   ** unused scratch allocations.
20501   */
20502   void *pScratchEnd;
20503   ScratchFreeslot *pScratchFree;
20504   u32 nScratchFree;
20505
20506   /*
20507   ** True if heap is nearly "full" where "full" is defined by the
20508   ** sqlite3_soft_heap_limit() setting.
20509   */
20510   int nearlyFull;
20511 } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
20512
20513 #define mem0 GLOBAL(struct Mem0Global, mem0)
20514
20515 /*
20516 ** Return the memory allocator mutex. sqlite3_status() needs it.
20517 */
20518 SQLITE_PRIVATE sqlite3_mutex *sqlite3MallocMutex(void){
20519   return mem0.mutex;
20520 }
20521
20522 /*
20523 ** This routine runs when the memory allocator sees that the
20524 ** total memory allocation is about to exceed the soft heap
20525 ** limit.
20526 */
20527 static void softHeapLimitEnforcer(
20528   void *NotUsed, 
20529   sqlite3_int64 NotUsed2,
20530   int allocSize
20531 ){
20532   UNUSED_PARAMETER2(NotUsed, NotUsed2);
20533   sqlite3_release_memory(allocSize);
20534 }
20535
20536 /*
20537 ** Change the alarm callback
20538 */
20539 static int sqlite3MemoryAlarm(
20540   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
20541   void *pArg,
20542   sqlite3_int64 iThreshold
20543 ){
20544   sqlite3_int64 nUsed;
20545   sqlite3_mutex_enter(mem0.mutex);
20546   mem0.alarmCallback = xCallback;
20547   mem0.alarmArg = pArg;
20548   mem0.alarmThreshold = iThreshold;
20549   nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
20550   mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
20551   sqlite3_mutex_leave(mem0.mutex);
20552   return SQLITE_OK;
20553 }
20554
20555 #ifndef SQLITE_OMIT_DEPRECATED
20556 /*
20557 ** Deprecated external interface.  Internal/core SQLite code
20558 ** should call sqlite3MemoryAlarm.
20559 */
20560 SQLITE_API int SQLITE_STDCALL sqlite3_memory_alarm(
20561   void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
20562   void *pArg,
20563   sqlite3_int64 iThreshold
20564 ){
20565   return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
20566 }
20567 #endif
20568
20569 /*
20570 ** Set the soft heap-size limit for the library. Passing a zero or 
20571 ** negative value indicates no limit.
20572 */
20573 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_soft_heap_limit64(sqlite3_int64 n){
20574   sqlite3_int64 priorLimit;
20575   sqlite3_int64 excess;
20576 #ifndef SQLITE_OMIT_AUTOINIT
20577   int rc = sqlite3_initialize();
20578   if( rc ) return -1;
20579 #endif
20580   sqlite3_mutex_enter(mem0.mutex);
20581   priorLimit = mem0.alarmThreshold;
20582   sqlite3_mutex_leave(mem0.mutex);
20583   if( n<0 ) return priorLimit;
20584   if( n>0 ){
20585     sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
20586   }else{
20587     sqlite3MemoryAlarm(0, 0, 0);
20588   }
20589   excess = sqlite3_memory_used() - n;
20590   if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
20591   return priorLimit;
20592 }
20593 SQLITE_API void SQLITE_STDCALL sqlite3_soft_heap_limit(int n){
20594   if( n<0 ) n = 0;
20595   sqlite3_soft_heap_limit64(n);
20596 }
20597
20598 /*
20599 ** Initialize the memory allocation subsystem.
20600 */
20601 SQLITE_PRIVATE int sqlite3MallocInit(void){
20602   int rc;
20603   if( sqlite3GlobalConfig.m.xMalloc==0 ){
20604     sqlite3MemSetDefault();
20605   }
20606   memset(&mem0, 0, sizeof(mem0));
20607   if( sqlite3GlobalConfig.bCoreMutex ){
20608     mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
20609   }
20610   if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
20611       && sqlite3GlobalConfig.nScratch>0 ){
20612     int i, n, sz;
20613     ScratchFreeslot *pSlot;
20614     sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
20615     sqlite3GlobalConfig.szScratch = sz;
20616     pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
20617     n = sqlite3GlobalConfig.nScratch;
20618     mem0.pScratchFree = pSlot;
20619     mem0.nScratchFree = n;
20620     for(i=0; i<n-1; i++){
20621       pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
20622       pSlot = pSlot->pNext;
20623     }
20624     pSlot->pNext = 0;
20625     mem0.pScratchEnd = (void*)&pSlot[1];
20626   }else{
20627     mem0.pScratchEnd = 0;
20628     sqlite3GlobalConfig.pScratch = 0;
20629     sqlite3GlobalConfig.szScratch = 0;
20630     sqlite3GlobalConfig.nScratch = 0;
20631   }
20632   if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
20633       || sqlite3GlobalConfig.nPage<1 ){
20634     sqlite3GlobalConfig.pPage = 0;
20635     sqlite3GlobalConfig.szPage = 0;
20636     sqlite3GlobalConfig.nPage = 0;
20637   }
20638   rc = sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
20639   if( rc!=SQLITE_OK ) memset(&mem0, 0, sizeof(mem0));
20640   return rc;
20641 }
20642
20643 /*
20644 ** Return true if the heap is currently under memory pressure - in other
20645 ** words if the amount of heap used is close to the limit set by
20646 ** sqlite3_soft_heap_limit().
20647 */
20648 SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
20649   return mem0.nearlyFull;
20650 }
20651
20652 /*
20653 ** Deinitialize the memory allocation subsystem.
20654 */
20655 SQLITE_PRIVATE void sqlite3MallocEnd(void){
20656   if( sqlite3GlobalConfig.m.xShutdown ){
20657     sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
20658   }
20659   memset(&mem0, 0, sizeof(mem0));
20660 }
20661
20662 /*
20663 ** Return the amount of memory currently checked out.
20664 */
20665 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_used(void){
20666   int n, mx;
20667   sqlite3_int64 res;
20668   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
20669   res = (sqlite3_int64)n;  /* Work around bug in Borland C. Ticket #3216 */
20670   return res;
20671 }
20672
20673 /*
20674 ** Return the maximum amount of memory that has ever been
20675 ** checked out since either the beginning of this process
20676 ** or since the most recent reset.
20677 */
20678 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_memory_highwater(int resetFlag){
20679   int n, mx;
20680   sqlite3_int64 res;
20681   sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
20682   res = (sqlite3_int64)mx;  /* Work around bug in Borland C. Ticket #3216 */
20683   return res;
20684 }
20685
20686 /*
20687 ** Trigger the alarm 
20688 */
20689 static void sqlite3MallocAlarm(int nByte){
20690   void (*xCallback)(void*,sqlite3_int64,int);
20691   sqlite3_int64 nowUsed;
20692   void *pArg;
20693   if( mem0.alarmCallback==0 ) return;
20694   xCallback = mem0.alarmCallback;
20695   nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
20696   pArg = mem0.alarmArg;
20697   mem0.alarmCallback = 0;
20698   sqlite3_mutex_leave(mem0.mutex);
20699   xCallback(pArg, nowUsed, nByte);
20700   sqlite3_mutex_enter(mem0.mutex);
20701   mem0.alarmCallback = xCallback;
20702   mem0.alarmArg = pArg;
20703 }
20704
20705 /*
20706 ** Do a memory allocation with statistics and alarms.  Assume the
20707 ** lock is already held.
20708 */
20709 static int mallocWithAlarm(int n, void **pp){
20710   int nFull;
20711   void *p;
20712   assert( sqlite3_mutex_held(mem0.mutex) );
20713   nFull = sqlite3GlobalConfig.m.xRoundup(n);
20714   sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
20715   if( mem0.alarmCallback!=0 ){
20716     sqlite3_int64 nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
20717     if( nUsed >= mem0.alarmThreshold - nFull ){
20718       mem0.nearlyFull = 1;
20719       sqlite3MallocAlarm(nFull);
20720     }else{
20721       mem0.nearlyFull = 0;
20722     }
20723   }
20724   p = sqlite3GlobalConfig.m.xMalloc(nFull);
20725 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
20726   if( p==0 && mem0.alarmCallback ){
20727     sqlite3MallocAlarm(nFull);
20728     p = sqlite3GlobalConfig.m.xMalloc(nFull);
20729   }
20730 #endif
20731   if( p ){
20732     nFull = sqlite3MallocSize(p);
20733     sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nFull);
20734     sqlite3StatusUp(SQLITE_STATUS_MALLOC_COUNT, 1);
20735   }
20736   *pp = p;
20737   return nFull;
20738 }
20739
20740 /*
20741 ** Allocate memory.  This routine is like sqlite3_malloc() except that it
20742 ** assumes the memory subsystem has already been initialized.
20743 */
20744 SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
20745   void *p;
20746   if( n==0 || n>=0x7fffff00 ){
20747     /* A memory allocation of a number of bytes which is near the maximum
20748     ** signed integer value might cause an integer overflow inside of the
20749     ** xMalloc().  Hence we limit the maximum size to 0x7fffff00, giving
20750     ** 255 bytes of overhead.  SQLite itself will never use anything near
20751     ** this amount.  The only way to reach the limit is with sqlite3_malloc() */
20752     p = 0;
20753   }else if( sqlite3GlobalConfig.bMemstat ){
20754     sqlite3_mutex_enter(mem0.mutex);
20755     mallocWithAlarm((int)n, &p);
20756     sqlite3_mutex_leave(mem0.mutex);
20757   }else{
20758     p = sqlite3GlobalConfig.m.xMalloc((int)n);
20759   }
20760   assert( EIGHT_BYTE_ALIGNMENT(p) );  /* IMP: R-11148-40995 */
20761   return p;
20762 }
20763
20764 /*
20765 ** This version of the memory allocation is for use by the application.
20766 ** First make sure the memory subsystem is initialized, then do the
20767 ** allocation.
20768 */
20769 SQLITE_API void *SQLITE_STDCALL sqlite3_malloc(int n){
20770 #ifndef SQLITE_OMIT_AUTOINIT
20771   if( sqlite3_initialize() ) return 0;
20772 #endif
20773   return n<=0 ? 0 : sqlite3Malloc(n);
20774 }
20775 SQLITE_API void *SQLITE_STDCALL sqlite3_malloc64(sqlite3_uint64 n){
20776 #ifndef SQLITE_OMIT_AUTOINIT
20777   if( sqlite3_initialize() ) return 0;
20778 #endif
20779   return sqlite3Malloc(n);
20780 }
20781
20782 /*
20783 ** Each thread may only have a single outstanding allocation from
20784 ** xScratchMalloc().  We verify this constraint in the single-threaded
20785 ** case by setting scratchAllocOut to 1 when an allocation
20786 ** is outstanding clearing it when the allocation is freed.
20787 */
20788 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
20789 static int scratchAllocOut = 0;
20790 #endif
20791
20792
20793 /*
20794 ** Allocate memory that is to be used and released right away.
20795 ** This routine is similar to alloca() in that it is not intended
20796 ** for situations where the memory might be held long-term.  This
20797 ** routine is intended to get memory to old large transient data
20798 ** structures that would not normally fit on the stack of an
20799 ** embedded processor.
20800 */
20801 SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
20802   void *p;
20803   assert( n>0 );
20804
20805   sqlite3_mutex_enter(mem0.mutex);
20806   sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
20807   if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
20808     p = mem0.pScratchFree;
20809     mem0.pScratchFree = mem0.pScratchFree->pNext;
20810     mem0.nScratchFree--;
20811     sqlite3StatusUp(SQLITE_STATUS_SCRATCH_USED, 1);
20812     sqlite3_mutex_leave(mem0.mutex);
20813   }else{
20814     sqlite3_mutex_leave(mem0.mutex);
20815     p = sqlite3Malloc(n);
20816     if( sqlite3GlobalConfig.bMemstat && p ){
20817       sqlite3_mutex_enter(mem0.mutex);
20818       sqlite3StatusUp(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p));
20819       sqlite3_mutex_leave(mem0.mutex);
20820     }
20821     sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
20822   }
20823   assert( sqlite3_mutex_notheld(mem0.mutex) );
20824
20825
20826 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
20827   /* EVIDENCE-OF: R-12970-05880 SQLite will not use more than one scratch
20828   ** buffers per thread.
20829   **
20830   ** This can only be checked in single-threaded mode.
20831   */
20832   assert( scratchAllocOut==0 );
20833   if( p ) scratchAllocOut++;
20834 #endif
20835
20836   return p;
20837 }
20838 SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
20839   if( p ){
20840
20841 #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
20842     /* Verify that no more than two scratch allocation per thread
20843     ** is outstanding at one time.  (This is only checked in the
20844     ** single-threaded case since checking in the multi-threaded case
20845     ** would be much more complicated.) */
20846     assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
20847     scratchAllocOut--;
20848 #endif
20849
20850     if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
20851       /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
20852       ScratchFreeslot *pSlot;
20853       pSlot = (ScratchFreeslot*)p;
20854       sqlite3_mutex_enter(mem0.mutex);
20855       pSlot->pNext = mem0.pScratchFree;
20856       mem0.pScratchFree = pSlot;
20857       mem0.nScratchFree++;
20858       assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
20859       sqlite3StatusDown(SQLITE_STATUS_SCRATCH_USED, 1);
20860       sqlite3_mutex_leave(mem0.mutex);
20861     }else{
20862       /* Release memory back to the heap */
20863       assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
20864       assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_SCRATCH) );
20865       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
20866       if( sqlite3GlobalConfig.bMemstat ){
20867         int iSize = sqlite3MallocSize(p);
20868         sqlite3_mutex_enter(mem0.mutex);
20869         sqlite3StatusDown(SQLITE_STATUS_SCRATCH_OVERFLOW, iSize);
20870         sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, iSize);
20871         sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
20872         sqlite3GlobalConfig.m.xFree(p);
20873         sqlite3_mutex_leave(mem0.mutex);
20874       }else{
20875         sqlite3GlobalConfig.m.xFree(p);
20876       }
20877     }
20878   }
20879 }
20880
20881 /*
20882 ** TRUE if p is a lookaside memory allocation from db
20883 */
20884 #ifndef SQLITE_OMIT_LOOKASIDE
20885 static int isLookaside(sqlite3 *db, void *p){
20886   return p>=db->lookaside.pStart && p<db->lookaside.pEnd;
20887 }
20888 #else
20889 #define isLookaside(A,B) 0
20890 #endif
20891
20892 /*
20893 ** Return the size of a memory allocation previously obtained from
20894 ** sqlite3Malloc() or sqlite3_malloc().
20895 */
20896 SQLITE_PRIVATE int sqlite3MallocSize(void *p){
20897   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
20898   return sqlite3GlobalConfig.m.xSize(p);
20899 }
20900 SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
20901   if( db==0 ){
20902     assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
20903     assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
20904     return sqlite3MallocSize(p);
20905   }else{
20906     assert( sqlite3_mutex_held(db->mutex) );
20907     if( isLookaside(db, p) ){
20908       return db->lookaside.sz;
20909     }else{
20910       assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
20911       assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
20912       return sqlite3GlobalConfig.m.xSize(p);
20913     }
20914   }
20915 }
20916 SQLITE_API sqlite3_uint64 SQLITE_STDCALL sqlite3_msize(void *p){
20917   assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
20918   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
20919   return (sqlite3_uint64)sqlite3GlobalConfig.m.xSize(p);
20920 }
20921
20922 /*
20923 ** Free memory previously obtained from sqlite3Malloc().
20924 */
20925 SQLITE_API void SQLITE_STDCALL sqlite3_free(void *p){
20926   if( p==0 ) return;  /* IMP: R-49053-54554 */
20927   assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
20928   assert( sqlite3MemdebugNoType(p, (u8)~MEMTYPE_HEAP) );
20929   if( sqlite3GlobalConfig.bMemstat ){
20930     sqlite3_mutex_enter(mem0.mutex);
20931     sqlite3StatusDown(SQLITE_STATUS_MEMORY_USED, sqlite3MallocSize(p));
20932     sqlite3StatusDown(SQLITE_STATUS_MALLOC_COUNT, 1);
20933     sqlite3GlobalConfig.m.xFree(p);
20934     sqlite3_mutex_leave(mem0.mutex);
20935   }else{
20936     sqlite3GlobalConfig.m.xFree(p);
20937   }
20938 }
20939
20940 /*
20941 ** Add the size of memory allocation "p" to the count in
20942 ** *db->pnBytesFreed.
20943 */
20944 static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
20945   *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
20946 }
20947
20948 /*
20949 ** Free memory that might be associated with a particular database
20950 ** connection.
20951 */
20952 SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
20953   assert( db==0 || sqlite3_mutex_held(db->mutex) );
20954   if( p==0 ) return;
20955   if( db ){
20956     if( db->pnBytesFreed ){
20957       measureAllocationSize(db, p);
20958       return;
20959     }
20960     if( isLookaside(db, p) ){
20961       LookasideSlot *pBuf = (LookasideSlot*)p;
20962 #if SQLITE_DEBUG
20963       /* Trash all content in the buffer being freed */
20964       memset(p, 0xaa, db->lookaside.sz);
20965 #endif
20966       pBuf->pNext = db->lookaside.pFree;
20967       db->lookaside.pFree = pBuf;
20968       db->lookaside.nOut--;
20969       return;
20970     }
20971   }
20972   assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
20973   assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
20974   assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
20975   sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
20976   sqlite3_free(p);
20977 }
20978
20979 /*
20980 ** Change the size of an existing memory allocation
20981 */
20982 SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
20983   int nOld, nNew, nDiff;
20984   void *pNew;
20985   assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
20986   assert( sqlite3MemdebugNoType(pOld, (u8)~MEMTYPE_HEAP) );
20987   if( pOld==0 ){
20988     return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
20989   }
20990   if( nBytes==0 ){
20991     sqlite3_free(pOld); /* IMP: R-26507-47431 */
20992     return 0;
20993   }
20994   if( nBytes>=0x7fffff00 ){
20995     /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
20996     return 0;
20997   }
20998   nOld = sqlite3MallocSize(pOld);
20999   /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
21000   ** argument to xRealloc is always a value returned by a prior call to
21001   ** xRoundup. */
21002   nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
21003   if( nOld==nNew ){
21004     pNew = pOld;
21005   }else if( sqlite3GlobalConfig.bMemstat ){
21006     sqlite3_mutex_enter(mem0.mutex);
21007     sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
21008     nDiff = nNew - nOld;
21009     if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >= 
21010           mem0.alarmThreshold-nDiff ){
21011       sqlite3MallocAlarm(nDiff);
21012     }
21013     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
21014     if( pNew==0 && mem0.alarmCallback ){
21015       sqlite3MallocAlarm((int)nBytes);
21016       pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
21017     }
21018     if( pNew ){
21019       nNew = sqlite3MallocSize(pNew);
21020       sqlite3StatusUp(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
21021     }
21022     sqlite3_mutex_leave(mem0.mutex);
21023   }else{
21024     pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
21025   }
21026   assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
21027   return pNew;
21028 }
21029
21030 /*
21031 ** The public interface to sqlite3Realloc.  Make sure that the memory
21032 ** subsystem is initialized prior to invoking sqliteRealloc.
21033 */
21034 SQLITE_API void *SQLITE_STDCALL sqlite3_realloc(void *pOld, int n){
21035 #ifndef SQLITE_OMIT_AUTOINIT
21036   if( sqlite3_initialize() ) return 0;
21037 #endif
21038   if( n<0 ) n = 0;  /* IMP: R-26507-47431 */
21039   return sqlite3Realloc(pOld, n);
21040 }
21041 SQLITE_API void *SQLITE_STDCALL sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
21042 #ifndef SQLITE_OMIT_AUTOINIT
21043   if( sqlite3_initialize() ) return 0;
21044 #endif
21045   return sqlite3Realloc(pOld, n);
21046 }
21047
21048
21049 /*
21050 ** Allocate and zero memory.
21051 */ 
21052 SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
21053   void *p = sqlite3Malloc(n);
21054   if( p ){
21055     memset(p, 0, (size_t)n);
21056   }
21057   return p;
21058 }
21059
21060 /*
21061 ** Allocate and zero memory.  If the allocation fails, make
21062 ** the mallocFailed flag in the connection pointer.
21063 */
21064 SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
21065   void *p = sqlite3DbMallocRaw(db, n);
21066   if( p ){
21067     memset(p, 0, (size_t)n);
21068   }
21069   return p;
21070 }
21071
21072 /*
21073 ** Allocate and zero memory.  If the allocation fails, make
21074 ** the mallocFailed flag in the connection pointer.
21075 **
21076 ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
21077 ** failure on the same database connection) then always return 0.
21078 ** Hence for a particular database connection, once malloc starts
21079 ** failing, it fails consistently until mallocFailed is reset.
21080 ** This is an important assumption.  There are many places in the
21081 ** code that do things like this:
21082 **
21083 **         int *a = (int*)sqlite3DbMallocRaw(db, 100);
21084 **         int *b = (int*)sqlite3DbMallocRaw(db, 200);
21085 **         if( b ) a[10] = 9;
21086 **
21087 ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
21088 ** that all prior mallocs (ex: "a") worked too.
21089 */
21090 SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
21091   void *p;
21092   assert( db==0 || sqlite3_mutex_held(db->mutex) );
21093   assert( db==0 || db->pnBytesFreed==0 );
21094 #ifndef SQLITE_OMIT_LOOKASIDE
21095   if( db ){
21096     LookasideSlot *pBuf;
21097     if( db->mallocFailed ){
21098       return 0;
21099     }
21100     if( db->lookaside.bEnabled ){
21101       if( n>db->lookaside.sz ){
21102         db->lookaside.anStat[1]++;
21103       }else if( (pBuf = db->lookaside.pFree)==0 ){
21104         db->lookaside.anStat[2]++;
21105       }else{
21106         db->lookaside.pFree = pBuf->pNext;
21107         db->lookaside.nOut++;
21108         db->lookaside.anStat[0]++;
21109         if( db->lookaside.nOut>db->lookaside.mxOut ){
21110           db->lookaside.mxOut = db->lookaside.nOut;
21111         }
21112         return (void*)pBuf;
21113       }
21114     }
21115   }
21116 #else
21117   if( db && db->mallocFailed ){
21118     return 0;
21119   }
21120 #endif
21121   p = sqlite3Malloc(n);
21122   if( !p && db ){
21123     db->mallocFailed = 1;
21124   }
21125   sqlite3MemdebugSetType(p, 
21126          (db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
21127   return p;
21128 }
21129
21130 /*
21131 ** Resize the block of memory pointed to by p to n bytes. If the
21132 ** resize fails, set the mallocFailed flag in the connection object.
21133 */
21134 SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
21135   void *pNew = 0;
21136   assert( db!=0 );
21137   assert( sqlite3_mutex_held(db->mutex) );
21138   if( db->mallocFailed==0 ){
21139     if( p==0 ){
21140       return sqlite3DbMallocRaw(db, n);
21141     }
21142     if( isLookaside(db, p) ){
21143       if( n<=db->lookaside.sz ){
21144         return p;
21145       }
21146       pNew = sqlite3DbMallocRaw(db, n);
21147       if( pNew ){
21148         memcpy(pNew, p, db->lookaside.sz);
21149         sqlite3DbFree(db, p);
21150       }
21151     }else{
21152       assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
21153       assert( sqlite3MemdebugNoType(p, (u8)~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
21154       sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
21155       pNew = sqlite3_realloc64(p, n);
21156       if( !pNew ){
21157         db->mallocFailed = 1;
21158       }
21159       sqlite3MemdebugSetType(pNew,
21160             (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
21161     }
21162   }
21163   return pNew;
21164 }
21165
21166 /*
21167 ** Attempt to reallocate p.  If the reallocation fails, then free p
21168 ** and set the mallocFailed flag in the database connection.
21169 */
21170 SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
21171   void *pNew;
21172   pNew = sqlite3DbRealloc(db, p, n);
21173   if( !pNew ){
21174     sqlite3DbFree(db, p);
21175   }
21176   return pNew;
21177 }
21178
21179 /*
21180 ** Make a copy of a string in memory obtained from sqliteMalloc(). These 
21181 ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
21182 ** is because when memory debugging is turned on, these two functions are 
21183 ** called via macros that record the current file and line number in the
21184 ** ThreadData structure.
21185 */
21186 SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
21187   char *zNew;
21188   size_t n;
21189   if( z==0 ){
21190     return 0;
21191   }
21192   n = sqlite3Strlen30(z) + 1;
21193   assert( (n&0x7fffffff)==n );
21194   zNew = sqlite3DbMallocRaw(db, (int)n);
21195   if( zNew ){
21196     memcpy(zNew, z, n);
21197   }
21198   return zNew;
21199 }
21200 SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
21201   char *zNew;
21202   if( z==0 ){
21203     return 0;
21204   }
21205   assert( (n&0x7fffffff)==n );
21206   zNew = sqlite3DbMallocRaw(db, n+1);
21207   if( zNew ){
21208     memcpy(zNew, z, (size_t)n);
21209     zNew[n] = 0;
21210   }
21211   return zNew;
21212 }
21213
21214 /*
21215 ** Create a string from the zFromat argument and the va_list that follows.
21216 ** Store the string in memory obtained from sqliteMalloc() and make *pz
21217 ** point to that string.
21218 */
21219 SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
21220   va_list ap;
21221   char *z;
21222
21223   va_start(ap, zFormat);
21224   z = sqlite3VMPrintf(db, zFormat, ap);
21225   va_end(ap);
21226   sqlite3DbFree(db, *pz);
21227   *pz = z;
21228 }
21229
21230 /*
21231 ** Take actions at the end of an API call to indicate an OOM error
21232 */
21233 static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
21234   db->mallocFailed = 0;
21235   sqlite3Error(db, SQLITE_NOMEM);
21236   return SQLITE_NOMEM;
21237 }
21238
21239 /*
21240 ** This function must be called before exiting any API function (i.e. 
21241 ** returning control to the user) that has called sqlite3_malloc or
21242 ** sqlite3_realloc.
21243 **
21244 ** The returned value is normally a copy of the second argument to this
21245 ** function. However, if a malloc() failure has occurred since the previous
21246 ** invocation SQLITE_NOMEM is returned instead. 
21247 **
21248 ** If the first argument, db, is not NULL and a malloc() error has occurred,
21249 ** then the connection error-code (the value returned by sqlite3_errcode())
21250 ** is set to SQLITE_NOMEM.
21251 */
21252 SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
21253   /* If the db handle is not NULL, then we must hold the connection handle
21254   ** mutex here. Otherwise the read (and possible write) of db->mallocFailed 
21255   ** is unsafe, as is the call to sqlite3Error().
21256   */
21257   assert( !db || sqlite3_mutex_held(db->mutex) );
21258   if( db==0 ) return rc & 0xff;
21259   if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
21260     return apiOomError(db);
21261   }
21262   return rc & db->errMask;
21263 }
21264
21265 /************** End of malloc.c **********************************************/
21266 /************** Begin file printf.c ******************************************/
21267 /*
21268 ** The "printf" code that follows dates from the 1980's.  It is in
21269 ** the public domain.  The original comments are included here for
21270 ** completeness.  They are very out-of-date but might be useful as
21271 ** an historical reference.  Most of the "enhancements" have been backed
21272 ** out so that the functionality is now the same as standard printf().
21273 **
21274 **************************************************************************
21275 **
21276 ** This file contains code for a set of "printf"-like routines.  These
21277 ** routines format strings much like the printf() from the standard C
21278 ** library, though the implementation here has enhancements to support
21279 ** SQLlite.
21280 */
21281
21282 /*
21283 ** Conversion types fall into various categories as defined by the
21284 ** following enumeration.
21285 */
21286 #define etRADIX       1 /* Integer types.  %d, %x, %o, and so forth */
21287 #define etFLOAT       2 /* Floating point.  %f */
21288 #define etEXP         3 /* Exponentional notation. %e and %E */
21289 #define etGENERIC     4 /* Floating or exponential, depending on exponent. %g */
21290 #define etSIZE        5 /* Return number of characters processed so far. %n */
21291 #define etSTRING      6 /* Strings. %s */
21292 #define etDYNSTRING   7 /* Dynamically allocated strings. %z */
21293 #define etPERCENT     8 /* Percent symbol. %% */
21294 #define etCHARX       9 /* Characters. %c */
21295 /* The rest are extensions, not normally found in printf() */
21296 #define etSQLESCAPE  10 /* Strings with '\'' doubled.  %q */
21297 #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
21298                           NULL pointers replaced by SQL NULL.  %Q */
21299 #define etTOKEN      12 /* a pointer to a Token structure */
21300 #define etSRCLIST    13 /* a pointer to a SrcList */
21301 #define etPOINTER    14 /* The %p conversion */
21302 #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
21303 #define etORDINAL    16 /* %r -> 1st, 2nd, 3rd, 4th, etc.  English only */
21304
21305 #define etINVALID     0 /* Any unrecognized conversion type */
21306
21307
21308 /*
21309 ** An "etByte" is an 8-bit unsigned value.
21310 */
21311 typedef unsigned char etByte;
21312
21313 /*
21314 ** Each builtin conversion character (ex: the 'd' in "%d") is described
21315 ** by an instance of the following structure
21316 */
21317 typedef struct et_info {   /* Information about each format field */
21318   char fmttype;            /* The format field code letter */
21319   etByte base;             /* The base for radix conversion */
21320   etByte flags;            /* One or more of FLAG_ constants below */
21321   etByte type;             /* Conversion paradigm */
21322   etByte charset;          /* Offset into aDigits[] of the digits string */
21323   etByte prefix;           /* Offset into aPrefix[] of the prefix string */
21324 } et_info;
21325
21326 /*
21327 ** Allowed values for et_info.flags
21328 */
21329 #define FLAG_SIGNED  1     /* True if the value to convert is signed */
21330 #define FLAG_INTERN  2     /* True if for internal use only */
21331 #define FLAG_STRING  4     /* Allow infinity precision */
21332
21333
21334 /*
21335 ** The following table is searched linearly, so it is good to put the
21336 ** most frequently used conversion types first.
21337 */
21338 static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
21339 static const char aPrefix[] = "-x0\000X0";
21340 static const et_info fmtinfo[] = {
21341   {  'd', 10, 1, etRADIX,      0,  0 },
21342   {  's',  0, 4, etSTRING,     0,  0 },
21343   {  'g',  0, 1, etGENERIC,    30, 0 },
21344   {  'z',  0, 4, etDYNSTRING,  0,  0 },
21345   {  'q',  0, 4, etSQLESCAPE,  0,  0 },
21346   {  'Q',  0, 4, etSQLESCAPE2, 0,  0 },
21347   {  'w',  0, 4, etSQLESCAPE3, 0,  0 },
21348   {  'c',  0, 0, etCHARX,      0,  0 },
21349   {  'o',  8, 0, etRADIX,      0,  2 },
21350   {  'u', 10, 0, etRADIX,      0,  0 },
21351   {  'x', 16, 0, etRADIX,      16, 1 },
21352   {  'X', 16, 0, etRADIX,      0,  4 },
21353 #ifndef SQLITE_OMIT_FLOATING_POINT
21354   {  'f',  0, 1, etFLOAT,      0,  0 },
21355   {  'e',  0, 1, etEXP,        30, 0 },
21356   {  'E',  0, 1, etEXP,        14, 0 },
21357   {  'G',  0, 1, etGENERIC,    14, 0 },
21358 #endif
21359   {  'i', 10, 1, etRADIX,      0,  0 },
21360   {  'n',  0, 0, etSIZE,       0,  0 },
21361   {  '%',  0, 0, etPERCENT,    0,  0 },
21362   {  'p', 16, 0, etPOINTER,    0,  1 },
21363
21364 /* All the rest have the FLAG_INTERN bit set and are thus for internal
21365 ** use only */
21366   {  'T',  0, 2, etTOKEN,      0,  0 },
21367   {  'S',  0, 2, etSRCLIST,    0,  0 },
21368   {  'r', 10, 3, etORDINAL,    0,  0 },
21369 };
21370
21371 /*
21372 ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
21373 ** conversions will work.
21374 */
21375 #ifndef SQLITE_OMIT_FLOATING_POINT
21376 /*
21377 ** "*val" is a double such that 0.1 <= *val < 10.0
21378 ** Return the ascii code for the leading digit of *val, then
21379 ** multiply "*val" by 10.0 to renormalize.
21380 **
21381 ** Example:
21382 **     input:     *val = 3.14159
21383 **     output:    *val = 1.4159    function return = '3'
21384 **
21385 ** The counter *cnt is incremented each time.  After counter exceeds
21386 ** 16 (the number of significant digits in a 64-bit float) '0' is
21387 ** always returned.
21388 */
21389 static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
21390   int digit;
21391   LONGDOUBLE_TYPE d;
21392   if( (*cnt)<=0 ) return '0';
21393   (*cnt)--;
21394   digit = (int)*val;
21395   d = digit;
21396   digit += '0';
21397   *val = (*val - d)*10.0;
21398   return (char)digit;
21399 }
21400 #endif /* SQLITE_OMIT_FLOATING_POINT */
21401
21402 /*
21403 ** Set the StrAccum object to an error mode.
21404 */
21405 static void setStrAccumError(StrAccum *p, u8 eError){
21406   p->accError = eError;
21407   p->nAlloc = 0;
21408 }
21409
21410 /*
21411 ** Extra argument values from a PrintfArguments object
21412 */
21413 static sqlite3_int64 getIntArg(PrintfArguments *p){
21414   if( p->nArg<=p->nUsed ) return 0;
21415   return sqlite3_value_int64(p->apArg[p->nUsed++]);
21416 }
21417 static double getDoubleArg(PrintfArguments *p){
21418   if( p->nArg<=p->nUsed ) return 0.0;
21419   return sqlite3_value_double(p->apArg[p->nUsed++]);
21420 }
21421 static char *getTextArg(PrintfArguments *p){
21422   if( p->nArg<=p->nUsed ) return 0;
21423   return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
21424 }
21425
21426
21427 /*
21428 ** On machines with a small stack size, you can redefine the
21429 ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
21430 */
21431 #ifndef SQLITE_PRINT_BUF_SIZE
21432 # define SQLITE_PRINT_BUF_SIZE 70
21433 #endif
21434 #define etBUFSIZE SQLITE_PRINT_BUF_SIZE  /* Size of the output buffer */
21435
21436 /*
21437 ** Render a string given by "fmt" into the StrAccum object.
21438 */
21439 SQLITE_PRIVATE void sqlite3VXPrintf(
21440   StrAccum *pAccum,          /* Accumulate results here */
21441   u32 bFlags,                /* SQLITE_PRINTF_* flags */
21442   const char *fmt,           /* Format string */
21443   va_list ap                 /* arguments */
21444 ){
21445   int c;                     /* Next character in the format string */
21446   char *bufpt;               /* Pointer to the conversion buffer */
21447   int precision;             /* Precision of the current field */
21448   int length;                /* Length of the field */
21449   int idx;                   /* A general purpose loop counter */
21450   int width;                 /* Width of the current field */
21451   etByte flag_leftjustify;   /* True if "-" flag is present */
21452   etByte flag_plussign;      /* True if "+" flag is present */
21453   etByte flag_blanksign;     /* True if " " flag is present */
21454   etByte flag_alternateform; /* True if "#" flag is present */
21455   etByte flag_altform2;      /* True if "!" flag is present */
21456   etByte flag_zeropad;       /* True if field width constant starts with zero */
21457   etByte flag_long;          /* True if "l" flag is present */
21458   etByte flag_longlong;      /* True if the "ll" flag is present */
21459   etByte done;               /* Loop termination flag */
21460   etByte xtype = 0;          /* Conversion paradigm */
21461   u8 bArgList;               /* True for SQLITE_PRINTF_SQLFUNC */
21462   u8 useIntern;              /* Ok to use internal conversions (ex: %T) */
21463   char prefix;               /* Prefix character.  "+" or "-" or " " or '\0'. */
21464   sqlite_uint64 longvalue;   /* Value for integer types */
21465   LONGDOUBLE_TYPE realvalue; /* Value for real types */
21466   const et_info *infop;      /* Pointer to the appropriate info structure */
21467   char *zOut;                /* Rendering buffer */
21468   int nOut;                  /* Size of the rendering buffer */
21469   char *zExtra = 0;          /* Malloced memory used by some conversion */
21470 #ifndef SQLITE_OMIT_FLOATING_POINT
21471   int  exp, e2;              /* exponent of real numbers */
21472   int nsd;                   /* Number of significant digits returned */
21473   double rounder;            /* Used for rounding floating point values */
21474   etByte flag_dp;            /* True if decimal point should be shown */
21475   etByte flag_rtz;           /* True if trailing zeros should be removed */
21476 #endif
21477   PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
21478   char buf[etBUFSIZE];       /* Conversion buffer */
21479
21480   bufpt = 0;
21481   if( bFlags ){
21482     if( (bArgList = (bFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
21483       pArgList = va_arg(ap, PrintfArguments*);
21484     }
21485     useIntern = bFlags & SQLITE_PRINTF_INTERNAL;
21486   }else{
21487     bArgList = useIntern = 0;
21488   }
21489   for(; (c=(*fmt))!=0; ++fmt){
21490     if( c!='%' ){
21491       bufpt = (char *)fmt;
21492 #if HAVE_STRCHRNUL
21493       fmt = strchrnul(fmt, '%');
21494 #else
21495       do{ fmt++; }while( *fmt && *fmt != '%' );
21496 #endif
21497       sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
21498       if( *fmt==0 ) break;
21499     }
21500     if( (c=(*++fmt))==0 ){
21501       sqlite3StrAccumAppend(pAccum, "%", 1);
21502       break;
21503     }
21504     /* Find out what flags are present */
21505     flag_leftjustify = flag_plussign = flag_blanksign = 
21506      flag_alternateform = flag_altform2 = flag_zeropad = 0;
21507     done = 0;
21508     do{
21509       switch( c ){
21510         case '-':   flag_leftjustify = 1;     break;
21511         case '+':   flag_plussign = 1;        break;
21512         case ' ':   flag_blanksign = 1;       break;
21513         case '#':   flag_alternateform = 1;   break;
21514         case '!':   flag_altform2 = 1;        break;
21515         case '0':   flag_zeropad = 1;         break;
21516         default:    done = 1;                 break;
21517       }
21518     }while( !done && (c=(*++fmt))!=0 );
21519     /* Get the field width */
21520     width = 0;
21521     if( c=='*' ){
21522       if( bArgList ){
21523         width = (int)getIntArg(pArgList);
21524       }else{
21525         width = va_arg(ap,int);
21526       }
21527       if( width<0 ){
21528         flag_leftjustify = 1;
21529         width = width >= -2147483647 ? -width : 0;
21530       }
21531       c = *++fmt;
21532     }else{
21533       unsigned wx = 0;
21534       while( c>='0' && c<='9' ){
21535         wx = wx*10 + c - '0';
21536         c = *++fmt;
21537       }
21538       testcase( wx>0x7fffffff );
21539       width = wx & 0x7fffffff;
21540     }
21541
21542     /* Get the precision */
21543     if( c=='.' ){
21544       precision = 0;
21545       c = *++fmt;
21546       if( c=='*' ){
21547         if( bArgList ){
21548           precision = (int)getIntArg(pArgList);
21549         }else{
21550           precision = va_arg(ap,int);
21551         }
21552         c = *++fmt;
21553         if( precision<0 ){
21554           precision = precision >= -2147483647 ? -precision : -1;
21555         }
21556       }else{
21557         unsigned px = 0;
21558         while( c>='0' && c<='9' ){
21559           px = px*10 + c - '0';
21560           c = *++fmt;
21561         }
21562         testcase( px>0x7fffffff );
21563         precision = px & 0x7fffffff;
21564       }
21565     }else{
21566       precision = -1;
21567     }
21568     /* Get the conversion type modifier */
21569     if( c=='l' ){
21570       flag_long = 1;
21571       c = *++fmt;
21572       if( c=='l' ){
21573         flag_longlong = 1;
21574         c = *++fmt;
21575       }else{
21576         flag_longlong = 0;
21577       }
21578     }else{
21579       flag_long = flag_longlong = 0;
21580     }
21581     /* Fetch the info entry for the field */
21582     infop = &fmtinfo[0];
21583     xtype = etINVALID;
21584     for(idx=0; idx<ArraySize(fmtinfo); idx++){
21585       if( c==fmtinfo[idx].fmttype ){
21586         infop = &fmtinfo[idx];
21587         if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
21588           xtype = infop->type;
21589         }else{
21590           return;
21591         }
21592         break;
21593       }
21594     }
21595
21596     /*
21597     ** At this point, variables are initialized as follows:
21598     **
21599     **   flag_alternateform          TRUE if a '#' is present.
21600     **   flag_altform2               TRUE if a '!' is present.
21601     **   flag_plussign               TRUE if a '+' is present.
21602     **   flag_leftjustify            TRUE if a '-' is present or if the
21603     **                               field width was negative.
21604     **   flag_zeropad                TRUE if the width began with 0.
21605     **   flag_long                   TRUE if the letter 'l' (ell) prefixed
21606     **                               the conversion character.
21607     **   flag_longlong               TRUE if the letter 'll' (ell ell) prefixed
21608     **                               the conversion character.
21609     **   flag_blanksign              TRUE if a ' ' is present.
21610     **   width                       The specified field width.  This is
21611     **                               always non-negative.  Zero is the default.
21612     **   precision                   The specified precision.  The default
21613     **                               is -1.
21614     **   xtype                       The class of the conversion.
21615     **   infop                       Pointer to the appropriate info struct.
21616     */
21617     switch( xtype ){
21618       case etPOINTER:
21619         flag_longlong = sizeof(char*)==sizeof(i64);
21620         flag_long = sizeof(char*)==sizeof(long int);
21621         /* Fall through into the next case */
21622       case etORDINAL:
21623       case etRADIX:
21624         if( infop->flags & FLAG_SIGNED ){
21625           i64 v;
21626           if( bArgList ){
21627             v = getIntArg(pArgList);
21628           }else if( flag_longlong ){
21629             v = va_arg(ap,i64);
21630           }else if( flag_long ){
21631             v = va_arg(ap,long int);
21632           }else{
21633             v = va_arg(ap,int);
21634           }
21635           if( v<0 ){
21636             if( v==SMALLEST_INT64 ){
21637               longvalue = ((u64)1)<<63;
21638             }else{
21639               longvalue = -v;
21640             }
21641             prefix = '-';
21642           }else{
21643             longvalue = v;
21644             if( flag_plussign )        prefix = '+';
21645             else if( flag_blanksign )  prefix = ' ';
21646             else                       prefix = 0;
21647           }
21648         }else{
21649           if( bArgList ){
21650             longvalue = (u64)getIntArg(pArgList);
21651           }else if( flag_longlong ){
21652             longvalue = va_arg(ap,u64);
21653           }else if( flag_long ){
21654             longvalue = va_arg(ap,unsigned long int);
21655           }else{
21656             longvalue = va_arg(ap,unsigned int);
21657           }
21658           prefix = 0;
21659         }
21660         if( longvalue==0 ) flag_alternateform = 0;
21661         if( flag_zeropad && precision<width-(prefix!=0) ){
21662           precision = width-(prefix!=0);
21663         }
21664         if( precision<etBUFSIZE-10 ){
21665           nOut = etBUFSIZE;
21666           zOut = buf;
21667         }else{
21668           nOut = precision + 10;
21669           zOut = zExtra = sqlite3Malloc( nOut );
21670           if( zOut==0 ){
21671             setStrAccumError(pAccum, STRACCUM_NOMEM);
21672             return;
21673           }
21674         }
21675         bufpt = &zOut[nOut-1];
21676         if( xtype==etORDINAL ){
21677           static const char zOrd[] = "thstndrd";
21678           int x = (int)(longvalue % 10);
21679           if( x>=4 || (longvalue/10)%10==1 ){
21680             x = 0;
21681           }
21682           *(--bufpt) = zOrd[x*2+1];
21683           *(--bufpt) = zOrd[x*2];
21684         }
21685         {
21686           const char *cset = &aDigits[infop->charset];
21687           u8 base = infop->base;
21688           do{                                           /* Convert to ascii */
21689             *(--bufpt) = cset[longvalue%base];
21690             longvalue = longvalue/base;
21691           }while( longvalue>0 );
21692         }
21693         length = (int)(&zOut[nOut-1]-bufpt);
21694         for(idx=precision-length; idx>0; idx--){
21695           *(--bufpt) = '0';                             /* Zero pad */
21696         }
21697         if( prefix ) *(--bufpt) = prefix;               /* Add sign */
21698         if( flag_alternateform && infop->prefix ){      /* Add "0" or "0x" */
21699           const char *pre;
21700           char x;
21701           pre = &aPrefix[infop->prefix];
21702           for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
21703         }
21704         length = (int)(&zOut[nOut-1]-bufpt);
21705         break;
21706       case etFLOAT:
21707       case etEXP:
21708       case etGENERIC:
21709         if( bArgList ){
21710           realvalue = getDoubleArg(pArgList);
21711         }else{
21712           realvalue = va_arg(ap,double);
21713         }
21714 #ifdef SQLITE_OMIT_FLOATING_POINT
21715         length = 0;
21716 #else
21717         if( precision<0 ) precision = 6;         /* Set default precision */
21718         if( realvalue<0.0 ){
21719           realvalue = -realvalue;
21720           prefix = '-';
21721         }else{
21722           if( flag_plussign )          prefix = '+';
21723           else if( flag_blanksign )    prefix = ' ';
21724           else                         prefix = 0;
21725         }
21726         if( xtype==etGENERIC && precision>0 ) precision--;
21727         testcase( precision>0xfff );
21728         for(idx=precision&0xfff, rounder=0.5; idx>0; idx--, rounder*=0.1){}
21729         if( xtype==etFLOAT ) realvalue += rounder;
21730         /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
21731         exp = 0;
21732         if( sqlite3IsNaN((double)realvalue) ){
21733           bufpt = "NaN";
21734           length = 3;
21735           break;
21736         }
21737         if( realvalue>0.0 ){
21738           LONGDOUBLE_TYPE scale = 1.0;
21739           while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
21740           while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
21741           while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
21742           while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
21743           realvalue /= scale;
21744           while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
21745           while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
21746           if( exp>350 ){
21747             if( prefix=='-' ){
21748               bufpt = "-Inf";
21749             }else if( prefix=='+' ){
21750               bufpt = "+Inf";
21751             }else{
21752               bufpt = "Inf";
21753             }
21754             length = sqlite3Strlen30(bufpt);
21755             break;
21756           }
21757         }
21758         bufpt = buf;
21759         /*
21760         ** If the field type is etGENERIC, then convert to either etEXP
21761         ** or etFLOAT, as appropriate.
21762         */
21763         if( xtype!=etFLOAT ){
21764           realvalue += rounder;
21765           if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
21766         }
21767         if( xtype==etGENERIC ){
21768           flag_rtz = !flag_alternateform;
21769           if( exp<-4 || exp>precision ){
21770             xtype = etEXP;
21771           }else{
21772             precision = precision - exp;
21773             xtype = etFLOAT;
21774           }
21775         }else{
21776           flag_rtz = flag_altform2;
21777         }
21778         if( xtype==etEXP ){
21779           e2 = 0;
21780         }else{
21781           e2 = exp;
21782         }
21783         if( MAX(e2,0)+(i64)precision+(i64)width > etBUFSIZE - 15 ){
21784           bufpt = zExtra 
21785               = sqlite3Malloc( MAX(e2,0)+(i64)precision+(i64)width+15 );
21786           if( bufpt==0 ){
21787             setStrAccumError(pAccum, STRACCUM_NOMEM);
21788             return;
21789           }
21790         }
21791         zOut = bufpt;
21792         nsd = 16 + flag_altform2*10;
21793         flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
21794         /* The sign in front of the number */
21795         if( prefix ){
21796           *(bufpt++) = prefix;
21797         }
21798         /* Digits prior to the decimal point */
21799         if( e2<0 ){
21800           *(bufpt++) = '0';
21801         }else{
21802           for(; e2>=0; e2--){
21803             *(bufpt++) = et_getdigit(&realvalue,&nsd);
21804           }
21805         }
21806         /* The decimal point */
21807         if( flag_dp ){
21808           *(bufpt++) = '.';
21809         }
21810         /* "0" digits after the decimal point but before the first
21811         ** significant digit of the number */
21812         for(e2++; e2<0; precision--, e2++){
21813           assert( precision>0 );
21814           *(bufpt++) = '0';
21815         }
21816         /* Significant digits after the decimal point */
21817         while( (precision--)>0 ){
21818           *(bufpt++) = et_getdigit(&realvalue,&nsd);
21819         }
21820         /* Remove trailing zeros and the "." if no digits follow the "." */
21821         if( flag_rtz && flag_dp ){
21822           while( bufpt[-1]=='0' ) *(--bufpt) = 0;
21823           assert( bufpt>zOut );
21824           if( bufpt[-1]=='.' ){
21825             if( flag_altform2 ){
21826               *(bufpt++) = '0';
21827             }else{
21828               *(--bufpt) = 0;
21829             }
21830           }
21831         }
21832         /* Add the "eNNN" suffix */
21833         if( xtype==etEXP ){
21834           *(bufpt++) = aDigits[infop->charset];
21835           if( exp<0 ){
21836             *(bufpt++) = '-'; exp = -exp;
21837           }else{
21838             *(bufpt++) = '+';
21839           }
21840           if( exp>=100 ){
21841             *(bufpt++) = (char)((exp/100)+'0');        /* 100's digit */
21842             exp %= 100;
21843           }
21844           *(bufpt++) = (char)(exp/10+'0');             /* 10's digit */
21845           *(bufpt++) = (char)(exp%10+'0');             /* 1's digit */
21846         }
21847         *bufpt = 0;
21848
21849         /* The converted number is in buf[] and zero terminated. Output it.
21850         ** Note that the number is in the usual order, not reversed as with
21851         ** integer conversions. */
21852         length = (int)(bufpt-zOut);
21853         bufpt = zOut;
21854
21855         /* Special case:  Add leading zeros if the flag_zeropad flag is
21856         ** set and we are not left justified */
21857         if( flag_zeropad && !flag_leftjustify && length < width){
21858           int i;
21859           int nPad = width - length;
21860           for(i=width; i>=nPad; i--){
21861             bufpt[i] = bufpt[i-nPad];
21862           }
21863           i = prefix!=0;
21864           while( nPad-- ) bufpt[i++] = '0';
21865           length = width;
21866         }
21867 #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
21868         break;
21869       case etSIZE:
21870         if( !bArgList ){
21871           *(va_arg(ap,int*)) = pAccum->nChar;
21872         }
21873         length = width = 0;
21874         break;
21875       case etPERCENT:
21876         buf[0] = '%';
21877         bufpt = buf;
21878         length = 1;
21879         break;
21880       case etCHARX:
21881         if( bArgList ){
21882           bufpt = getTextArg(pArgList);
21883           c = bufpt ? bufpt[0] : 0;
21884         }else{
21885           c = va_arg(ap,int);
21886         }
21887         if( precision>1 ){
21888           width -= precision-1;
21889           if( width>1 && !flag_leftjustify ){
21890             sqlite3AppendChar(pAccum, width-1, ' ');
21891             width = 0;
21892           }
21893           sqlite3AppendChar(pAccum, precision-1, c);
21894         }
21895         length = 1;
21896         buf[0] = c;
21897         bufpt = buf;
21898         break;
21899       case etSTRING:
21900       case etDYNSTRING:
21901         if( bArgList ){
21902           bufpt = getTextArg(pArgList);
21903         }else{
21904           bufpt = va_arg(ap,char*);
21905         }
21906         if( bufpt==0 ){
21907           bufpt = "";
21908         }else if( xtype==etDYNSTRING && !bArgList ){
21909           zExtra = bufpt;
21910         }
21911         if( precision>=0 ){
21912           for(length=0; length<precision && bufpt[length]; length++){}
21913         }else{
21914           length = sqlite3Strlen30(bufpt);
21915         }
21916         break;
21917       case etSQLESCAPE:
21918       case etSQLESCAPE2:
21919       case etSQLESCAPE3: {
21920         int i, j, k, n, isnull;
21921         int needQuote;
21922         char ch;
21923         char q = ((xtype==etSQLESCAPE3)?'"':'\'');   /* Quote character */
21924         char *escarg;
21925
21926         if( bArgList ){
21927           escarg = getTextArg(pArgList);
21928         }else{
21929           escarg = va_arg(ap,char*);
21930         }
21931         isnull = escarg==0;
21932         if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
21933         k = precision;
21934         for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
21935           if( ch==q )  n++;
21936         }
21937         needQuote = !isnull && xtype==etSQLESCAPE2;
21938         n += i + 1 + needQuote*2;
21939         if( n>etBUFSIZE ){
21940           bufpt = zExtra = sqlite3Malloc( n );
21941           if( bufpt==0 ){
21942             setStrAccumError(pAccum, STRACCUM_NOMEM);
21943             return;
21944           }
21945         }else{
21946           bufpt = buf;
21947         }
21948         j = 0;
21949         if( needQuote ) bufpt[j++] = q;
21950         k = i;
21951         for(i=0; i<k; i++){
21952           bufpt[j++] = ch = escarg[i];
21953           if( ch==q ) bufpt[j++] = ch;
21954         }
21955         if( needQuote ) bufpt[j++] = q;
21956         bufpt[j] = 0;
21957         length = j;
21958         /* The precision in %q and %Q means how many input characters to
21959         ** consume, not the length of the output...
21960         ** if( precision>=0 && precision<length ) length = precision; */
21961         break;
21962       }
21963       case etTOKEN: {
21964         Token *pToken = va_arg(ap, Token*);
21965         assert( bArgList==0 );
21966         if( pToken && pToken->n ){
21967           sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
21968         }
21969         length = width = 0;
21970         break;
21971       }
21972       case etSRCLIST: {
21973         SrcList *pSrc = va_arg(ap, SrcList*);
21974         int k = va_arg(ap, int);
21975         struct SrcList_item *pItem = &pSrc->a[k];
21976         assert( bArgList==0 );
21977         assert( k>=0 && k<pSrc->nSrc );
21978         if( pItem->zDatabase ){
21979           sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
21980           sqlite3StrAccumAppend(pAccum, ".", 1);
21981         }
21982         sqlite3StrAccumAppendAll(pAccum, pItem->zName);
21983         length = width = 0;
21984         break;
21985       }
21986       default: {
21987         assert( xtype==etINVALID );
21988         return;
21989       }
21990     }/* End switch over the format type */
21991     /*
21992     ** The text of the conversion is pointed to by "bufpt" and is
21993     ** "length" characters long.  The field width is "width".  Do
21994     ** the output.
21995     */
21996     width -= length;
21997     if( width>0 && !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
21998     sqlite3StrAccumAppend(pAccum, bufpt, length);
21999     if( width>0 && flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
22000
22001     if( zExtra ){
22002       sqlite3_free(zExtra);
22003       zExtra = 0;
22004     }
22005   }/* End for loop over the format string */
22006 } /* End of function */
22007
22008 /*
22009 ** Enlarge the memory allocation on a StrAccum object so that it is
22010 ** able to accept at least N more bytes of text.
22011 **
22012 ** Return the number of bytes of text that StrAccum is able to accept
22013 ** after the attempted enlargement.  The value returned might be zero.
22014 */
22015 static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
22016   char *zNew;
22017   assert( p->nChar+(i64)N >= p->nAlloc ); /* Only called if really needed */
22018   if( p->accError ){
22019     testcase(p->accError==STRACCUM_TOOBIG);
22020     testcase(p->accError==STRACCUM_NOMEM);
22021     return 0;
22022   }
22023   if( !p->useMalloc ){
22024     N = p->nAlloc - p->nChar - 1;
22025     setStrAccumError(p, STRACCUM_TOOBIG);
22026     return N;
22027   }else{
22028     char *zOld = (p->zText==p->zBase ? 0 : p->zText);
22029     i64 szNew = p->nChar;
22030     szNew += N + 1;
22031     if( szNew+p->nChar<=p->mxAlloc ){
22032       /* Force exponential buffer size growth as long as it does not overflow,
22033       ** to avoid having to call this routine too often */
22034       szNew += p->nChar;
22035     }
22036     if( szNew > p->mxAlloc ){
22037       sqlite3StrAccumReset(p);
22038       setStrAccumError(p, STRACCUM_TOOBIG);
22039       return 0;
22040     }else{
22041       p->nAlloc = (int)szNew;
22042     }
22043     if( p->useMalloc==1 ){
22044       zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
22045     }else{
22046       zNew = sqlite3_realloc(zOld, p->nAlloc);
22047     }
22048     if( zNew ){
22049       assert( p->zText!=0 || p->nChar==0 );
22050       if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
22051       p->zText = zNew;
22052       p->nAlloc = sqlite3DbMallocSize(p->db, zNew);
22053     }else{
22054       sqlite3StrAccumReset(p);
22055       setStrAccumError(p, STRACCUM_NOMEM);
22056       return 0;
22057     }
22058   }
22059   return N;
22060 }
22061
22062 /*
22063 ** Append N copies of character c to the given string buffer.
22064 */
22065 SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
22066   testcase( p->nChar + (i64)N > 0x7fffffff );
22067   if( p->nChar+(i64)N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ){
22068     return;
22069   }
22070   while( (N--)>0 ) p->zText[p->nChar++] = c;
22071 }
22072
22073 /*
22074 ** The StrAccum "p" is not large enough to accept N new bytes of z[].
22075 ** So enlarge if first, then do the append.
22076 **
22077 ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
22078 ** work (enlarging the buffer) using tail recursion, so that the
22079 ** sqlite3StrAccumAppend() routine can use fast calling semantics.
22080 */
22081 static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
22082   N = sqlite3StrAccumEnlarge(p, N);
22083   if( N>0 ){
22084     memcpy(&p->zText[p->nChar], z, N);
22085     p->nChar += N;
22086   }
22087 }
22088
22089 /*
22090 ** Append N bytes of text from z to the StrAccum object.  Increase the
22091 ** size of the memory allocation for StrAccum if necessary.
22092 */
22093 SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
22094   assert( z!=0 );
22095   assert( p->zText!=0 || p->nChar==0 || p->accError );
22096   assert( N>=0 );
22097   assert( p->accError==0 || p->nAlloc==0 );
22098   if( p->nChar+N >= p->nAlloc ){
22099     enlargeAndAppend(p,z,N);
22100   }else{
22101     assert( p->zText );
22102     p->nChar += N;
22103     memcpy(&p->zText[p->nChar-N], z, N);
22104   }
22105 }
22106
22107 /*
22108 ** Append the complete text of zero-terminated string z[] to the p string.
22109 */
22110 SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
22111   sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
22112 }
22113
22114
22115 /*
22116 ** Finish off a string by making sure it is zero-terminated.
22117 ** Return a pointer to the resulting string.  Return a NULL
22118 ** pointer if any kind of error was encountered.
22119 */
22120 SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
22121   if( p->zText ){
22122     p->zText[p->nChar] = 0;
22123     if( p->useMalloc && p->zText==p->zBase ){
22124       if( p->useMalloc==1 ){
22125         p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
22126       }else{
22127         p->zText = sqlite3_malloc(p->nChar+1);
22128       }
22129       if( p->zText ){
22130         memcpy(p->zText, p->zBase, p->nChar+1);
22131       }else{
22132         setStrAccumError(p, STRACCUM_NOMEM);
22133       }
22134     }
22135   }
22136   return p->zText;
22137 }
22138
22139 /*
22140 ** Reset an StrAccum string.  Reclaim all malloced memory.
22141 */
22142 SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
22143   if( p->zText!=p->zBase ){
22144     if( p->useMalloc==1 ){
22145       sqlite3DbFree(p->db, p->zText);
22146     }else{
22147       sqlite3_free(p->zText);
22148     }
22149   }
22150   p->zText = 0;
22151 }
22152
22153 /*
22154 ** Initialize a string accumulator
22155 */
22156 SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
22157   p->zText = p->zBase = zBase;
22158   p->db = 0;
22159   p->nChar = 0;
22160   p->nAlloc = n;
22161   p->mxAlloc = mx;
22162   p->useMalloc = 1;
22163   p->accError = 0;
22164 }
22165
22166 /*
22167 ** Print into memory obtained from sqliteMalloc().  Use the internal
22168 ** %-conversion extensions.
22169 */
22170 SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
22171   char *z;
22172   char zBase[SQLITE_PRINT_BUF_SIZE];
22173   StrAccum acc;
22174   assert( db!=0 );
22175   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
22176                       db->aLimit[SQLITE_LIMIT_LENGTH]);
22177   acc.db = db;
22178   sqlite3VXPrintf(&acc, SQLITE_PRINTF_INTERNAL, zFormat, ap);
22179   z = sqlite3StrAccumFinish(&acc);
22180   if( acc.accError==STRACCUM_NOMEM ){
22181     db->mallocFailed = 1;
22182   }
22183   return z;
22184 }
22185
22186 /*
22187 ** Print into memory obtained from sqliteMalloc().  Use the internal
22188 ** %-conversion extensions.
22189 */
22190 SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
22191   va_list ap;
22192   char *z;
22193   va_start(ap, zFormat);
22194   z = sqlite3VMPrintf(db, zFormat, ap);
22195   va_end(ap);
22196   return z;
22197 }
22198
22199 /*
22200 ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
22201 ** the string and before returning.  This routine is intended to be used
22202 ** to modify an existing string.  For example:
22203 **
22204 **       x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
22205 **
22206 */
22207 SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
22208   va_list ap;
22209   char *z;
22210   va_start(ap, zFormat);
22211   z = sqlite3VMPrintf(db, zFormat, ap);
22212   va_end(ap);
22213   sqlite3DbFree(db, zStr);
22214   return z;
22215 }
22216
22217 /*
22218 ** Print into memory obtained from sqlite3_malloc().  Omit the internal
22219 ** %-conversion extensions.
22220 */
22221 SQLITE_API char *SQLITE_STDCALL sqlite3_vmprintf(const char *zFormat, va_list ap){
22222   char *z;
22223   char zBase[SQLITE_PRINT_BUF_SIZE];
22224   StrAccum acc;
22225
22226 #ifdef SQLITE_ENABLE_API_ARMOR  
22227   if( zFormat==0 ){
22228     (void)SQLITE_MISUSE_BKPT;
22229     return 0;
22230   }
22231 #endif
22232 #ifndef SQLITE_OMIT_AUTOINIT
22233   if( sqlite3_initialize() ) return 0;
22234 #endif
22235   sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
22236   acc.useMalloc = 2;
22237   sqlite3VXPrintf(&acc, 0, zFormat, ap);
22238   z = sqlite3StrAccumFinish(&acc);
22239   return z;
22240 }
22241
22242 /*
22243 ** Print into memory obtained from sqlite3_malloc()().  Omit the internal
22244 ** %-conversion extensions.
22245 */
22246 SQLITE_API char *SQLITE_CDECL sqlite3_mprintf(const char *zFormat, ...){
22247   va_list ap;
22248   char *z;
22249 #ifndef SQLITE_OMIT_AUTOINIT
22250   if( sqlite3_initialize() ) return 0;
22251 #endif
22252   va_start(ap, zFormat);
22253   z = sqlite3_vmprintf(zFormat, ap);
22254   va_end(ap);
22255   return z;
22256 }
22257
22258 /*
22259 ** sqlite3_snprintf() works like snprintf() except that it ignores the
22260 ** current locale settings.  This is important for SQLite because we
22261 ** are not able to use a "," as the decimal point in place of "." as
22262 ** specified by some locales.
22263 **
22264 ** Oops:  The first two arguments of sqlite3_snprintf() are backwards
22265 ** from the snprintf() standard.  Unfortunately, it is too late to change
22266 ** this without breaking compatibility, so we just have to live with the
22267 ** mistake.
22268 **
22269 ** sqlite3_vsnprintf() is the varargs version.
22270 */
22271 SQLITE_API char *SQLITE_STDCALL sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
22272   StrAccum acc;
22273   if( n<=0 ) return zBuf;
22274 #ifdef SQLITE_ENABLE_API_ARMOR
22275   if( zBuf==0 || zFormat==0 ) {
22276     (void)SQLITE_MISUSE_BKPT;
22277     if( zBuf ) zBuf[0] = 0;
22278     return zBuf;
22279   }
22280 #endif
22281   sqlite3StrAccumInit(&acc, zBuf, n, 0);
22282   acc.useMalloc = 0;
22283   sqlite3VXPrintf(&acc, 0, zFormat, ap);
22284   return sqlite3StrAccumFinish(&acc);
22285 }
22286 SQLITE_API char *SQLITE_CDECL sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
22287   char *z;
22288   va_list ap;
22289   va_start(ap,zFormat);
22290   z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
22291   va_end(ap);
22292   return z;
22293 }
22294
22295 /*
22296 ** This is the routine that actually formats the sqlite3_log() message.
22297 ** We house it in a separate routine from sqlite3_log() to avoid using
22298 ** stack space on small-stack systems when logging is disabled.
22299 **
22300 ** sqlite3_log() must render into a static buffer.  It cannot dynamically
22301 ** allocate memory because it might be called while the memory allocator
22302 ** mutex is held.
22303 */
22304 static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
22305   StrAccum acc;                          /* String accumulator */
22306   char zMsg[SQLITE_PRINT_BUF_SIZE*3];    /* Complete log message */
22307
22308   sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
22309   acc.useMalloc = 0;
22310   sqlite3VXPrintf(&acc, 0, zFormat, ap);
22311   sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
22312                            sqlite3StrAccumFinish(&acc));
22313 }
22314
22315 /*
22316 ** Format and write a message to the log if logging is enabled.
22317 */
22318 SQLITE_API void SQLITE_CDECL sqlite3_log(int iErrCode, const char *zFormat, ...){
22319   va_list ap;                             /* Vararg list */
22320   if( sqlite3GlobalConfig.xLog ){
22321     va_start(ap, zFormat);
22322     renderLogMsg(iErrCode, zFormat, ap);
22323     va_end(ap);
22324   }
22325 }
22326
22327 #if defined(SQLITE_DEBUG)
22328 /*
22329 ** A version of printf() that understands %lld.  Used for debugging.
22330 ** The printf() built into some versions of windows does not understand %lld
22331 ** and segfaults if you give it a long long int.
22332 */
22333 SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
22334   va_list ap;
22335   StrAccum acc;
22336   char zBuf[500];
22337   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
22338   acc.useMalloc = 0;
22339   va_start(ap,zFormat);
22340   sqlite3VXPrintf(&acc, 0, zFormat, ap);
22341   va_end(ap);
22342   sqlite3StrAccumFinish(&acc);
22343   fprintf(stdout,"%s", zBuf);
22344   fflush(stdout);
22345 }
22346 #endif
22347
22348 #ifdef SQLITE_DEBUG
22349 /*************************************************************************
22350 ** Routines for implementing the "TreeView" display of hierarchical
22351 ** data structures for debugging.
22352 **
22353 ** The main entry points (coded elsewhere) are:
22354 **     sqlite3TreeViewExpr(0, pExpr, 0);
22355 **     sqlite3TreeViewExprList(0, pList, 0, 0);
22356 **     sqlite3TreeViewSelect(0, pSelect, 0);
22357 ** Insert calls to those routines while debugging in order to display
22358 ** a diagram of Expr, ExprList, and Select objects.
22359 **
22360 */
22361 /* Add a new subitem to the tree.  The moreToFollow flag indicates that this
22362 ** is not the last item in the tree. */
22363 SQLITE_PRIVATE TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
22364   if( p==0 ){
22365     p = sqlite3_malloc( sizeof(*p) );
22366     if( p==0 ) return 0;
22367     memset(p, 0, sizeof(*p));
22368   }else{
22369     p->iLevel++;
22370   }
22371   assert( moreToFollow==0 || moreToFollow==1 );
22372   if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
22373   return p;
22374 }
22375 /* Finished with one layer of the tree */
22376 SQLITE_PRIVATE void sqlite3TreeViewPop(TreeView *p){
22377   if( p==0 ) return;
22378   p->iLevel--;
22379   if( p->iLevel<0 ) sqlite3_free(p);
22380 }
22381 /* Generate a single line of output for the tree, with a prefix that contains
22382 ** all the appropriate tree lines */
22383 SQLITE_PRIVATE void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
22384   va_list ap;
22385   int i;
22386   StrAccum acc;
22387   char zBuf[500];
22388   sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
22389   acc.useMalloc = 0;
22390   if( p ){
22391     for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
22392       sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|   " : "    ", 4);
22393     }
22394     sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
22395   }
22396   va_start(ap, zFormat);
22397   sqlite3VXPrintf(&acc, 0, zFormat, ap);
22398   va_end(ap);
22399   if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
22400   sqlite3StrAccumFinish(&acc);
22401   fprintf(stdout,"%s", zBuf);
22402   fflush(stdout);
22403 }
22404 /* Shorthand for starting a new tree item that consists of a single label */
22405 SQLITE_PRIVATE void sqlite3TreeViewItem(TreeView *p, const char *zLabel, u8 moreToFollow){
22406   p = sqlite3TreeViewPush(p, moreToFollow);
22407   sqlite3TreeViewLine(p, "%s", zLabel);
22408 }
22409 #endif /* SQLITE_DEBUG */
22410
22411 /*
22412 ** variable-argument wrapper around sqlite3VXPrintf().
22413 */
22414 SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, u32 bFlags, const char *zFormat, ...){
22415   va_list ap;
22416   va_start(ap,zFormat);
22417   sqlite3VXPrintf(p, bFlags, zFormat, ap);
22418   va_end(ap);
22419 }
22420
22421 /************** End of printf.c **********************************************/
22422 /************** Begin file random.c ******************************************/
22423 /*
22424 ** 2001 September 15
22425 **
22426 ** The author disclaims copyright to this source code.  In place of
22427 ** a legal notice, here is a blessing:
22428 **
22429 **    May you do good and not evil.
22430 **    May you find forgiveness for yourself and forgive others.
22431 **    May you share freely, never taking more than you give.
22432 **
22433 *************************************************************************
22434 ** This file contains code to implement a pseudo-random number
22435 ** generator (PRNG) for SQLite.
22436 **
22437 ** Random numbers are used by some of the database backends in order
22438 ** to generate random integer keys for tables or random filenames.
22439 */
22440
22441
22442 /* All threads share a single random number generator.
22443 ** This structure is the current state of the generator.
22444 */
22445 static SQLITE_WSD struct sqlite3PrngType {
22446   unsigned char isInit;          /* True if initialized */
22447   unsigned char i, j;            /* State variables */
22448   unsigned char s[256];          /* State variables */
22449 } sqlite3Prng;
22450
22451 /*
22452 ** Return N random bytes.
22453 */
22454 SQLITE_API void SQLITE_STDCALL sqlite3_randomness(int N, void *pBuf){
22455   unsigned char t;
22456   unsigned char *zBuf = pBuf;
22457
22458   /* The "wsdPrng" macro will resolve to the pseudo-random number generator
22459   ** state vector.  If writable static data is unsupported on the target,
22460   ** we have to locate the state vector at run-time.  In the more common
22461   ** case where writable static data is supported, wsdPrng can refer directly
22462   ** to the "sqlite3Prng" state vector declared above.
22463   */
22464 #ifdef SQLITE_OMIT_WSD
22465   struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
22466 # define wsdPrng p[0]
22467 #else
22468 # define wsdPrng sqlite3Prng
22469 #endif
22470
22471 #if SQLITE_THREADSAFE
22472   sqlite3_mutex *mutex;
22473 #endif
22474
22475 #ifndef SQLITE_OMIT_AUTOINIT
22476   if( sqlite3_initialize() ) return;
22477 #endif
22478
22479 #if SQLITE_THREADSAFE
22480   mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
22481 #endif
22482
22483   sqlite3_mutex_enter(mutex);
22484   if( N<=0 || pBuf==0 ){
22485     wsdPrng.isInit = 0;
22486     sqlite3_mutex_leave(mutex);
22487     return;
22488   }
22489
22490   /* Initialize the state of the random number generator once,
22491   ** the first time this routine is called.  The seed value does
22492   ** not need to contain a lot of randomness since we are not
22493   ** trying to do secure encryption or anything like that...
22494   **
22495   ** Nothing in this file or anywhere else in SQLite does any kind of
22496   ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
22497   ** number generator) not as an encryption device.
22498   */
22499   if( !wsdPrng.isInit ){
22500     int i;
22501     char k[256];
22502     wsdPrng.j = 0;
22503     wsdPrng.i = 0;
22504     sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
22505     for(i=0; i<256; i++){
22506       wsdPrng.s[i] = (u8)i;
22507     }
22508     for(i=0; i<256; i++){
22509       wsdPrng.j += wsdPrng.s[i] + k[i];
22510       t = wsdPrng.s[wsdPrng.j];
22511       wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
22512       wsdPrng.s[i] = t;
22513     }
22514     wsdPrng.isInit = 1;
22515   }
22516
22517   assert( N>0 );
22518   do{
22519     wsdPrng.i++;
22520     t = wsdPrng.s[wsdPrng.i];
22521     wsdPrng.j += t;
22522     wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
22523     wsdPrng.s[wsdPrng.j] = t;
22524     t += wsdPrng.s[wsdPrng.i];
22525     *(zBuf++) = wsdPrng.s[t];
22526   }while( --N );
22527   sqlite3_mutex_leave(mutex);
22528 }
22529
22530 #ifndef SQLITE_OMIT_BUILTIN_TEST
22531 /*
22532 ** For testing purposes, we sometimes want to preserve the state of
22533 ** PRNG and restore the PRNG to its saved state at a later time, or
22534 ** to reset the PRNG to its initial state.  These routines accomplish
22535 ** those tasks.
22536 **
22537 ** The sqlite3_test_control() interface calls these routines to
22538 ** control the PRNG.
22539 */
22540 static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
22541 SQLITE_PRIVATE void sqlite3PrngSaveState(void){
22542   memcpy(
22543     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
22544     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
22545     sizeof(sqlite3Prng)
22546   );
22547 }
22548 SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
22549   memcpy(
22550     &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
22551     &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
22552     sizeof(sqlite3Prng)
22553   );
22554 }
22555 #endif /* SQLITE_OMIT_BUILTIN_TEST */
22556
22557 /************** End of random.c **********************************************/
22558 /************** Begin file threads.c *****************************************/
22559 /*
22560 ** 2012 July 21
22561 **
22562 ** The author disclaims copyright to this source code.  In place of
22563 ** a legal notice, here is a blessing:
22564 **
22565 **    May you do good and not evil.
22566 **    May you find forgiveness for yourself and forgive others.
22567 **    May you share freely, never taking more than you give.
22568 **
22569 ******************************************************************************
22570 **
22571 ** This file presents a simple cross-platform threading interface for
22572 ** use internally by SQLite.
22573 **
22574 ** A "thread" can be created using sqlite3ThreadCreate().  This thread
22575 ** runs independently of its creator until it is joined using
22576 ** sqlite3ThreadJoin(), at which point it terminates.
22577 **
22578 ** Threads do not have to be real.  It could be that the work of the
22579 ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
22580 ** or sqlite3ThreadJoin() call.  This is, in fact, what happens in
22581 ** single threaded systems.  Nothing in SQLite requires multiple threads.
22582 ** This interface exists so that applications that want to take advantage
22583 ** of multiple cores can do so, while also allowing applications to stay
22584 ** single-threaded if desired.
22585 */
22586 #if SQLITE_OS_WIN
22587 #endif
22588
22589 #if SQLITE_MAX_WORKER_THREADS>0
22590
22591 /********************************* Unix Pthreads ****************************/
22592 #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
22593
22594 #define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */
22595 /* #include <pthread.h> */
22596
22597 /* A running thread */
22598 struct SQLiteThread {
22599   pthread_t tid;                 /* Thread ID */
22600   int done;                      /* Set to true when thread finishes */
22601   void *pOut;                    /* Result returned by the thread */
22602   void *(*xTask)(void*);         /* The thread routine */
22603   void *pIn;                     /* Argument to the thread */
22604 };
22605
22606 /* Create a new thread */
22607 SQLITE_PRIVATE int sqlite3ThreadCreate(
22608   SQLiteThread **ppThread,  /* OUT: Write the thread object here */
22609   void *(*xTask)(void*),    /* Routine to run in a separate thread */
22610   void *pIn                 /* Argument passed into xTask() */
22611 ){
22612   SQLiteThread *p;
22613   int rc;
22614
22615   assert( ppThread!=0 );
22616   assert( xTask!=0 );
22617   /* This routine is never used in single-threaded mode */
22618   assert( sqlite3GlobalConfig.bCoreMutex!=0 );
22619
22620   *ppThread = 0;
22621   p = sqlite3Malloc(sizeof(*p));
22622   if( p==0 ) return SQLITE_NOMEM;
22623   memset(p, 0, sizeof(*p));
22624   p->xTask = xTask;
22625   p->pIn = pIn;
22626   if( sqlite3FaultSim(200) ){
22627     rc = 1;
22628   }else{    
22629     rc = pthread_create(&p->tid, 0, xTask, pIn);
22630   }
22631   if( rc ){
22632     p->done = 1;
22633     p->pOut = xTask(pIn);
22634   }
22635   *ppThread = p;
22636   return SQLITE_OK;
22637 }
22638
22639 /* Get the results of the thread */
22640 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
22641   int rc;
22642
22643   assert( ppOut!=0 );
22644   if( NEVER(p==0) ) return SQLITE_NOMEM;
22645   if( p->done ){
22646     *ppOut = p->pOut;
22647     rc = SQLITE_OK;
22648   }else{
22649     rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
22650   }
22651   sqlite3_free(p);
22652   return rc;
22653 }
22654
22655 #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
22656 /******************************** End Unix Pthreads *************************/
22657
22658
22659 /********************************* Win32 Threads ****************************/
22660 #if SQLITE_OS_WIN_THREADS
22661
22662 #define SQLITE_THREADS_IMPLEMENTED 1  /* Prevent the single-thread code below */
22663 #include <process.h>
22664
22665 /* A running thread */
22666 struct SQLiteThread {
22667   void *tid;               /* The thread handle */
22668   unsigned id;             /* The thread identifier */
22669   void *(*xTask)(void*);   /* The routine to run as a thread */
22670   void *pIn;               /* Argument to xTask */
22671   void *pResult;           /* Result of xTask */
22672 };
22673
22674 /* Thread procedure Win32 compatibility shim */
22675 static unsigned __stdcall sqlite3ThreadProc(
22676   void *pArg  /* IN: Pointer to the SQLiteThread structure */
22677 ){
22678   SQLiteThread *p = (SQLiteThread *)pArg;
22679
22680   assert( p!=0 );
22681 #if 0
22682   /*
22683   ** This assert appears to trigger spuriously on certain
22684   ** versions of Windows, possibly due to _beginthreadex()
22685   ** and/or CreateThread() not fully setting their thread
22686   ** ID parameter before starting the thread.
22687   */
22688   assert( p->id==GetCurrentThreadId() );
22689 #endif
22690   assert( p->xTask!=0 );
22691   p->pResult = p->xTask(p->pIn);
22692
22693   _endthreadex(0);
22694   return 0; /* NOT REACHED */
22695 }
22696
22697 /* Create a new thread */
22698 SQLITE_PRIVATE int sqlite3ThreadCreate(
22699   SQLiteThread **ppThread,  /* OUT: Write the thread object here */
22700   void *(*xTask)(void*),    /* Routine to run in a separate thread */
22701   void *pIn                 /* Argument passed into xTask() */
22702 ){
22703   SQLiteThread *p;
22704
22705   assert( ppThread!=0 );
22706   assert( xTask!=0 );
22707   *ppThread = 0;
22708   p = sqlite3Malloc(sizeof(*p));
22709   if( p==0 ) return SQLITE_NOMEM;
22710   if( sqlite3GlobalConfig.bCoreMutex==0 ){
22711     memset(p, 0, sizeof(*p));
22712   }else{
22713     p->xTask = xTask;
22714     p->pIn = pIn;
22715     p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
22716     if( p->tid==0 ){
22717       memset(p, 0, sizeof(*p));
22718     }
22719   }
22720   if( p->xTask==0 ){
22721     p->id = GetCurrentThreadId();
22722     p->pResult = xTask(pIn);
22723   }
22724   *ppThread = p;
22725   return SQLITE_OK;
22726 }
22727
22728 SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
22729
22730 /* Get the results of the thread */
22731 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
22732   DWORD rc;
22733   BOOL bRc;
22734
22735   assert( ppOut!=0 );
22736   if( NEVER(p==0) ) return SQLITE_NOMEM;
22737   if( p->xTask==0 ){
22738     assert( p->id==GetCurrentThreadId() );
22739     rc = WAIT_OBJECT_0;
22740     assert( p->tid==0 );
22741   }else{
22742     assert( p->id!=0 && p->id!=GetCurrentThreadId() );
22743     rc = sqlite3Win32Wait((HANDLE)p->tid);
22744     assert( rc!=WAIT_IO_COMPLETION );
22745     bRc = CloseHandle((HANDLE)p->tid);
22746     assert( bRc );
22747   }
22748   if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
22749   sqlite3_free(p);
22750   return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
22751 }
22752
22753 #endif /* SQLITE_OS_WIN_THREADS */
22754 /******************************** End Win32 Threads *************************/
22755
22756
22757 /********************************* Single-Threaded **************************/
22758 #ifndef SQLITE_THREADS_IMPLEMENTED
22759 /*
22760 ** This implementation does not actually create a new thread.  It does the
22761 ** work of the thread in the main thread, when either the thread is created
22762 ** or when it is joined
22763 */
22764
22765 /* A running thread */
22766 struct SQLiteThread {
22767   void *(*xTask)(void*);   /* The routine to run as a thread */
22768   void *pIn;               /* Argument to xTask */
22769   void *pResult;           /* Result of xTask */
22770 };
22771
22772 /* Create a new thread */
22773 SQLITE_PRIVATE int sqlite3ThreadCreate(
22774   SQLiteThread **ppThread,  /* OUT: Write the thread object here */
22775   void *(*xTask)(void*),    /* Routine to run in a separate thread */
22776   void *pIn                 /* Argument passed into xTask() */
22777 ){
22778   SQLiteThread *p;
22779
22780   assert( ppThread!=0 );
22781   assert( xTask!=0 );
22782   *ppThread = 0;
22783   p = sqlite3Malloc(sizeof(*p));
22784   if( p==0 ) return SQLITE_NOMEM;
22785   if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
22786     p->xTask = xTask;
22787     p->pIn = pIn;
22788   }else{
22789     p->xTask = 0;
22790     p->pResult = xTask(pIn);
22791   }
22792   *ppThread = p;
22793   return SQLITE_OK;
22794 }
22795
22796 /* Get the results of the thread */
22797 SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
22798
22799   assert( ppOut!=0 );
22800   if( NEVER(p==0) ) return SQLITE_NOMEM;
22801   if( p->xTask ){
22802     *ppOut = p->xTask(p->pIn);
22803   }else{
22804     *ppOut = p->pResult;
22805   }
22806   sqlite3_free(p);
22807
22808 #if defined(SQLITE_TEST)
22809   {
22810     void *pTstAlloc = sqlite3Malloc(10);
22811     if (!pTstAlloc) return SQLITE_NOMEM;
22812     sqlite3_free(pTstAlloc);
22813   }
22814 #endif
22815
22816   return SQLITE_OK;
22817 }
22818
22819 #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
22820 /****************************** End Single-Threaded *************************/
22821 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
22822
22823 /************** End of threads.c *********************************************/
22824 /************** Begin file utf.c *********************************************/
22825 /*
22826 ** 2004 April 13
22827 **
22828 ** The author disclaims copyright to this source code.  In place of
22829 ** a legal notice, here is a blessing:
22830 **
22831 **    May you do good and not evil.
22832 **    May you find forgiveness for yourself and forgive others.
22833 **    May you share freely, never taking more than you give.
22834 **
22835 *************************************************************************
22836 ** This file contains routines used to translate between UTF-8, 
22837 ** UTF-16, UTF-16BE, and UTF-16LE.
22838 **
22839 ** Notes on UTF-8:
22840 **
22841 **   Byte-0    Byte-1    Byte-2    Byte-3    Value
22842 **  0xxxxxxx                                 00000000 00000000 0xxxxxxx
22843 **  110yyyyy  10xxxxxx                       00000000 00000yyy yyxxxxxx
22844 **  1110zzzz  10yyyyyy  10xxxxxx             00000000 zzzzyyyy yyxxxxxx
22845 **  11110uuu  10uuzzzz  10yyyyyy  10xxxxxx   000uuuuu zzzzyyyy yyxxxxxx
22846 **
22847 **
22848 ** Notes on UTF-16:  (with wwww+1==uuuuu)
22849 **
22850 **      Word-0               Word-1          Value
22851 **  110110ww wwzzzzyy   110111yy yyxxxxxx    000uuuuu zzzzyyyy yyxxxxxx
22852 **  zzzzyyyy yyxxxxxx                        00000000 zzzzyyyy yyxxxxxx
22853 **
22854 **
22855 ** BOM or Byte Order Mark:
22856 **     0xff 0xfe   little-endian utf-16 follows
22857 **     0xfe 0xff   big-endian utf-16 follows
22858 **
22859 */
22860 /* #include <assert.h> */
22861
22862 #ifndef SQLITE_AMALGAMATION
22863 /*
22864 ** The following constant value is used by the SQLITE_BIGENDIAN and
22865 ** SQLITE_LITTLEENDIAN macros.
22866 */
22867 SQLITE_PRIVATE const int sqlite3one = 1;
22868 #endif /* SQLITE_AMALGAMATION */
22869
22870 /*
22871 ** This lookup table is used to help decode the first byte of
22872 ** a multi-byte UTF8 character.
22873 */
22874 static const unsigned char sqlite3Utf8Trans1[] = {
22875   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
22876   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
22877   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
22878   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
22879   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
22880   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
22881   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
22882   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
22883 };
22884
22885
22886 #define WRITE_UTF8(zOut, c) {                          \
22887   if( c<0x00080 ){                                     \
22888     *zOut++ = (u8)(c&0xFF);                            \
22889   }                                                    \
22890   else if( c<0x00800 ){                                \
22891     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
22892     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
22893   }                                                    \
22894   else if( c<0x10000 ){                                \
22895     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
22896     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
22897     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
22898   }else{                                               \
22899     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
22900     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
22901     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
22902     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
22903   }                                                    \
22904 }
22905
22906 #define WRITE_UTF16LE(zOut, c) {                                    \
22907   if( c<=0xFFFF ){                                                  \
22908     *zOut++ = (u8)(c&0x00FF);                                       \
22909     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
22910   }else{                                                            \
22911     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
22912     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
22913     *zOut++ = (u8)(c&0x00FF);                                       \
22914     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
22915   }                                                                 \
22916 }
22917
22918 #define WRITE_UTF16BE(zOut, c) {                                    \
22919   if( c<=0xFFFF ){                                                  \
22920     *zOut++ = (u8)((c>>8)&0x00FF);                                  \
22921     *zOut++ = (u8)(c&0x00FF);                                       \
22922   }else{                                                            \
22923     *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03));              \
22924     *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0));  \
22925     *zOut++ = (u8)(0x00DC + ((c>>8)&0x03));                         \
22926     *zOut++ = (u8)(c&0x00FF);                                       \
22927   }                                                                 \
22928 }
22929
22930 #define READ_UTF16LE(zIn, TERM, c){                                   \
22931   c = (*zIn++);                                                       \
22932   c += ((*zIn++)<<8);                                                 \
22933   if( c>=0xD800 && c<0xE000 && TERM ){                                \
22934     int c2 = (*zIn++);                                                \
22935     c2 += ((*zIn++)<<8);                                              \
22936     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
22937   }                                                                   \
22938 }
22939
22940 #define READ_UTF16BE(zIn, TERM, c){                                   \
22941   c = ((*zIn++)<<8);                                                  \
22942   c += (*zIn++);                                                      \
22943   if( c>=0xD800 && c<0xE000 && TERM ){                                \
22944     int c2 = ((*zIn++)<<8);                                           \
22945     c2 += (*zIn++);                                                   \
22946     c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10);   \
22947   }                                                                   \
22948 }
22949
22950 /*
22951 ** Translate a single UTF-8 character.  Return the unicode value.
22952 **
22953 ** During translation, assume that the byte that zTerm points
22954 ** is a 0x00.
22955 **
22956 ** Write a pointer to the next unread byte back into *pzNext.
22957 **
22958 ** Notes On Invalid UTF-8:
22959 **
22960 **  *  This routine never allows a 7-bit character (0x00 through 0x7f) to
22961 **     be encoded as a multi-byte character.  Any multi-byte character that
22962 **     attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
22963 **
22964 **  *  This routine never allows a UTF16 surrogate value to be encoded.
22965 **     If a multi-byte character attempts to encode a value between
22966 **     0xd800 and 0xe000 then it is rendered as 0xfffd.
22967 **
22968 **  *  Bytes in the range of 0x80 through 0xbf which occur as the first
22969 **     byte of a character are interpreted as single-byte characters
22970 **     and rendered as themselves even though they are technically
22971 **     invalid characters.
22972 **
22973 **  *  This routine accepts over-length UTF8 encodings
22974 **     for unicode values 0x80 and greater.  It does not change over-length
22975 **     encodings to 0xfffd as some systems recommend.
22976 */
22977 #define READ_UTF8(zIn, zTerm, c)                           \
22978   c = *(zIn++);                                            \
22979   if( c>=0xc0 ){                                           \
22980     c = sqlite3Utf8Trans1[c-0xc0];                         \
22981     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
22982       c = (c<<6) + (0x3f & *(zIn++));                      \
22983     }                                                      \
22984     if( c<0x80                                             \
22985         || (c&0xFFFFF800)==0xD800                          \
22986         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
22987   }
22988 SQLITE_PRIVATE u32 sqlite3Utf8Read(
22989   const unsigned char **pz    /* Pointer to string from which to read char */
22990 ){
22991   unsigned int c;
22992
22993   /* Same as READ_UTF8() above but without the zTerm parameter.
22994   ** For this routine, we assume the UTF8 string is always zero-terminated.
22995   */
22996   c = *((*pz)++);
22997   if( c>=0xc0 ){
22998     c = sqlite3Utf8Trans1[c-0xc0];
22999     while( (*(*pz) & 0xc0)==0x80 ){
23000       c = (c<<6) + (0x3f & *((*pz)++));
23001     }
23002     if( c<0x80
23003         || (c&0xFFFFF800)==0xD800
23004         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }
23005   }
23006   return c;
23007 }
23008
23009
23010
23011
23012 /*
23013 ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
23014 ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
23015 */ 
23016 /* #define TRANSLATE_TRACE 1 */
23017
23018 #ifndef SQLITE_OMIT_UTF16
23019 /*
23020 ** This routine transforms the internal text encoding used by pMem to
23021 ** desiredEnc. It is an error if the string is already of the desired
23022 ** encoding, or if *pMem does not contain a string value.
23023 */
23024 SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
23025   int len;                    /* Maximum length of output string in bytes */
23026   unsigned char *zOut;                  /* Output buffer */
23027   unsigned char *zIn;                   /* Input iterator */
23028   unsigned char *zTerm;                 /* End of input */
23029   unsigned char *z;                     /* Output iterator */
23030   unsigned int c;
23031
23032   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
23033   assert( pMem->flags&MEM_Str );
23034   assert( pMem->enc!=desiredEnc );
23035   assert( pMem->enc!=0 );
23036   assert( pMem->n>=0 );
23037
23038 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
23039   {
23040     char zBuf[100];
23041     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
23042     fprintf(stderr, "INPUT:  %s\n", zBuf);
23043   }
23044 #endif
23045
23046   /* If the translation is between UTF-16 little and big endian, then 
23047   ** all that is required is to swap the byte order. This case is handled
23048   ** differently from the others.
23049   */
23050   if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
23051     u8 temp;
23052     int rc;
23053     rc = sqlite3VdbeMemMakeWriteable(pMem);
23054     if( rc!=SQLITE_OK ){
23055       assert( rc==SQLITE_NOMEM );
23056       return SQLITE_NOMEM;
23057     }
23058     zIn = (u8*)pMem->z;
23059     zTerm = &zIn[pMem->n&~1];
23060     while( zIn<zTerm ){
23061       temp = *zIn;
23062       *zIn = *(zIn+1);
23063       zIn++;
23064       *zIn++ = temp;
23065     }
23066     pMem->enc = desiredEnc;
23067     goto translate_out;
23068   }
23069
23070   /* Set len to the maximum number of bytes required in the output buffer. */
23071   if( desiredEnc==SQLITE_UTF8 ){
23072     /* When converting from UTF-16, the maximum growth results from
23073     ** translating a 2-byte character to a 4-byte UTF-8 character.
23074     ** A single byte is required for the output string
23075     ** nul-terminator.
23076     */
23077     pMem->n &= ~1;
23078     len = pMem->n * 2 + 1;
23079   }else{
23080     /* When converting from UTF-8 to UTF-16 the maximum growth is caused
23081     ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
23082     ** character. Two bytes are required in the output buffer for the
23083     ** nul-terminator.
23084     */
23085     len = pMem->n * 2 + 2;
23086   }
23087
23088   /* Set zIn to point at the start of the input buffer and zTerm to point 1
23089   ** byte past the end.
23090   **
23091   ** Variable zOut is set to point at the output buffer, space obtained
23092   ** from sqlite3_malloc().
23093   */
23094   zIn = (u8*)pMem->z;
23095   zTerm = &zIn[pMem->n];
23096   zOut = sqlite3DbMallocRaw(pMem->db, len);
23097   if( !zOut ){
23098     return SQLITE_NOMEM;
23099   }
23100   z = zOut;
23101
23102   if( pMem->enc==SQLITE_UTF8 ){
23103     if( desiredEnc==SQLITE_UTF16LE ){
23104       /* UTF-8 -> UTF-16 Little-endian */
23105       while( zIn<zTerm ){
23106         READ_UTF8(zIn, zTerm, c);
23107         WRITE_UTF16LE(z, c);
23108       }
23109     }else{
23110       assert( desiredEnc==SQLITE_UTF16BE );
23111       /* UTF-8 -> UTF-16 Big-endian */
23112       while( zIn<zTerm ){
23113         READ_UTF8(zIn, zTerm, c);
23114         WRITE_UTF16BE(z, c);
23115       }
23116     }
23117     pMem->n = (int)(z - zOut);
23118     *z++ = 0;
23119   }else{
23120     assert( desiredEnc==SQLITE_UTF8 );
23121     if( pMem->enc==SQLITE_UTF16LE ){
23122       /* UTF-16 Little-endian -> UTF-8 */
23123       while( zIn<zTerm ){
23124         READ_UTF16LE(zIn, zIn<zTerm, c); 
23125         WRITE_UTF8(z, c);
23126       }
23127     }else{
23128       /* UTF-16 Big-endian -> UTF-8 */
23129       while( zIn<zTerm ){
23130         READ_UTF16BE(zIn, zIn<zTerm, c); 
23131         WRITE_UTF8(z, c);
23132       }
23133     }
23134     pMem->n = (int)(z - zOut);
23135   }
23136   *z = 0;
23137   assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
23138
23139   c = pMem->flags;
23140   sqlite3VdbeMemRelease(pMem);
23141   pMem->flags = MEM_Str|MEM_Term|(c&MEM_AffMask);
23142   pMem->enc = desiredEnc;
23143   pMem->z = (char*)zOut;
23144   pMem->zMalloc = pMem->z;
23145   pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
23146
23147 translate_out:
23148 #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
23149   {
23150     char zBuf[100];
23151     sqlite3VdbeMemPrettyPrint(pMem, zBuf);
23152     fprintf(stderr, "OUTPUT: %s\n", zBuf);
23153   }
23154 #endif
23155   return SQLITE_OK;
23156 }
23157
23158 /*
23159 ** This routine checks for a byte-order mark at the beginning of the 
23160 ** UTF-16 string stored in *pMem. If one is present, it is removed and
23161 ** the encoding of the Mem adjusted. This routine does not do any
23162 ** byte-swapping, it just sets Mem.enc appropriately.
23163 **
23164 ** The allocation (static, dynamic etc.) and encoding of the Mem may be
23165 ** changed by this function.
23166 */
23167 SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
23168   int rc = SQLITE_OK;
23169   u8 bom = 0;
23170
23171   assert( pMem->n>=0 );
23172   if( pMem->n>1 ){
23173     u8 b1 = *(u8 *)pMem->z;
23174     u8 b2 = *(((u8 *)pMem->z) + 1);
23175     if( b1==0xFE && b2==0xFF ){
23176       bom = SQLITE_UTF16BE;
23177     }
23178     if( b1==0xFF && b2==0xFE ){
23179       bom = SQLITE_UTF16LE;
23180     }
23181   }
23182   
23183   if( bom ){
23184     rc = sqlite3VdbeMemMakeWriteable(pMem);
23185     if( rc==SQLITE_OK ){
23186       pMem->n -= 2;
23187       memmove(pMem->z, &pMem->z[2], pMem->n);
23188       pMem->z[pMem->n] = '\0';
23189       pMem->z[pMem->n+1] = '\0';
23190       pMem->flags |= MEM_Term;
23191       pMem->enc = bom;
23192     }
23193   }
23194   return rc;
23195 }
23196 #endif /* SQLITE_OMIT_UTF16 */
23197
23198 /*
23199 ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
23200 ** return the number of unicode characters in pZ up to (but not including)
23201 ** the first 0x00 byte. If nByte is not less than zero, return the
23202 ** number of unicode characters in the first nByte of pZ (or up to 
23203 ** the first 0x00, whichever comes first).
23204 */
23205 SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
23206   int r = 0;
23207   const u8 *z = (const u8*)zIn;
23208   const u8 *zTerm;
23209   if( nByte>=0 ){
23210     zTerm = &z[nByte];
23211   }else{
23212     zTerm = (const u8*)(-1);
23213   }
23214   assert( z<=zTerm );
23215   while( *z!=0 && z<zTerm ){
23216     SQLITE_SKIP_UTF8(z);
23217     r++;
23218   }
23219   return r;
23220 }
23221
23222 /* This test function is not currently used by the automated test-suite. 
23223 ** Hence it is only available in debug builds.
23224 */
23225 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
23226 /*
23227 ** Translate UTF-8 to UTF-8.
23228 **
23229 ** This has the effect of making sure that the string is well-formed
23230 ** UTF-8.  Miscoded characters are removed.
23231 **
23232 ** The translation is done in-place and aborted if the output
23233 ** overruns the input.
23234 */
23235 SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
23236   unsigned char *zOut = zIn;
23237   unsigned char *zStart = zIn;
23238   u32 c;
23239
23240   while( zIn[0] && zOut<=zIn ){
23241     c = sqlite3Utf8Read((const u8**)&zIn);
23242     if( c!=0xfffd ){
23243       WRITE_UTF8(zOut, c);
23244     }
23245   }
23246   *zOut = 0;
23247   return (int)(zOut - zStart);
23248 }
23249 #endif
23250
23251 #ifndef SQLITE_OMIT_UTF16
23252 /*
23253 ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
23254 ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
23255 ** be freed by the calling function.
23256 **
23257 ** NULL is returned if there is an allocation error.
23258 */
23259 SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
23260   Mem m;
23261   memset(&m, 0, sizeof(m));
23262   m.db = db;
23263   sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
23264   sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
23265   if( db->mallocFailed ){
23266     sqlite3VdbeMemRelease(&m);
23267     m.z = 0;
23268   }
23269   assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
23270   assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
23271   assert( m.z || db->mallocFailed );
23272   return m.z;
23273 }
23274
23275 /*
23276 ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
23277 ** Return the number of bytes in the first nChar unicode characters
23278 ** in pZ.  nChar must be non-negative.
23279 */
23280 SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
23281   int c;
23282   unsigned char const *z = zIn;
23283   int n = 0;
23284   
23285   if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
23286     while( n<nChar ){
23287       READ_UTF16BE(z, 1, c);
23288       n++;
23289     }
23290   }else{
23291     while( n<nChar ){
23292       READ_UTF16LE(z, 1, c);
23293       n++;
23294     }
23295   }
23296   return (int)(z-(unsigned char const *)zIn);
23297 }
23298
23299 #if defined(SQLITE_TEST)
23300 /*
23301 ** This routine is called from the TCL test function "translate_selftest".
23302 ** It checks that the primitives for serializing and deserializing
23303 ** characters in each encoding are inverses of each other.
23304 */
23305 SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
23306   unsigned int i, t;
23307   unsigned char zBuf[20];
23308   unsigned char *z;
23309   int n;
23310   unsigned int c;
23311
23312   for(i=0; i<0x00110000; i++){
23313     z = zBuf;
23314     WRITE_UTF8(z, i);
23315     n = (int)(z-zBuf);
23316     assert( n>0 && n<=4 );
23317     z[0] = 0;
23318     z = zBuf;
23319     c = sqlite3Utf8Read((const u8**)&z);
23320     t = i;
23321     if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
23322     if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
23323     assert( c==t );
23324     assert( (z-zBuf)==n );
23325   }
23326   for(i=0; i<0x00110000; i++){
23327     if( i>=0xD800 && i<0xE000 ) continue;
23328     z = zBuf;
23329     WRITE_UTF16LE(z, i);
23330     n = (int)(z-zBuf);
23331     assert( n>0 && n<=4 );
23332     z[0] = 0;
23333     z = zBuf;
23334     READ_UTF16LE(z, 1, c);
23335     assert( c==i );
23336     assert( (z-zBuf)==n );
23337   }
23338   for(i=0; i<0x00110000; i++){
23339     if( i>=0xD800 && i<0xE000 ) continue;
23340     z = zBuf;
23341     WRITE_UTF16BE(z, i);
23342     n = (int)(z-zBuf);
23343     assert( n>0 && n<=4 );
23344     z[0] = 0;
23345     z = zBuf;
23346     READ_UTF16BE(z, 1, c);
23347     assert( c==i );
23348     assert( (z-zBuf)==n );
23349   }
23350 }
23351 #endif /* SQLITE_TEST */
23352 #endif /* SQLITE_OMIT_UTF16 */
23353
23354 /************** End of utf.c *************************************************/
23355 /************** Begin file util.c ********************************************/
23356 /*
23357 ** 2001 September 15
23358 **
23359 ** The author disclaims copyright to this source code.  In place of
23360 ** a legal notice, here is a blessing:
23361 **
23362 **    May you do good and not evil.
23363 **    May you find forgiveness for yourself and forgive others.
23364 **    May you share freely, never taking more than you give.
23365 **
23366 *************************************************************************
23367 ** Utility functions used throughout sqlite.
23368 **
23369 ** This file contains functions for allocating memory, comparing
23370 ** strings, and stuff like that.
23371 **
23372 */
23373 /* #include <stdarg.h> */
23374 #if HAVE_ISNAN || SQLITE_HAVE_ISNAN
23375 # include <math.h>
23376 #endif
23377
23378 /*
23379 ** Routine needed to support the testcase() macro.
23380 */
23381 #ifdef SQLITE_COVERAGE_TEST
23382 SQLITE_PRIVATE void sqlite3Coverage(int x){
23383   static unsigned dummy = 0;
23384   dummy += (unsigned)x;
23385 }
23386 #endif
23387
23388 /*
23389 ** Give a callback to the test harness that can be used to simulate faults
23390 ** in places where it is difficult or expensive to do so purely by means
23391 ** of inputs.
23392 **
23393 ** The intent of the integer argument is to let the fault simulator know
23394 ** which of multiple sqlite3FaultSim() calls has been hit.
23395 **
23396 ** Return whatever integer value the test callback returns, or return
23397 ** SQLITE_OK if no test callback is installed.
23398 */
23399 #ifndef SQLITE_OMIT_BUILTIN_TEST
23400 SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
23401   int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
23402   return xCallback ? xCallback(iTest) : SQLITE_OK;
23403 }
23404 #endif
23405
23406 #ifndef SQLITE_OMIT_FLOATING_POINT
23407 /*
23408 ** Return true if the floating point value is Not a Number (NaN).
23409 **
23410 ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
23411 ** Otherwise, we have our own implementation that works on most systems.
23412 */
23413 SQLITE_PRIVATE int sqlite3IsNaN(double x){
23414   int rc;   /* The value return */
23415 #if !SQLITE_HAVE_ISNAN && !HAVE_ISNAN
23416   /*
23417   ** Systems that support the isnan() library function should probably
23418   ** make use of it by compiling with -DSQLITE_HAVE_ISNAN.  But we have
23419   ** found that many systems do not have a working isnan() function so
23420   ** this implementation is provided as an alternative.
23421   **
23422   ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
23423   ** On the other hand, the use of -ffast-math comes with the following
23424   ** warning:
23425   **
23426   **      This option [-ffast-math] should never be turned on by any
23427   **      -O option since it can result in incorrect output for programs
23428   **      which depend on an exact implementation of IEEE or ISO 
23429   **      rules/specifications for math functions.
23430   **
23431   ** Under MSVC, this NaN test may fail if compiled with a floating-
23432   ** point precision mode other than /fp:precise.  From the MSDN 
23433   ** documentation:
23434   **
23435   **      The compiler [with /fp:precise] will properly handle comparisons 
23436   **      involving NaN. For example, x != x evaluates to true if x is NaN 
23437   **      ...
23438   */
23439 #ifdef __FAST_MATH__
23440 # error SQLite will not work correctly with the -ffast-math option of GCC.
23441 #endif
23442   volatile double y = x;
23443   volatile double z = y;
23444   rc = (y!=z);
23445 #else  /* if HAVE_ISNAN */
23446   rc = isnan(x);
23447 #endif /* HAVE_ISNAN */
23448   testcase( rc );
23449   return rc;
23450 }
23451 #endif /* SQLITE_OMIT_FLOATING_POINT */
23452
23453 /*
23454 ** Compute a string length that is limited to what can be stored in
23455 ** lower 30 bits of a 32-bit signed integer.
23456 **
23457 ** The value returned will never be negative.  Nor will it ever be greater
23458 ** than the actual length of the string.  For very long strings (greater
23459 ** than 1GiB) the value returned might be less than the true string length.
23460 */
23461 SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
23462   const char *z2 = z;
23463   if( z==0 ) return 0;
23464   while( *z2 ){ z2++; }
23465   return 0x3fffffff & (int)(z2 - z);
23466 }
23467
23468 /*
23469 ** Set the current error code to err_code and clear any prior error message.
23470 */
23471 SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
23472   assert( db!=0 );
23473   db->errCode = err_code;
23474   if( db->pErr ) sqlite3ValueSetNull(db->pErr);
23475 }
23476
23477 /*
23478 ** Set the most recent error code and error string for the sqlite
23479 ** handle "db". The error code is set to "err_code".
23480 **
23481 ** If it is not NULL, string zFormat specifies the format of the
23482 ** error string in the style of the printf functions: The following
23483 ** format characters are allowed:
23484 **
23485 **      %s      Insert a string
23486 **      %z      A string that should be freed after use
23487 **      %d      Insert an integer
23488 **      %T      Insert a token
23489 **      %S      Insert the first element of a SrcList
23490 **
23491 ** zFormat and any string tokens that follow it are assumed to be
23492 ** encoded in UTF-8.
23493 **
23494 ** To clear the most recent error for sqlite handle "db", sqlite3Error
23495 ** should be called with err_code set to SQLITE_OK and zFormat set
23496 ** to NULL.
23497 */
23498 SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
23499   assert( db!=0 );
23500   db->errCode = err_code;
23501   if( zFormat==0 ){
23502     sqlite3Error(db, err_code);
23503   }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
23504     char *z;
23505     va_list ap;
23506     va_start(ap, zFormat);
23507     z = sqlite3VMPrintf(db, zFormat, ap);
23508     va_end(ap);
23509     sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
23510   }
23511 }
23512
23513 /*
23514 ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
23515 ** The following formatting characters are allowed:
23516 **
23517 **      %s      Insert a string
23518 **      %z      A string that should be freed after use
23519 **      %d      Insert an integer
23520 **      %T      Insert a token
23521 **      %S      Insert the first element of a SrcList
23522 **
23523 ** This function should be used to report any error that occurs while
23524 ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
23525 ** last thing the sqlite3_prepare() function does is copy the error
23526 ** stored by this function into the database handle using sqlite3Error().
23527 ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
23528 ** during statement execution (sqlite3_step() etc.).
23529 */
23530 SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
23531   char *zMsg;
23532   va_list ap;
23533   sqlite3 *db = pParse->db;
23534   va_start(ap, zFormat);
23535   zMsg = sqlite3VMPrintf(db, zFormat, ap);
23536   va_end(ap);
23537   if( db->suppressErr ){
23538     sqlite3DbFree(db, zMsg);
23539   }else{
23540     pParse->nErr++;
23541     sqlite3DbFree(db, pParse->zErrMsg);
23542     pParse->zErrMsg = zMsg;
23543     pParse->rc = SQLITE_ERROR;
23544   }
23545 }
23546
23547 /*
23548 ** Convert an SQL-style quoted string into a normal string by removing
23549 ** the quote characters.  The conversion is done in-place.  If the
23550 ** input does not begin with a quote character, then this routine
23551 ** is a no-op.
23552 **
23553 ** The input string must be zero-terminated.  A new zero-terminator
23554 ** is added to the dequoted string.
23555 **
23556 ** The return value is -1 if no dequoting occurs or the length of the
23557 ** dequoted string, exclusive of the zero terminator, if dequoting does
23558 ** occur.
23559 **
23560 ** 2002-Feb-14: This routine is extended to remove MS-Access style
23561 ** brackets from around identifiers.  For example:  "[a-b-c]" becomes
23562 ** "a-b-c".
23563 */
23564 SQLITE_PRIVATE int sqlite3Dequote(char *z){
23565   char quote;
23566   int i, j;
23567   if( z==0 ) return -1;
23568   quote = z[0];
23569   switch( quote ){
23570     case '\'':  break;
23571     case '"':   break;
23572     case '`':   break;                /* For MySQL compatibility */
23573     case '[':   quote = ']';  break;  /* For MS SqlServer compatibility */
23574     default:    return -1;
23575   }
23576   for(i=1, j=0;; i++){
23577     assert( z[i] );
23578     if( z[i]==quote ){
23579       if( z[i+1]==quote ){
23580         z[j++] = quote;
23581         i++;
23582       }else{
23583         break;
23584       }
23585     }else{
23586       z[j++] = z[i];
23587     }
23588   }
23589   z[j] = 0;
23590   return j;
23591 }
23592
23593 /* Convenient short-hand */
23594 #define UpperToLower sqlite3UpperToLower
23595
23596 /*
23597 ** Some systems have stricmp().  Others have strcasecmp().  Because
23598 ** there is no consistency, we will define our own.
23599 **
23600 ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
23601 ** sqlite3_strnicmp() APIs allow applications and extensions to compare
23602 ** the contents of two buffers containing UTF-8 strings in a
23603 ** case-independent fashion, using the same definition of "case
23604 ** independence" that SQLite uses internally when comparing identifiers.
23605 */
23606 SQLITE_API int SQLITE_STDCALL sqlite3_stricmp(const char *zLeft, const char *zRight){
23607   register unsigned char *a, *b;
23608   if( zLeft==0 ){
23609     return zRight ? -1 : 0;
23610   }else if( zRight==0 ){
23611     return 1;
23612   }
23613   a = (unsigned char *)zLeft;
23614   b = (unsigned char *)zRight;
23615   while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
23616   return UpperToLower[*a] - UpperToLower[*b];
23617 }
23618 SQLITE_API int SQLITE_STDCALL sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
23619   register unsigned char *a, *b;
23620   if( zLeft==0 ){
23621     return zRight ? -1 : 0;
23622   }else if( zRight==0 ){
23623     return 1;
23624   }
23625   a = (unsigned char *)zLeft;
23626   b = (unsigned char *)zRight;
23627   while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
23628   return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
23629 }
23630
23631 /*
23632 ** The string z[] is an text representation of a real number.
23633 ** Convert this string to a double and write it into *pResult.
23634 **
23635 ** The string z[] is length bytes in length (bytes, not characters) and
23636 ** uses the encoding enc.  The string is not necessarily zero-terminated.
23637 **
23638 ** Return TRUE if the result is a valid real number (or integer) and FALSE
23639 ** if the string is empty or contains extraneous text.  Valid numbers
23640 ** are in one of these formats:
23641 **
23642 **    [+-]digits[E[+-]digits]
23643 **    [+-]digits.[digits][E[+-]digits]
23644 **    [+-].digits[E[+-]digits]
23645 **
23646 ** Leading and trailing whitespace is ignored for the purpose of determining
23647 ** validity.
23648 **
23649 ** If some prefix of the input string is a valid number, this routine
23650 ** returns FALSE but it still converts the prefix and writes the result
23651 ** into *pResult.
23652 */
23653 SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
23654 #ifndef SQLITE_OMIT_FLOATING_POINT
23655   int incr;
23656   const char *zEnd = z + length;
23657   /* sign * significand * (10 ^ (esign * exponent)) */
23658   int sign = 1;    /* sign of significand */
23659   i64 s = 0;       /* significand */
23660   int d = 0;       /* adjust exponent for shifting decimal point */
23661   int esign = 1;   /* sign of exponent */
23662   int e = 0;       /* exponent */
23663   int eValid = 1;  /* True exponent is either not used or is well-formed */
23664   double result;
23665   int nDigits = 0;
23666   int nonNum = 0;
23667
23668   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
23669   *pResult = 0.0;   /* Default return value, in case of an error */
23670
23671   if( enc==SQLITE_UTF8 ){
23672     incr = 1;
23673   }else{
23674     int i;
23675     incr = 2;
23676     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
23677     for(i=3-enc; i<length && z[i]==0; i+=2){}
23678     nonNum = i<length;
23679     zEnd = z+i+enc-3;
23680     z += (enc&1);
23681   }
23682
23683   /* skip leading spaces */
23684   while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
23685   if( z>=zEnd ) return 0;
23686
23687   /* get sign of significand */
23688   if( *z=='-' ){
23689     sign = -1;
23690     z+=incr;
23691   }else if( *z=='+' ){
23692     z+=incr;
23693   }
23694
23695   /* skip leading zeroes */
23696   while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
23697
23698   /* copy max significant digits to significand */
23699   while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
23700     s = s*10 + (*z - '0');
23701     z+=incr, nDigits++;
23702   }
23703
23704   /* skip non-significant significand digits
23705   ** (increase exponent by d to shift decimal left) */
23706   while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
23707   if( z>=zEnd ) goto do_atof_calc;
23708
23709   /* if decimal point is present */
23710   if( *z=='.' ){
23711     z+=incr;
23712     /* copy digits from after decimal to significand
23713     ** (decrease exponent by d to shift decimal right) */
23714     while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
23715       s = s*10 + (*z - '0');
23716       z+=incr, nDigits++, d--;
23717     }
23718     /* skip non-significant digits */
23719     while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
23720   }
23721   if( z>=zEnd ) goto do_atof_calc;
23722
23723   /* if exponent is present */
23724   if( *z=='e' || *z=='E' ){
23725     z+=incr;
23726     eValid = 0;
23727     if( z>=zEnd ) goto do_atof_calc;
23728     /* get sign of exponent */
23729     if( *z=='-' ){
23730       esign = -1;
23731       z+=incr;
23732     }else if( *z=='+' ){
23733       z+=incr;
23734     }
23735     /* copy digits to exponent */
23736     while( z<zEnd && sqlite3Isdigit(*z) ){
23737       e = e<10000 ? (e*10 + (*z - '0')) : 10000;
23738       z+=incr;
23739       eValid = 1;
23740     }
23741   }
23742
23743   /* skip trailing spaces */
23744   if( nDigits && eValid ){
23745     while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
23746   }
23747
23748 do_atof_calc:
23749   /* adjust exponent by d, and update sign */
23750   e = (e*esign) + d;
23751   if( e<0 ) {
23752     esign = -1;
23753     e *= -1;
23754   } else {
23755     esign = 1;
23756   }
23757
23758   /* if 0 significand */
23759   if( !s ) {
23760     /* In the IEEE 754 standard, zero is signed.
23761     ** Add the sign if we've seen at least one digit */
23762     result = (sign<0 && nDigits) ? -(double)0 : (double)0;
23763   } else {
23764     /* attempt to reduce exponent */
23765     if( esign>0 ){
23766       while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
23767     }else{
23768       while( !(s%10) && e>0 ) e--,s/=10;
23769     }
23770
23771     /* adjust the sign of significand */
23772     s = sign<0 ? -s : s;
23773
23774     /* if exponent, scale significand as appropriate
23775     ** and store in result. */
23776     if( e ){
23777       LONGDOUBLE_TYPE scale = 1.0;
23778       /* attempt to handle extremely small/large numbers better */
23779       if( e>307 && e<342 ){
23780         while( e%308 ) { scale *= 1.0e+1; e -= 1; }
23781         if( esign<0 ){
23782           result = s / scale;
23783           result /= 1.0e+308;
23784         }else{
23785           result = s * scale;
23786           result *= 1.0e+308;
23787         }
23788       }else if( e>=342 ){
23789         if( esign<0 ){
23790           result = 0.0*s;
23791         }else{
23792           result = 1e308*1e308*s;  /* Infinity */
23793         }
23794       }else{
23795         /* 1.0e+22 is the largest power of 10 than can be 
23796         ** represented exactly. */
23797         while( e%22 ) { scale *= 1.0e+1; e -= 1; }
23798         while( e>0 ) { scale *= 1.0e+22; e -= 22; }
23799         if( esign<0 ){
23800           result = s / scale;
23801         }else{
23802           result = s * scale;
23803         }
23804       }
23805     } else {
23806       result = (double)s;
23807     }
23808   }
23809
23810   /* store the result */
23811   *pResult = result;
23812
23813   /* return true if number and no extra non-whitespace chracters after */
23814   return z>=zEnd && nDigits>0 && eValid && nonNum==0;
23815 #else
23816   return !sqlite3Atoi64(z, pResult, length, enc);
23817 #endif /* SQLITE_OMIT_FLOATING_POINT */
23818 }
23819
23820 /*
23821 ** Compare the 19-character string zNum against the text representation
23822 ** value 2^63:  9223372036854775808.  Return negative, zero, or positive
23823 ** if zNum is less than, equal to, or greater than the string.
23824 ** Note that zNum must contain exactly 19 characters.
23825 **
23826 ** Unlike memcmp() this routine is guaranteed to return the difference
23827 ** in the values of the last digit if the only difference is in the
23828 ** last digit.  So, for example,
23829 **
23830 **      compare2pow63("9223372036854775800", 1)
23831 **
23832 ** will return -8.
23833 */
23834 static int compare2pow63(const char *zNum, int incr){
23835   int c = 0;
23836   int i;
23837                     /* 012345678901234567 */
23838   const char *pow63 = "922337203685477580";
23839   for(i=0; c==0 && i<18; i++){
23840     c = (zNum[i*incr]-pow63[i])*10;
23841   }
23842   if( c==0 ){
23843     c = zNum[18*incr] - '8';
23844     testcase( c==(-1) );
23845     testcase( c==0 );
23846     testcase( c==(+1) );
23847   }
23848   return c;
23849 }
23850
23851 /*
23852 ** Convert zNum to a 64-bit signed integer.  zNum must be decimal. This
23853 ** routine does *not* accept hexadecimal notation.
23854 **
23855 ** If the zNum value is representable as a 64-bit twos-complement 
23856 ** integer, then write that value into *pNum and return 0.
23857 **
23858 ** If zNum is exactly 9223372036854775808, return 2.  This special
23859 ** case is broken out because while 9223372036854775808 cannot be a 
23860 ** signed 64-bit integer, its negative -9223372036854775808 can be.
23861 **
23862 ** If zNum is too big for a 64-bit integer and is not
23863 ** 9223372036854775808  or if zNum contains any non-numeric text,
23864 ** then return 1.
23865 **
23866 ** length is the number of bytes in the string (bytes, not characters).
23867 ** The string is not necessarily zero-terminated.  The encoding is
23868 ** given by enc.
23869 */
23870 SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
23871   int incr;
23872   u64 u = 0;
23873   int neg = 0; /* assume positive */
23874   int i;
23875   int c = 0;
23876   int nonNum = 0;
23877   const char *zStart;
23878   const char *zEnd = zNum + length;
23879   assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
23880   if( enc==SQLITE_UTF8 ){
23881     incr = 1;
23882   }else{
23883     incr = 2;
23884     assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
23885     for(i=3-enc; i<length && zNum[i]==0; i+=2){}
23886     nonNum = i<length;
23887     zEnd = zNum+i+enc-3;
23888     zNum += (enc&1);
23889   }
23890   while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
23891   if( zNum<zEnd ){
23892     if( *zNum=='-' ){
23893       neg = 1;
23894       zNum+=incr;
23895     }else if( *zNum=='+' ){
23896       zNum+=incr;
23897     }
23898   }
23899   zStart = zNum;
23900   while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
23901   for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
23902     u = u*10 + c - '0';
23903   }
23904   if( u>LARGEST_INT64 ){
23905     *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
23906   }else if( neg ){
23907     *pNum = -(i64)u;
23908   }else{
23909     *pNum = (i64)u;
23910   }
23911   testcase( i==18 );
23912   testcase( i==19 );
23913   testcase( i==20 );
23914   if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
23915     /* zNum is empty or contains non-numeric text or is longer
23916     ** than 19 digits (thus guaranteeing that it is too large) */
23917     return 1;
23918   }else if( i<19*incr ){
23919     /* Less than 19 digits, so we know that it fits in 64 bits */
23920     assert( u<=LARGEST_INT64 );
23921     return 0;
23922   }else{
23923     /* zNum is a 19-digit numbers.  Compare it against 9223372036854775808. */
23924     c = compare2pow63(zNum, incr);
23925     if( c<0 ){
23926       /* zNum is less than 9223372036854775808 so it fits */
23927       assert( u<=LARGEST_INT64 );
23928       return 0;
23929     }else if( c>0 ){
23930       /* zNum is greater than 9223372036854775808 so it overflows */
23931       return 1;
23932     }else{
23933       /* zNum is exactly 9223372036854775808.  Fits if negative.  The
23934       ** special case 2 overflow if positive */
23935       assert( u-1==LARGEST_INT64 );
23936       return neg ? 0 : 2;
23937     }
23938   }
23939 }
23940
23941 /*
23942 ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
23943 ** into a 64-bit signed integer.  This routine accepts hexadecimal literals,
23944 ** whereas sqlite3Atoi64() does not.
23945 **
23946 ** Returns:
23947 **
23948 **     0    Successful transformation.  Fits in a 64-bit signed integer.
23949 **     1    Integer too large for a 64-bit signed integer or is malformed
23950 **     2    Special case of 9223372036854775808
23951 */
23952 SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
23953 #ifndef SQLITE_OMIT_HEX_INTEGER
23954   if( z[0]=='0'
23955    && (z[1]=='x' || z[1]=='X')
23956    && sqlite3Isxdigit(z[2])
23957   ){
23958     u64 u = 0;
23959     int i, k;
23960     for(i=2; z[i]=='0'; i++){}
23961     for(k=i; sqlite3Isxdigit(z[k]); k++){
23962       u = u*16 + sqlite3HexToInt(z[k]);
23963     }
23964     memcpy(pOut, &u, 8);
23965     return (z[k]==0 && k-i<=16) ? 0 : 1;
23966   }else
23967 #endif /* SQLITE_OMIT_HEX_INTEGER */
23968   {
23969     return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
23970   }
23971 }
23972
23973 /*
23974 ** If zNum represents an integer that will fit in 32-bits, then set
23975 ** *pValue to that integer and return true.  Otherwise return false.
23976 **
23977 ** This routine accepts both decimal and hexadecimal notation for integers.
23978 **
23979 ** Any non-numeric characters that following zNum are ignored.
23980 ** This is different from sqlite3Atoi64() which requires the
23981 ** input number to be zero-terminated.
23982 */
23983 SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
23984   sqlite_int64 v = 0;
23985   int i, c;
23986   int neg = 0;
23987   if( zNum[0]=='-' ){
23988     neg = 1;
23989     zNum++;
23990   }else if( zNum[0]=='+' ){
23991     zNum++;
23992   }
23993 #ifndef SQLITE_OMIT_HEX_INTEGER
23994   else if( zNum[0]=='0'
23995         && (zNum[1]=='x' || zNum[1]=='X')
23996         && sqlite3Isxdigit(zNum[2])
23997   ){
23998     u32 u = 0;
23999     zNum += 2;
24000     while( zNum[0]=='0' ) zNum++;
24001     for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
24002       u = u*16 + sqlite3HexToInt(zNum[i]);
24003     }
24004     if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
24005       memcpy(pValue, &u, 4);
24006       return 1;
24007     }else{
24008       return 0;
24009     }
24010   }
24011 #endif
24012   for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
24013     v = v*10 + c;
24014   }
24015
24016   /* The longest decimal representation of a 32 bit integer is 10 digits:
24017   **
24018   **             1234567890
24019   **     2^31 -> 2147483648
24020   */
24021   testcase( i==10 );
24022   if( i>10 ){
24023     return 0;
24024   }
24025   testcase( v-neg==2147483647 );
24026   if( v-neg>2147483647 ){
24027     return 0;
24028   }
24029   if( neg ){
24030     v = -v;
24031   }
24032   *pValue = (int)v;
24033   return 1;
24034 }
24035
24036 /*
24037 ** Return a 32-bit integer value extracted from a string.  If the
24038 ** string is not an integer, just return 0.
24039 */
24040 SQLITE_PRIVATE int sqlite3Atoi(const char *z){
24041   int x = 0;
24042   if( z ) sqlite3GetInt32(z, &x);
24043   return x;
24044 }
24045
24046 /*
24047 ** The variable-length integer encoding is as follows:
24048 **
24049 ** KEY:
24050 **         A = 0xxxxxxx    7 bits of data and one flag bit
24051 **         B = 1xxxxxxx    7 bits of data and one flag bit
24052 **         C = xxxxxxxx    8 bits of data
24053 **
24054 **  7 bits - A
24055 ** 14 bits - BA
24056 ** 21 bits - BBA
24057 ** 28 bits - BBBA
24058 ** 35 bits - BBBBA
24059 ** 42 bits - BBBBBA
24060 ** 49 bits - BBBBBBA
24061 ** 56 bits - BBBBBBBA
24062 ** 64 bits - BBBBBBBBC
24063 */
24064
24065 /*
24066 ** Write a 64-bit variable-length integer to memory starting at p[0].
24067 ** The length of data write will be between 1 and 9 bytes.  The number
24068 ** of bytes written is returned.
24069 **
24070 ** A variable-length integer consists of the lower 7 bits of each byte
24071 ** for all bytes that have the 8th bit set and one byte with the 8th
24072 ** bit clear.  Except, if we get to the 9th byte, it stores the full
24073 ** 8 bits and is the last byte.
24074 */
24075 static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
24076   int i, j, n;
24077   u8 buf[10];
24078   if( v & (((u64)0xff000000)<<32) ){
24079     p[8] = (u8)v;
24080     v >>= 8;
24081     for(i=7; i>=0; i--){
24082       p[i] = (u8)((v & 0x7f) | 0x80);
24083       v >>= 7;
24084     }
24085     return 9;
24086   }    
24087   n = 0;
24088   do{
24089     buf[n++] = (u8)((v & 0x7f) | 0x80);
24090     v >>= 7;
24091   }while( v!=0 );
24092   buf[0] &= 0x7f;
24093   assert( n<=9 );
24094   for(i=0, j=n-1; j>=0; j--, i++){
24095     p[i] = buf[j];
24096   }
24097   return n;
24098 }
24099 SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
24100   if( v<=0x7f ){
24101     p[0] = v&0x7f;
24102     return 1;
24103   }
24104   if( v<=0x3fff ){
24105     p[0] = ((v>>7)&0x7f)|0x80;
24106     p[1] = v&0x7f;
24107     return 2;
24108   }
24109   return putVarint64(p,v);
24110 }
24111
24112 /*
24113 ** Bitmasks used by sqlite3GetVarint().  These precomputed constants
24114 ** are defined here rather than simply putting the constant expressions
24115 ** inline in order to work around bugs in the RVT compiler.
24116 **
24117 ** SLOT_2_0     A mask for  (0x7f<<14) | 0x7f
24118 **
24119 ** SLOT_4_2_0   A mask for  (0x7f<<28) | SLOT_2_0
24120 */
24121 #define SLOT_2_0     0x001fc07f
24122 #define SLOT_4_2_0   0xf01fc07f
24123
24124
24125 /*
24126 ** Read a 64-bit variable-length integer from memory starting at p[0].
24127 ** Return the number of bytes read.  The value is stored in *v.
24128 */
24129 SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
24130   u32 a,b,s;
24131
24132   a = *p;
24133   /* a: p0 (unmasked) */
24134   if (!(a&0x80))
24135   {
24136     *v = a;
24137     return 1;
24138   }
24139
24140   p++;
24141   b = *p;
24142   /* b: p1 (unmasked) */
24143   if (!(b&0x80))
24144   {
24145     a &= 0x7f;
24146     a = a<<7;
24147     a |= b;
24148     *v = a;
24149     return 2;
24150   }
24151
24152   /* Verify that constants are precomputed correctly */
24153   assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
24154   assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
24155
24156   p++;
24157   a = a<<14;
24158   a |= *p;
24159   /* a: p0<<14 | p2 (unmasked) */
24160   if (!(a&0x80))
24161   {
24162     a &= SLOT_2_0;
24163     b &= 0x7f;
24164     b = b<<7;
24165     a |= b;
24166     *v = a;
24167     return 3;
24168   }
24169
24170   /* CSE1 from below */
24171   a &= SLOT_2_0;
24172   p++;
24173   b = b<<14;
24174   b |= *p;
24175   /* b: p1<<14 | p3 (unmasked) */
24176   if (!(b&0x80))
24177   {
24178     b &= SLOT_2_0;
24179     /* moved CSE1 up */
24180     /* a &= (0x7f<<14)|(0x7f); */
24181     a = a<<7;
24182     a |= b;
24183     *v = a;
24184     return 4;
24185   }
24186
24187   /* a: p0<<14 | p2 (masked) */
24188   /* b: p1<<14 | p3 (unmasked) */
24189   /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
24190   /* moved CSE1 up */
24191   /* a &= (0x7f<<14)|(0x7f); */
24192   b &= SLOT_2_0;
24193   s = a;
24194   /* s: p0<<14 | p2 (masked) */
24195
24196   p++;
24197   a = a<<14;
24198   a |= *p;
24199   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
24200   if (!(a&0x80))
24201   {
24202     /* we can skip these cause they were (effectively) done above in calc'ing s */
24203     /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
24204     /* b &= (0x7f<<14)|(0x7f); */
24205     b = b<<7;
24206     a |= b;
24207     s = s>>18;
24208     *v = ((u64)s)<<32 | a;
24209     return 5;
24210   }
24211
24212   /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
24213   s = s<<7;
24214   s |= b;
24215   /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
24216
24217   p++;
24218   b = b<<14;
24219   b |= *p;
24220   /* b: p1<<28 | p3<<14 | p5 (unmasked) */
24221   if (!(b&0x80))
24222   {
24223     /* we can skip this cause it was (effectively) done above in calc'ing s */
24224     /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
24225     a &= SLOT_2_0;
24226     a = a<<7;
24227     a |= b;
24228     s = s>>18;
24229     *v = ((u64)s)<<32 | a;
24230     return 6;
24231   }
24232
24233   p++;
24234   a = a<<14;
24235   a |= *p;
24236   /* a: p2<<28 | p4<<14 | p6 (unmasked) */
24237   if (!(a&0x80))
24238   {
24239     a &= SLOT_4_2_0;
24240     b &= SLOT_2_0;
24241     b = b<<7;
24242     a |= b;
24243     s = s>>11;
24244     *v = ((u64)s)<<32 | a;
24245     return 7;
24246   }
24247
24248   /* CSE2 from below */
24249   a &= SLOT_2_0;
24250   p++;
24251   b = b<<14;
24252   b |= *p;
24253   /* b: p3<<28 | p5<<14 | p7 (unmasked) */
24254   if (!(b&0x80))
24255   {
24256     b &= SLOT_4_2_0;
24257     /* moved CSE2 up */
24258     /* a &= (0x7f<<14)|(0x7f); */
24259     a = a<<7;
24260     a |= b;
24261     s = s>>4;
24262     *v = ((u64)s)<<32 | a;
24263     return 8;
24264   }
24265
24266   p++;
24267   a = a<<15;
24268   a |= *p;
24269   /* a: p4<<29 | p6<<15 | p8 (unmasked) */
24270
24271   /* moved CSE2 up */
24272   /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
24273   b &= SLOT_2_0;
24274   b = b<<8;
24275   a |= b;
24276
24277   s = s<<4;
24278   b = p[-4];
24279   b &= 0x7f;
24280   b = b>>3;
24281   s |= b;
24282
24283   *v = ((u64)s)<<32 | a;
24284
24285   return 9;
24286 }
24287
24288 /*
24289 ** Read a 32-bit variable-length integer from memory starting at p[0].
24290 ** Return the number of bytes read.  The value is stored in *v.
24291 **
24292 ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
24293 ** integer, then set *v to 0xffffffff.
24294 **
24295 ** A MACRO version, getVarint32, is provided which inlines the 
24296 ** single-byte case.  All code should use the MACRO version as 
24297 ** this function assumes the single-byte case has already been handled.
24298 */
24299 SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
24300   u32 a,b;
24301
24302   /* The 1-byte case.  Overwhelmingly the most common.  Handled inline
24303   ** by the getVarin32() macro */
24304   a = *p;
24305   /* a: p0 (unmasked) */
24306 #ifndef getVarint32
24307   if (!(a&0x80))
24308   {
24309     /* Values between 0 and 127 */
24310     *v = a;
24311     return 1;
24312   }
24313 #endif
24314
24315   /* The 2-byte case */
24316   p++;
24317   b = *p;
24318   /* b: p1 (unmasked) */
24319   if (!(b&0x80))
24320   {
24321     /* Values between 128 and 16383 */
24322     a &= 0x7f;
24323     a = a<<7;
24324     *v = a | b;
24325     return 2;
24326   }
24327
24328   /* The 3-byte case */
24329   p++;
24330   a = a<<14;
24331   a |= *p;
24332   /* a: p0<<14 | p2 (unmasked) */
24333   if (!(a&0x80))
24334   {
24335     /* Values between 16384 and 2097151 */
24336     a &= (0x7f<<14)|(0x7f);
24337     b &= 0x7f;
24338     b = b<<7;
24339     *v = a | b;
24340     return 3;
24341   }
24342
24343   /* A 32-bit varint is used to store size information in btrees.
24344   ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
24345   ** A 3-byte varint is sufficient, for example, to record the size
24346   ** of a 1048569-byte BLOB or string.
24347   **
24348   ** We only unroll the first 1-, 2-, and 3- byte cases.  The very
24349   ** rare larger cases can be handled by the slower 64-bit varint
24350   ** routine.
24351   */
24352 #if 1
24353   {
24354     u64 v64;
24355     u8 n;
24356
24357     p -= 2;
24358     n = sqlite3GetVarint(p, &v64);
24359     assert( n>3 && n<=9 );
24360     if( (v64 & SQLITE_MAX_U32)!=v64 ){
24361       *v = 0xffffffff;
24362     }else{
24363       *v = (u32)v64;
24364     }
24365     return n;
24366   }
24367
24368 #else
24369   /* For following code (kept for historical record only) shows an
24370   ** unrolling for the 3- and 4-byte varint cases.  This code is
24371   ** slightly faster, but it is also larger and much harder to test.
24372   */
24373   p++;
24374   b = b<<14;
24375   b |= *p;
24376   /* b: p1<<14 | p3 (unmasked) */
24377   if (!(b&0x80))
24378   {
24379     /* Values between 2097152 and 268435455 */
24380     b &= (0x7f<<14)|(0x7f);
24381     a &= (0x7f<<14)|(0x7f);
24382     a = a<<7;
24383     *v = a | b;
24384     return 4;
24385   }
24386
24387   p++;
24388   a = a<<14;
24389   a |= *p;
24390   /* a: p0<<28 | p2<<14 | p4 (unmasked) */
24391   if (!(a&0x80))
24392   {
24393     /* Values  between 268435456 and 34359738367 */
24394     a &= SLOT_4_2_0;
24395     b &= SLOT_4_2_0;
24396     b = b<<7;
24397     *v = a | b;
24398     return 5;
24399   }
24400
24401   /* We can only reach this point when reading a corrupt database
24402   ** file.  In that case we are not in any hurry.  Use the (relatively
24403   ** slow) general-purpose sqlite3GetVarint() routine to extract the
24404   ** value. */
24405   {
24406     u64 v64;
24407     u8 n;
24408
24409     p -= 4;
24410     n = sqlite3GetVarint(p, &v64);
24411     assert( n>5 && n<=9 );
24412     *v = (u32)v64;
24413     return n;
24414   }
24415 #endif
24416 }
24417
24418 /*
24419 ** Return the number of bytes that will be needed to store the given
24420 ** 64-bit integer.
24421 */
24422 SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
24423   int i = 0;
24424   do{
24425     i++;
24426     v >>= 7;
24427   }while( v!=0 && ALWAYS(i<9) );
24428   return i;
24429 }
24430
24431
24432 /*
24433 ** Read or write a four-byte big-endian integer value.
24434 */
24435 SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
24436   testcase( p[0]&0x80 );
24437   return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
24438 }
24439 SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
24440   p[0] = (u8)(v>>24);
24441   p[1] = (u8)(v>>16);
24442   p[2] = (u8)(v>>8);
24443   p[3] = (u8)v;
24444 }
24445
24446
24447
24448 /*
24449 ** Translate a single byte of Hex into an integer.
24450 ** This routine only works if h really is a valid hexadecimal
24451 ** character:  0..9a..fA..F
24452 */
24453 SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
24454   assert( (h>='0' && h<='9') ||  (h>='a' && h<='f') ||  (h>='A' && h<='F') );
24455 #ifdef SQLITE_ASCII
24456   h += 9*(1&(h>>6));
24457 #endif
24458 #ifdef SQLITE_EBCDIC
24459   h += 9*(1&~(h>>4));
24460 #endif
24461   return (u8)(h & 0xf);
24462 }
24463
24464 #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
24465 /*
24466 ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
24467 ** value.  Return a pointer to its binary value.  Space to hold the
24468 ** binary value has been obtained from malloc and must be freed by
24469 ** the calling routine.
24470 */
24471 SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
24472   char *zBlob;
24473   int i;
24474
24475   zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
24476   n--;
24477   if( zBlob ){
24478     for(i=0; i<n; i+=2){
24479       zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
24480     }
24481     zBlob[i/2] = 0;
24482   }
24483   return zBlob;
24484 }
24485 #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
24486
24487 /*
24488 ** Log an error that is an API call on a connection pointer that should
24489 ** not have been used.  The "type" of connection pointer is given as the
24490 ** argument.  The zType is a word like "NULL" or "closed" or "invalid".
24491 */
24492 static void logBadConnection(const char *zType){
24493   sqlite3_log(SQLITE_MISUSE, 
24494      "API call with %s database connection pointer",
24495      zType
24496   );
24497 }
24498
24499 /*
24500 ** Check to make sure we have a valid db pointer.  This test is not
24501 ** foolproof but it does provide some measure of protection against
24502 ** misuse of the interface such as passing in db pointers that are
24503 ** NULL or which have been previously closed.  If this routine returns
24504 ** 1 it means that the db pointer is valid and 0 if it should not be
24505 ** dereferenced for any reason.  The calling function should invoke
24506 ** SQLITE_MISUSE immediately.
24507 **
24508 ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
24509 ** use.  sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
24510 ** open properly and is not fit for general use but which can be
24511 ** used as an argument to sqlite3_errmsg() or sqlite3_close().
24512 */
24513 SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
24514   u32 magic;
24515   if( db==0 ){
24516     logBadConnection("NULL");
24517     return 0;
24518   }
24519   magic = db->magic;
24520   if( magic!=SQLITE_MAGIC_OPEN ){
24521     if( sqlite3SafetyCheckSickOrOk(db) ){
24522       testcase( sqlite3GlobalConfig.xLog!=0 );
24523       logBadConnection("unopened");
24524     }
24525     return 0;
24526   }else{
24527     return 1;
24528   }
24529 }
24530 SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
24531   u32 magic;
24532   magic = db->magic;
24533   if( magic!=SQLITE_MAGIC_SICK &&
24534       magic!=SQLITE_MAGIC_OPEN &&
24535       magic!=SQLITE_MAGIC_BUSY ){
24536     testcase( sqlite3GlobalConfig.xLog!=0 );
24537     logBadConnection("invalid");
24538     return 0;
24539   }else{
24540     return 1;
24541   }
24542 }
24543
24544 /*
24545 ** Attempt to add, substract, or multiply the 64-bit signed value iB against
24546 ** the other 64-bit signed integer at *pA and store the result in *pA.
24547 ** Return 0 on success.  Or if the operation would have resulted in an
24548 ** overflow, leave *pA unchanged and return 1.
24549 */
24550 SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
24551   i64 iA = *pA;
24552   testcase( iA==0 ); testcase( iA==1 );
24553   testcase( iB==-1 ); testcase( iB==0 );
24554   if( iB>=0 ){
24555     testcase( iA>0 && LARGEST_INT64 - iA == iB );
24556     testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
24557     if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
24558   }else{
24559     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
24560     testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
24561     if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
24562   }
24563   *pA += iB;
24564   return 0; 
24565 }
24566 SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
24567   testcase( iB==SMALLEST_INT64+1 );
24568   if( iB==SMALLEST_INT64 ){
24569     testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
24570     if( (*pA)>=0 ) return 1;
24571     *pA -= iB;
24572     return 0;
24573   }else{
24574     return sqlite3AddInt64(pA, -iB);
24575   }
24576 }
24577 #define TWOPOWER32 (((i64)1)<<32)
24578 #define TWOPOWER31 (((i64)1)<<31)
24579 SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
24580   i64 iA = *pA;
24581   i64 iA1, iA0, iB1, iB0, r;
24582
24583   iA1 = iA/TWOPOWER32;
24584   iA0 = iA % TWOPOWER32;
24585   iB1 = iB/TWOPOWER32;
24586   iB0 = iB % TWOPOWER32;
24587   if( iA1==0 ){
24588     if( iB1==0 ){
24589       *pA *= iB;
24590       return 0;
24591     }
24592     r = iA0*iB1;
24593   }else if( iB1==0 ){
24594     r = iA1*iB0;
24595   }else{
24596     /* If both iA1 and iB1 are non-zero, overflow will result */
24597     return 1;
24598   }
24599   testcase( r==(-TWOPOWER31)-1 );
24600   testcase( r==(-TWOPOWER31) );
24601   testcase( r==TWOPOWER31 );
24602   testcase( r==TWOPOWER31-1 );
24603   if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
24604   r *= TWOPOWER32;
24605   if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
24606   *pA = r;
24607   return 0;
24608 }
24609
24610 /*
24611 ** Compute the absolute value of a 32-bit signed integer, of possible.  Or 
24612 ** if the integer has a value of -2147483648, return +2147483647
24613 */
24614 SQLITE_PRIVATE int sqlite3AbsInt32(int x){
24615   if( x>=0 ) return x;
24616   if( x==(int)0x80000000 ) return 0x7fffffff;
24617   return -x;
24618 }
24619
24620 #ifdef SQLITE_ENABLE_8_3_NAMES
24621 /*
24622 ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
24623 ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
24624 ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
24625 ** three characters, then shorten the suffix on z[] to be the last three
24626 ** characters of the original suffix.
24627 **
24628 ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
24629 ** do the suffix shortening regardless of URI parameter.
24630 **
24631 ** Examples:
24632 **
24633 **     test.db-journal    =>   test.nal
24634 **     test.db-wal        =>   test.wal
24635 **     test.db-shm        =>   test.shm
24636 **     test.db-mj7f3319fa =>   test.9fa
24637 */
24638 SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
24639 #if SQLITE_ENABLE_8_3_NAMES<2
24640   if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
24641 #endif
24642   {
24643     int i, sz;
24644     sz = sqlite3Strlen30(z);
24645     for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
24646     if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
24647   }
24648 }
24649 #endif
24650
24651 /* 
24652 ** Find (an approximate) sum of two LogEst values.  This computation is
24653 ** not a simple "+" operator because LogEst is stored as a logarithmic
24654 ** value.
24655 ** 
24656 */
24657 SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
24658   static const unsigned char x[] = {
24659      10, 10,                         /* 0,1 */
24660       9, 9,                          /* 2,3 */
24661       8, 8,                          /* 4,5 */
24662       7, 7, 7,                       /* 6,7,8 */
24663       6, 6, 6,                       /* 9,10,11 */
24664       5, 5, 5,                       /* 12-14 */
24665       4, 4, 4, 4,                    /* 15-18 */
24666       3, 3, 3, 3, 3, 3,              /* 19-24 */
24667       2, 2, 2, 2, 2, 2, 2,           /* 25-31 */
24668   };
24669   if( a>=b ){
24670     if( a>b+49 ) return a;
24671     if( a>b+31 ) return a+1;
24672     return a+x[a-b];
24673   }else{
24674     if( b>a+49 ) return b;
24675     if( b>a+31 ) return b+1;
24676     return b+x[b-a];
24677   }
24678 }
24679
24680 /*
24681 ** Convert an integer into a LogEst.  In other words, compute an
24682 ** approximation for 10*log2(x).
24683 */
24684 SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
24685   static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
24686   LogEst y = 40;
24687   if( x<8 ){
24688     if( x<2 ) return 0;
24689     while( x<8 ){  y -= 10; x <<= 1; }
24690   }else{
24691     while( x>255 ){ y += 40; x >>= 4; }
24692     while( x>15 ){  y += 10; x >>= 1; }
24693   }
24694   return a[x&7] + y - 10;
24695 }
24696
24697 #ifndef SQLITE_OMIT_VIRTUALTABLE
24698 /*
24699 ** Convert a double into a LogEst
24700 ** In other words, compute an approximation for 10*log2(x).
24701 */
24702 SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
24703   u64 a;
24704   LogEst e;
24705   assert( sizeof(x)==8 && sizeof(a)==8 );
24706   if( x<=1 ) return 0;
24707   if( x<=2000000000 ) return sqlite3LogEst((u64)x);
24708   memcpy(&a, &x, 8);
24709   e = (a>>52) - 1022;
24710   return e*10;
24711 }
24712 #endif /* SQLITE_OMIT_VIRTUALTABLE */
24713
24714 /*
24715 ** Convert a LogEst into an integer.
24716 */
24717 SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
24718   u64 n;
24719   if( x<10 ) return 1;
24720   n = x%10;
24721   x /= 10;
24722   if( n>=5 ) n -= 2;
24723   else if( n>=1 ) n -= 1;
24724   if( x>=3 ){
24725     return x>60 ? (u64)LARGEST_INT64 : (n+8)<<(x-3);
24726   }
24727   return (n+8)>>(3-x);
24728 }
24729
24730 /************** End of util.c ************************************************/
24731 /************** Begin file hash.c ********************************************/
24732 /*
24733 ** 2001 September 22
24734 **
24735 ** The author disclaims copyright to this source code.  In place of
24736 ** a legal notice, here is a blessing:
24737 **
24738 **    May you do good and not evil.
24739 **    May you find forgiveness for yourself and forgive others.
24740 **    May you share freely, never taking more than you give.
24741 **
24742 *************************************************************************
24743 ** This is the implementation of generic hash-tables
24744 ** used in SQLite.
24745 */
24746 /* #include <assert.h> */
24747
24748 /* Turn bulk memory into a hash table object by initializing the
24749 ** fields of the Hash structure.
24750 **
24751 ** "pNew" is a pointer to the hash table that is to be initialized.
24752 */
24753 SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
24754   assert( pNew!=0 );
24755   pNew->first = 0;
24756   pNew->count = 0;
24757   pNew->htsize = 0;
24758   pNew->ht = 0;
24759 }
24760
24761 /* Remove all entries from a hash table.  Reclaim all memory.
24762 ** Call this routine to delete a hash table or to reset a hash table
24763 ** to the empty state.
24764 */
24765 SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
24766   HashElem *elem;         /* For looping over all elements of the table */
24767
24768   assert( pH!=0 );
24769   elem = pH->first;
24770   pH->first = 0;
24771   sqlite3_free(pH->ht);
24772   pH->ht = 0;
24773   pH->htsize = 0;
24774   while( elem ){
24775     HashElem *next_elem = elem->next;
24776     sqlite3_free(elem);
24777     elem = next_elem;
24778   }
24779   pH->count = 0;
24780 }
24781
24782 /*
24783 ** The hashing function.
24784 */
24785 static unsigned int strHash(const char *z){
24786   unsigned int h = 0;
24787   unsigned char c;
24788   while( (c = (unsigned char)*z++)!=0 ){
24789     h = (h<<3) ^ h ^ sqlite3UpperToLower[c];
24790   }
24791   return h;
24792 }
24793
24794
24795 /* Link pNew element into the hash table pH.  If pEntry!=0 then also
24796 ** insert pNew into the pEntry hash bucket.
24797 */
24798 static void insertElement(
24799   Hash *pH,              /* The complete hash table */
24800   struct _ht *pEntry,    /* The entry into which pNew is inserted */
24801   HashElem *pNew         /* The element to be inserted */
24802 ){
24803   HashElem *pHead;       /* First element already in pEntry */
24804   if( pEntry ){
24805     pHead = pEntry->count ? pEntry->chain : 0;
24806     pEntry->count++;
24807     pEntry->chain = pNew;
24808   }else{
24809     pHead = 0;
24810   }
24811   if( pHead ){
24812     pNew->next = pHead;
24813     pNew->prev = pHead->prev;
24814     if( pHead->prev ){ pHead->prev->next = pNew; }
24815     else             { pH->first = pNew; }
24816     pHead->prev = pNew;
24817   }else{
24818     pNew->next = pH->first;
24819     if( pH->first ){ pH->first->prev = pNew; }
24820     pNew->prev = 0;
24821     pH->first = pNew;
24822   }
24823 }
24824
24825
24826 /* Resize the hash table so that it cantains "new_size" buckets.
24827 **
24828 ** The hash table might fail to resize if sqlite3_malloc() fails or
24829 ** if the new size is the same as the prior size.
24830 ** Return TRUE if the resize occurs and false if not.
24831 */
24832 static int rehash(Hash *pH, unsigned int new_size){
24833   struct _ht *new_ht;            /* The new hash table */
24834   HashElem *elem, *next_elem;    /* For looping over existing elements */
24835
24836 #if SQLITE_MALLOC_SOFT_LIMIT>0
24837   if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
24838     new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
24839   }
24840   if( new_size==pH->htsize ) return 0;
24841 #endif
24842
24843   /* The inability to allocates space for a larger hash table is
24844   ** a performance hit but it is not a fatal error.  So mark the
24845   ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of 
24846   ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
24847   ** only zeroes the requested number of bytes whereas this module will
24848   ** use the actual amount of space allocated for the hash table (which
24849   ** may be larger than the requested amount).
24850   */
24851   sqlite3BeginBenignMalloc();
24852   new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
24853   sqlite3EndBenignMalloc();
24854
24855   if( new_ht==0 ) return 0;
24856   sqlite3_free(pH->ht);
24857   pH->ht = new_ht;
24858   pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
24859   memset(new_ht, 0, new_size*sizeof(struct _ht));
24860   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
24861     unsigned int h = strHash(elem->pKey) % new_size;
24862     next_elem = elem->next;
24863     insertElement(pH, &new_ht[h], elem);
24864   }
24865   return 1;
24866 }
24867
24868 /* This function (for internal use only) locates an element in an
24869 ** hash table that matches the given key.  The hash for this key is
24870 ** also computed and returned in the *pH parameter.
24871 */
24872 static HashElem *findElementWithHash(
24873   const Hash *pH,     /* The pH to be searched */
24874   const char *pKey,   /* The key we are searching for */
24875   unsigned int *pHash /* Write the hash value here */
24876 ){
24877   HashElem *elem;                /* Used to loop thru the element list */
24878   int count;                     /* Number of elements left to test */
24879   unsigned int h;                /* The computed hash */
24880
24881   if( pH->ht ){
24882     struct _ht *pEntry;
24883     h = strHash(pKey) % pH->htsize;
24884     pEntry = &pH->ht[h];
24885     elem = pEntry->chain;
24886     count = pEntry->count;
24887   }else{
24888     h = 0;
24889     elem = pH->first;
24890     count = pH->count;
24891   }
24892   *pHash = h;
24893   while( count-- ){
24894     assert( elem!=0 );
24895     if( sqlite3StrICmp(elem->pKey,pKey)==0 ){ 
24896       return elem;
24897     }
24898     elem = elem->next;
24899   }
24900   return 0;
24901 }
24902
24903 /* Remove a single entry from the hash table given a pointer to that
24904 ** element and a hash on the element's key.
24905 */
24906 static void removeElementGivenHash(
24907   Hash *pH,         /* The pH containing "elem" */
24908   HashElem* elem,   /* The element to be removed from the pH */
24909   unsigned int h    /* Hash value for the element */
24910 ){
24911   struct _ht *pEntry;
24912   if( elem->prev ){
24913     elem->prev->next = elem->next; 
24914   }else{
24915     pH->first = elem->next;
24916   }
24917   if( elem->next ){
24918     elem->next->prev = elem->prev;
24919   }
24920   if( pH->ht ){
24921     pEntry = &pH->ht[h];
24922     if( pEntry->chain==elem ){
24923       pEntry->chain = elem->next;
24924     }
24925     pEntry->count--;
24926     assert( pEntry->count>=0 );
24927   }
24928   sqlite3_free( elem );
24929   pH->count--;
24930   if( pH->count==0 ){
24931     assert( pH->first==0 );
24932     assert( pH->count==0 );
24933     sqlite3HashClear(pH);
24934   }
24935 }
24936
24937 /* Attempt to locate an element of the hash table pH with a key
24938 ** that matches pKey.  Return the data for this element if it is
24939 ** found, or NULL if there is no match.
24940 */
24941 SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
24942   HashElem *elem;    /* The element that matches key */
24943   unsigned int h;    /* A hash on key */
24944
24945   assert( pH!=0 );
24946   assert( pKey!=0 );
24947   elem = findElementWithHash(pH, pKey, &h);
24948   return elem ? elem->data : 0;
24949 }
24950
24951 /* Insert an element into the hash table pH.  The key is pKey
24952 ** and the data is "data".
24953 **
24954 ** If no element exists with a matching key, then a new
24955 ** element is created and NULL is returned.
24956 **
24957 ** If another element already exists with the same key, then the
24958 ** new data replaces the old data and the old data is returned.
24959 ** The key is not copied in this instance.  If a malloc fails, then
24960 ** the new data is returned and the hash table is unchanged.
24961 **
24962 ** If the "data" parameter to this function is NULL, then the
24963 ** element corresponding to "key" is removed from the hash table.
24964 */
24965 SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
24966   unsigned int h;       /* the hash of the key modulo hash table size */
24967   HashElem *elem;       /* Used to loop thru the element list */
24968   HashElem *new_elem;   /* New element added to the pH */
24969
24970   assert( pH!=0 );
24971   assert( pKey!=0 );
24972   elem = findElementWithHash(pH,pKey,&h);
24973   if( elem ){
24974     void *old_data = elem->data;
24975     if( data==0 ){
24976       removeElementGivenHash(pH,elem,h);
24977     }else{
24978       elem->data = data;
24979       elem->pKey = pKey;
24980     }
24981     return old_data;
24982   }
24983   if( data==0 ) return 0;
24984   new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
24985   if( new_elem==0 ) return data;
24986   new_elem->pKey = pKey;
24987   new_elem->data = data;
24988   pH->count++;
24989   if( pH->count>=10 && pH->count > 2*pH->htsize ){
24990     if( rehash(pH, pH->count*2) ){
24991       assert( pH->htsize>0 );
24992       h = strHash(pKey) % pH->htsize;
24993     }
24994   }
24995   insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
24996   return 0;
24997 }
24998
24999 /************** End of hash.c ************************************************/
25000 /************** Begin file opcodes.c *****************************************/
25001 /* Automatically generated.  Do not edit */
25002 /* See the mkopcodec.awk script for details. */
25003 #if !defined(SQLITE_OMIT_EXPLAIN) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
25004 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
25005 # define OpHelp(X) "\0" X
25006 #else
25007 # define OpHelp(X)
25008 #endif
25009 SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
25010  static const char *const azName[] = { "?",
25011      /*   1 */ "Function"         OpHelp("r[P3]=func(r[P2@P5])"),
25012      /*   2 */ "Savepoint"        OpHelp(""),
25013      /*   3 */ "AutoCommit"       OpHelp(""),
25014      /*   4 */ "Transaction"      OpHelp(""),
25015      /*   5 */ "SorterNext"       OpHelp(""),
25016      /*   6 */ "PrevIfOpen"       OpHelp(""),
25017      /*   7 */ "NextIfOpen"       OpHelp(""),
25018      /*   8 */ "Prev"             OpHelp(""),
25019      /*   9 */ "Next"             OpHelp(""),
25020      /*  10 */ "AggStep"          OpHelp("accum=r[P3] step(r[P2@P5])"),
25021      /*  11 */ "Checkpoint"       OpHelp(""),
25022      /*  12 */ "JournalMode"      OpHelp(""),
25023      /*  13 */ "Vacuum"           OpHelp(""),
25024      /*  14 */ "VFilter"          OpHelp("iplan=r[P3] zplan='P4'"),
25025      /*  15 */ "VUpdate"          OpHelp("data=r[P3@P2]"),
25026      /*  16 */ "Goto"             OpHelp(""),
25027      /*  17 */ "Gosub"            OpHelp(""),
25028      /*  18 */ "Return"           OpHelp(""),
25029      /*  19 */ "Not"              OpHelp("r[P2]= !r[P1]"),
25030      /*  20 */ "InitCoroutine"    OpHelp(""),
25031      /*  21 */ "EndCoroutine"     OpHelp(""),
25032      /*  22 */ "Yield"            OpHelp(""),
25033      /*  23 */ "HaltIfNull"       OpHelp("if r[P3]=null halt"),
25034      /*  24 */ "Halt"             OpHelp(""),
25035      /*  25 */ "Integer"          OpHelp("r[P2]=P1"),
25036      /*  26 */ "Int64"            OpHelp("r[P2]=P4"),
25037      /*  27 */ "String"           OpHelp("r[P2]='P4' (len=P1)"),
25038      /*  28 */ "Null"             OpHelp("r[P2..P3]=NULL"),
25039      /*  29 */ "SoftNull"         OpHelp("r[P1]=NULL"),
25040      /*  30 */ "Blob"             OpHelp("r[P2]=P4 (len=P1)"),
25041      /*  31 */ "Variable"         OpHelp("r[P2]=parameter(P1,P4)"),
25042      /*  32 */ "Move"             OpHelp("r[P2@P3]=r[P1@P3]"),
25043      /*  33 */ "Copy"             OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
25044      /*  34 */ "SCopy"            OpHelp("r[P2]=r[P1]"),
25045      /*  35 */ "ResultRow"        OpHelp("output=r[P1@P2]"),
25046      /*  36 */ "CollSeq"          OpHelp(""),
25047      /*  37 */ "AddImm"           OpHelp("r[P1]=r[P1]+P2"),
25048      /*  38 */ "MustBeInt"        OpHelp(""),
25049      /*  39 */ "RealAffinity"     OpHelp(""),
25050      /*  40 */ "Cast"             OpHelp("affinity(r[P1])"),
25051      /*  41 */ "Permutation"      OpHelp(""),
25052      /*  42 */ "Compare"          OpHelp("r[P1@P3] <-> r[P2@P3]"),
25053      /*  43 */ "Jump"             OpHelp(""),
25054      /*  44 */ "Once"             OpHelp(""),
25055      /*  45 */ "If"               OpHelp(""),
25056      /*  46 */ "IfNot"            OpHelp(""),
25057      /*  47 */ "Column"           OpHelp("r[P3]=PX"),
25058      /*  48 */ "Affinity"         OpHelp("affinity(r[P1@P2])"),
25059      /*  49 */ "MakeRecord"       OpHelp("r[P3]=mkrec(r[P1@P2])"),
25060      /*  50 */ "Count"            OpHelp("r[P2]=count()"),
25061      /*  51 */ "ReadCookie"       OpHelp(""),
25062      /*  52 */ "SetCookie"        OpHelp(""),
25063      /*  53 */ "ReopenIdx"        OpHelp("root=P2 iDb=P3"),
25064      /*  54 */ "OpenRead"         OpHelp("root=P2 iDb=P3"),
25065      /*  55 */ "OpenWrite"        OpHelp("root=P2 iDb=P3"),
25066      /*  56 */ "OpenAutoindex"    OpHelp("nColumn=P2"),
25067      /*  57 */ "OpenEphemeral"    OpHelp("nColumn=P2"),
25068      /*  58 */ "SorterOpen"       OpHelp(""),
25069      /*  59 */ "SequenceTest"     OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
25070      /*  60 */ "OpenPseudo"       OpHelp("P3 columns in r[P2]"),
25071      /*  61 */ "Close"            OpHelp(""),
25072      /*  62 */ "SeekLT"           OpHelp("key=r[P3@P4]"),
25073      /*  63 */ "SeekLE"           OpHelp("key=r[P3@P4]"),
25074      /*  64 */ "SeekGE"           OpHelp("key=r[P3@P4]"),
25075      /*  65 */ "SeekGT"           OpHelp("key=r[P3@P4]"),
25076      /*  66 */ "Seek"             OpHelp("intkey=r[P2]"),
25077      /*  67 */ "NoConflict"       OpHelp("key=r[P3@P4]"),
25078      /*  68 */ "NotFound"         OpHelp("key=r[P3@P4]"),
25079      /*  69 */ "Found"            OpHelp("key=r[P3@P4]"),
25080      /*  70 */ "NotExists"        OpHelp("intkey=r[P3]"),
25081      /*  71 */ "Or"               OpHelp("r[P3]=(r[P1] || r[P2])"),
25082      /*  72 */ "And"              OpHelp("r[P3]=(r[P1] && r[P2])"),
25083      /*  73 */ "Sequence"         OpHelp("r[P2]=cursor[P1].ctr++"),
25084      /*  74 */ "NewRowid"         OpHelp("r[P2]=rowid"),
25085      /*  75 */ "Insert"           OpHelp("intkey=r[P3] data=r[P2]"),
25086      /*  76 */ "IsNull"           OpHelp("if r[P1]==NULL goto P2"),
25087      /*  77 */ "NotNull"          OpHelp("if r[P1]!=NULL goto P2"),
25088      /*  78 */ "Ne"               OpHelp("if r[P1]!=r[P3] goto P2"),
25089      /*  79 */ "Eq"               OpHelp("if r[P1]==r[P3] goto P2"),
25090      /*  80 */ "Gt"               OpHelp("if r[P1]>r[P3] goto P2"),
25091      /*  81 */ "Le"               OpHelp("if r[P1]<=r[P3] goto P2"),
25092      /*  82 */ "Lt"               OpHelp("if r[P1]<r[P3] goto P2"),
25093      /*  83 */ "Ge"               OpHelp("if r[P1]>=r[P3] goto P2"),
25094      /*  84 */ "InsertInt"        OpHelp("intkey=P3 data=r[P2]"),
25095      /*  85 */ "BitAnd"           OpHelp("r[P3]=r[P1]&r[P2]"),
25096      /*  86 */ "BitOr"            OpHelp("r[P3]=r[P1]|r[P2]"),
25097      /*  87 */ "ShiftLeft"        OpHelp("r[P3]=r[P2]<<r[P1]"),
25098      /*  88 */ "ShiftRight"       OpHelp("r[P3]=r[P2]>>r[P1]"),
25099      /*  89 */ "Add"              OpHelp("r[P3]=r[P1]+r[P2]"),
25100      /*  90 */ "Subtract"         OpHelp("r[P3]=r[P2]-r[P1]"),
25101      /*  91 */ "Multiply"         OpHelp("r[P3]=r[P1]*r[P2]"),
25102      /*  92 */ "Divide"           OpHelp("r[P3]=r[P2]/r[P1]"),
25103      /*  93 */ "Remainder"        OpHelp("r[P3]=r[P2]%r[P1]"),
25104      /*  94 */ "Concat"           OpHelp("r[P3]=r[P2]+r[P1]"),
25105      /*  95 */ "Delete"           OpHelp(""),
25106      /*  96 */ "BitNot"           OpHelp("r[P1]= ~r[P1]"),
25107      /*  97 */ "String8"          OpHelp("r[P2]='P4'"),
25108      /*  98 */ "ResetCount"       OpHelp(""),
25109      /*  99 */ "SorterCompare"    OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
25110      /* 100 */ "SorterData"       OpHelp("r[P2]=data"),
25111      /* 101 */ "RowKey"           OpHelp("r[P2]=key"),
25112      /* 102 */ "RowData"          OpHelp("r[P2]=data"),
25113      /* 103 */ "Rowid"            OpHelp("r[P2]=rowid"),
25114      /* 104 */ "NullRow"          OpHelp(""),
25115      /* 105 */ "Last"             OpHelp(""),
25116      /* 106 */ "SorterSort"       OpHelp(""),
25117      /* 107 */ "Sort"             OpHelp(""),
25118      /* 108 */ "Rewind"           OpHelp(""),
25119      /* 109 */ "SorterInsert"     OpHelp(""),
25120      /* 110 */ "IdxInsert"        OpHelp("key=r[P2]"),
25121      /* 111 */ "IdxDelete"        OpHelp("key=r[P2@P3]"),
25122      /* 112 */ "IdxRowid"         OpHelp("r[P2]=rowid"),
25123      /* 113 */ "IdxLE"            OpHelp("key=r[P3@P4]"),
25124      /* 114 */ "IdxGT"            OpHelp("key=r[P3@P4]"),
25125      /* 115 */ "IdxLT"            OpHelp("key=r[P3@P4]"),
25126      /* 116 */ "IdxGE"            OpHelp("key=r[P3@P4]"),
25127      /* 117 */ "Destroy"          OpHelp(""),
25128      /* 118 */ "Clear"            OpHelp(""),
25129      /* 119 */ "ResetSorter"      OpHelp(""),
25130      /* 120 */ "CreateIndex"      OpHelp("r[P2]=root iDb=P1"),
25131      /* 121 */ "CreateTable"      OpHelp("r[P2]=root iDb=P1"),
25132      /* 122 */ "ParseSchema"      OpHelp(""),
25133      /* 123 */ "LoadAnalysis"     OpHelp(""),
25134      /* 124 */ "DropTable"        OpHelp(""),
25135      /* 125 */ "DropIndex"        OpHelp(""),
25136      /* 126 */ "DropTrigger"      OpHelp(""),
25137      /* 127 */ "IntegrityCk"      OpHelp(""),
25138      /* 128 */ "RowSetAdd"        OpHelp("rowset(P1)=r[P2]"),
25139      /* 129 */ "RowSetRead"       OpHelp("r[P3]=rowset(P1)"),
25140      /* 130 */ "RowSetTest"       OpHelp("if r[P3] in rowset(P1) goto P2"),
25141      /* 131 */ "Program"          OpHelp(""),
25142      /* 132 */ "Param"            OpHelp(""),
25143      /* 133 */ "Real"             OpHelp("r[P2]=P4"),
25144      /* 134 */ "FkCounter"        OpHelp("fkctr[P1]+=P2"),
25145      /* 135 */ "FkIfZero"         OpHelp("if fkctr[P1]==0 goto P2"),
25146      /* 136 */ "MemMax"           OpHelp("r[P1]=max(r[P1],r[P2])"),
25147      /* 137 */ "IfPos"            OpHelp("if r[P1]>0 goto P2"),
25148      /* 138 */ "IfNeg"            OpHelp("r[P1]+=P3, if r[P1]<0 goto P2"),
25149      /* 139 */ "IfNotZero"        OpHelp("if r[P1]!=0 then r[P1]+=P3, goto P2"),
25150      /* 140 */ "DecrJumpZero"     OpHelp("if (--r[P1])==0 goto P2"),
25151      /* 141 */ "JumpZeroIncr"     OpHelp("if (r[P1]++)==0 ) goto P2"),
25152      /* 142 */ "AggFinal"         OpHelp("accum=r[P1] N=P2"),
25153      /* 143 */ "IncrVacuum"       OpHelp(""),
25154      /* 144 */ "Expire"           OpHelp(""),
25155      /* 145 */ "TableLock"        OpHelp("iDb=P1 root=P2 write=P3"),
25156      /* 146 */ "VBegin"           OpHelp(""),
25157      /* 147 */ "VCreate"          OpHelp(""),
25158      /* 148 */ "VDestroy"         OpHelp(""),
25159      /* 149 */ "VOpen"            OpHelp(""),
25160      /* 150 */ "VColumn"          OpHelp("r[P3]=vcolumn(P2)"),
25161      /* 151 */ "VNext"            OpHelp(""),
25162      /* 152 */ "VRename"          OpHelp(""),
25163      /* 153 */ "Pagecount"        OpHelp(""),
25164      /* 154 */ "MaxPgcnt"         OpHelp(""),
25165      /* 155 */ "Init"             OpHelp("Start at P2"),
25166      /* 156 */ "Noop"             OpHelp(""),
25167      /* 157 */ "Explain"          OpHelp(""),
25168   };
25169   return azName[i];
25170 }
25171 #endif
25172
25173 /************** End of opcodes.c *********************************************/
25174 /************** Begin file os_unix.c *****************************************/
25175 /*
25176 ** 2004 May 22
25177 **
25178 ** The author disclaims copyright to this source code.  In place of
25179 ** a legal notice, here is a blessing:
25180 **
25181 **    May you do good and not evil.
25182 **    May you find forgiveness for yourself and forgive others.
25183 **    May you share freely, never taking more than you give.
25184 **
25185 ******************************************************************************
25186 **
25187 ** This file contains the VFS implementation for unix-like operating systems
25188 ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
25189 **
25190 ** There are actually several different VFS implementations in this file.
25191 ** The differences are in the way that file locking is done.  The default
25192 ** implementation uses Posix Advisory Locks.  Alternative implementations
25193 ** use flock(), dot-files, various proprietary locking schemas, or simply
25194 ** skip locking all together.
25195 **
25196 ** This source file is organized into divisions where the logic for various
25197 ** subfunctions is contained within the appropriate division.  PLEASE
25198 ** KEEP THE STRUCTURE OF THIS FILE INTACT.  New code should be placed
25199 ** in the correct division and should be clearly labeled.
25200 **
25201 ** The layout of divisions is as follows:
25202 **
25203 **   *  General-purpose declarations and utility functions.
25204 **   *  Unique file ID logic used by VxWorks.
25205 **   *  Various locking primitive implementations (all except proxy locking):
25206 **      + for Posix Advisory Locks
25207 **      + for no-op locks
25208 **      + for dot-file locks
25209 **      + for flock() locking
25210 **      + for named semaphore locks (VxWorks only)
25211 **      + for AFP filesystem locks (MacOSX only)
25212 **   *  sqlite3_file methods not associated with locking.
25213 **   *  Definitions of sqlite3_io_methods objects for all locking
25214 **      methods plus "finder" functions for each locking method.
25215 **   *  sqlite3_vfs method implementations.
25216 **   *  Locking primitives for the proxy uber-locking-method. (MacOSX only)
25217 **   *  Definitions of sqlite3_vfs objects for all locking methods
25218 **      plus implementations of sqlite3_os_init() and sqlite3_os_end().
25219 */
25220 #if SQLITE_OS_UNIX              /* This file is used on unix only */
25221
25222 /*
25223 ** There are various methods for file locking used for concurrency
25224 ** control:
25225 **
25226 **   1. POSIX locking (the default),
25227 **   2. No locking,
25228 **   3. Dot-file locking,
25229 **   4. flock() locking,
25230 **   5. AFP locking (OSX only),
25231 **   6. Named POSIX semaphores (VXWorks only),
25232 **   7. proxy locking. (OSX only)
25233 **
25234 ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
25235 ** is defined to 1.  The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
25236 ** selection of the appropriate locking style based on the filesystem
25237 ** where the database is located.  
25238 */
25239 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
25240 #  if defined(__APPLE__)
25241 #    define SQLITE_ENABLE_LOCKING_STYLE 1
25242 #  else
25243 #    define SQLITE_ENABLE_LOCKING_STYLE 0
25244 #  endif
25245 #endif
25246
25247 /*
25248 ** standard include files.
25249 */
25250 #include <sys/types.h>
25251 #include <sys/stat.h>
25252 #include <fcntl.h>
25253 #include <unistd.h>
25254 /* #include <time.h> */
25255 #include <sys/time.h>
25256 #include <errno.h>
25257 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
25258 # include <sys/mman.h>
25259 #endif
25260
25261 #if SQLITE_ENABLE_LOCKING_STYLE
25262 # include <sys/ioctl.h>
25263 # include <sys/file.h>
25264 # include <sys/param.h>
25265 #endif /* SQLITE_ENABLE_LOCKING_STYLE */
25266
25267 #if OS_VXWORKS
25268 /* # include <sys/ioctl.h> */
25269 # include <semaphore.h>
25270 # include <limits.h>
25271 #endif /* OS_VXWORKS */
25272
25273 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
25274 # include <sys/mount.h>
25275 #endif
25276
25277 #ifdef HAVE_UTIME
25278 # include <utime.h>
25279 #endif
25280
25281 /*
25282 ** Allowed values of unixFile.fsFlags
25283 */
25284 #define SQLITE_FSFLAGS_IS_MSDOS     0x1
25285
25286 /*
25287 ** If we are to be thread-safe, include the pthreads header and define
25288 ** the SQLITE_UNIX_THREADS macro.
25289 */
25290 #if SQLITE_THREADSAFE
25291 /* # include <pthread.h> */
25292 # define SQLITE_UNIX_THREADS 1
25293 #endif
25294
25295 /*
25296 ** Default permissions when creating a new file
25297 */
25298 #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
25299 # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
25300 #endif
25301
25302 /*
25303 ** Default permissions when creating auto proxy dir
25304 */
25305 #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
25306 # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
25307 #endif
25308
25309 /*
25310 ** Maximum supported path-length.
25311 */
25312 #define MAX_PATHNAME 512
25313
25314 /* Always cast the getpid() return type for compatibility with
25315 ** kernel modules in VxWorks. */
25316 #define osGetpid(X) (pid_t)getpid()
25317
25318 /*
25319 ** Only set the lastErrno if the error code is a real error and not 
25320 ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
25321 */
25322 #define IS_LOCK_ERROR(x)  ((x != SQLITE_OK) && (x != SQLITE_BUSY))
25323
25324 /* Forward references */
25325 typedef struct unixShm unixShm;               /* Connection shared memory */
25326 typedef struct unixShmNode unixShmNode;       /* Shared memory instance */
25327 typedef struct unixInodeInfo unixInodeInfo;   /* An i-node */
25328 typedef struct UnixUnusedFd UnixUnusedFd;     /* An unused file descriptor */
25329
25330 /*
25331 ** Sometimes, after a file handle is closed by SQLite, the file descriptor
25332 ** cannot be closed immediately. In these cases, instances of the following
25333 ** structure are used to store the file descriptor while waiting for an
25334 ** opportunity to either close or reuse it.
25335 */
25336 struct UnixUnusedFd {
25337   int fd;                   /* File descriptor to close */
25338   int flags;                /* Flags this file descriptor was opened with */
25339   UnixUnusedFd *pNext;      /* Next unused file descriptor on same file */
25340 };
25341
25342 /*
25343 ** The unixFile structure is subclass of sqlite3_file specific to the unix
25344 ** VFS implementations.
25345 */
25346 typedef struct unixFile unixFile;
25347 struct unixFile {
25348   sqlite3_io_methods const *pMethod;  /* Always the first entry */
25349   sqlite3_vfs *pVfs;                  /* The VFS that created this unixFile */
25350   unixInodeInfo *pInode;              /* Info about locks on this inode */
25351   int h;                              /* The file descriptor */
25352   unsigned char eFileLock;            /* The type of lock held on this fd */
25353   unsigned short int ctrlFlags;       /* Behavioral bits.  UNIXFILE_* flags */
25354   int lastErrno;                      /* The unix errno from last I/O error */
25355   void *lockingContext;               /* Locking style specific state */
25356   UnixUnusedFd *pUnused;              /* Pre-allocated UnixUnusedFd */
25357   const char *zPath;                  /* Name of the file */
25358   unixShm *pShm;                      /* Shared memory segment information */
25359   int szChunk;                        /* Configured by FCNTL_CHUNK_SIZE */
25360 #if SQLITE_MAX_MMAP_SIZE>0
25361   int nFetchOut;                      /* Number of outstanding xFetch refs */
25362   sqlite3_int64 mmapSize;             /* Usable size of mapping at pMapRegion */
25363   sqlite3_int64 mmapSizeActual;       /* Actual size of mapping at pMapRegion */
25364   sqlite3_int64 mmapSizeMax;          /* Configured FCNTL_MMAP_SIZE value */
25365   void *pMapRegion;                   /* Memory mapped region */
25366 #endif
25367 #ifdef __QNXNTO__
25368   int sectorSize;                     /* Device sector size */
25369   int deviceCharacteristics;          /* Precomputed device characteristics */
25370 #endif
25371 #if SQLITE_ENABLE_LOCKING_STYLE
25372   int openFlags;                      /* The flags specified at open() */
25373 #endif
25374 #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
25375   unsigned fsFlags;                   /* cached details from statfs() */
25376 #endif
25377 #if OS_VXWORKS
25378   struct vxworksFileId *pId;          /* Unique file ID */
25379 #endif
25380 #ifdef SQLITE_DEBUG
25381   /* The next group of variables are used to track whether or not the
25382   ** transaction counter in bytes 24-27 of database files are updated
25383   ** whenever any part of the database changes.  An assertion fault will
25384   ** occur if a file is updated without also updating the transaction
25385   ** counter.  This test is made to avoid new problems similar to the
25386   ** one described by ticket #3584. 
25387   */
25388   unsigned char transCntrChng;   /* True if the transaction counter changed */
25389   unsigned char dbUpdate;        /* True if any part of database file changed */
25390   unsigned char inNormalWrite;   /* True if in a normal write operation */
25391
25392 #endif
25393
25394 #ifdef SQLITE_TEST
25395   /* In test mode, increase the size of this structure a bit so that 
25396   ** it is larger than the struct CrashFile defined in test6.c.
25397   */
25398   char aPadding[32];
25399 #endif
25400 };
25401
25402 /* This variable holds the process id (pid) from when the xRandomness()
25403 ** method was called.  If xOpen() is called from a different process id,
25404 ** indicating that a fork() has occurred, the PRNG will be reset.
25405 */
25406 static pid_t randomnessPid = 0;
25407
25408 /*
25409 ** Allowed values for the unixFile.ctrlFlags bitmask:
25410 */
25411 #define UNIXFILE_EXCL        0x01     /* Connections from one process only */
25412 #define UNIXFILE_RDONLY      0x02     /* Connection is read only */
25413 #define UNIXFILE_PERSIST_WAL 0x04     /* Persistent WAL mode */
25414 #ifndef SQLITE_DISABLE_DIRSYNC
25415 # define UNIXFILE_DIRSYNC    0x08     /* Directory sync needed */
25416 #else
25417 # define UNIXFILE_DIRSYNC    0x00
25418 #endif
25419 #define UNIXFILE_PSOW        0x10     /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
25420 #define UNIXFILE_DELETE      0x20     /* Delete on close */
25421 #define UNIXFILE_URI         0x40     /* Filename might have query parameters */
25422 #define UNIXFILE_NOLOCK      0x80     /* Do no file locking */
25423 #define UNIXFILE_WARNED    0x0100     /* verifyDbFile() warnings issued */
25424 #define UNIXFILE_BLOCK     0x0200     /* Next SHM lock might block */
25425
25426 /*
25427 ** Include code that is common to all os_*.c files
25428 */
25429 /************** Include os_common.h in the middle of os_unix.c ***************/
25430 /************** Begin file os_common.h ***************************************/
25431 /*
25432 ** 2004 May 22
25433 **
25434 ** The author disclaims copyright to this source code.  In place of
25435 ** a legal notice, here is a blessing:
25436 **
25437 **    May you do good and not evil.
25438 **    May you find forgiveness for yourself and forgive others.
25439 **    May you share freely, never taking more than you give.
25440 **
25441 ******************************************************************************
25442 **
25443 ** This file contains macros and a little bit of code that is common to
25444 ** all of the platform-specific files (os_*.c) and is #included into those
25445 ** files.
25446 **
25447 ** This file should be #included by the os_*.c files only.  It is not a
25448 ** general purpose header file.
25449 */
25450 #ifndef _OS_COMMON_H_
25451 #define _OS_COMMON_H_
25452
25453 /*
25454 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
25455 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
25456 ** switch.  The following code should catch this problem at compile-time.
25457 */
25458 #ifdef MEMORY_DEBUG
25459 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
25460 #endif
25461
25462 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
25463 # ifndef SQLITE_DEBUG_OS_TRACE
25464 #   define SQLITE_DEBUG_OS_TRACE 0
25465 # endif
25466   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
25467 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
25468 #else
25469 # define OSTRACE(X)
25470 #endif
25471
25472 /*
25473 ** Macros for performance tracing.  Normally turned off.  Only works
25474 ** on i486 hardware.
25475 */
25476 #ifdef SQLITE_PERFORMANCE_TRACE
25477
25478 /* 
25479 ** hwtime.h contains inline assembler code for implementing 
25480 ** high-performance timing routines.
25481 */
25482 /************** Include hwtime.h in the middle of os_common.h ****************/
25483 /************** Begin file hwtime.h ******************************************/
25484 /*
25485 ** 2008 May 27
25486 **
25487 ** The author disclaims copyright to this source code.  In place of
25488 ** a legal notice, here is a blessing:
25489 **
25490 **    May you do good and not evil.
25491 **    May you find forgiveness for yourself and forgive others.
25492 **    May you share freely, never taking more than you give.
25493 **
25494 ******************************************************************************
25495 **
25496 ** This file contains inline asm code for retrieving "high-performance"
25497 ** counters for x86 class CPUs.
25498 */
25499 #ifndef _HWTIME_H_
25500 #define _HWTIME_H_
25501
25502 /*
25503 ** The following routine only works on pentium-class (or newer) processors.
25504 ** It uses the RDTSC opcode to read the cycle count value out of the
25505 ** processor and returns that value.  This can be used for high-res
25506 ** profiling.
25507 */
25508 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
25509       (defined(i386) || defined(__i386__) || defined(_M_IX86))
25510
25511   #if defined(__GNUC__)
25512
25513   __inline__ sqlite_uint64 sqlite3Hwtime(void){
25514      unsigned int lo, hi;
25515      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
25516      return (sqlite_uint64)hi << 32 | lo;
25517   }
25518
25519   #elif defined(_MSC_VER)
25520
25521   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
25522      __asm {
25523         rdtsc
25524         ret       ; return value at EDX:EAX
25525      }
25526   }
25527
25528   #endif
25529
25530 #elif (defined(__GNUC__) && defined(__x86_64__))
25531
25532   __inline__ sqlite_uint64 sqlite3Hwtime(void){
25533       unsigned long val;
25534       __asm__ __volatile__ ("rdtsc" : "=A" (val));
25535       return val;
25536   }
25537  
25538 #elif (defined(__GNUC__) && defined(__ppc__))
25539
25540   __inline__ sqlite_uint64 sqlite3Hwtime(void){
25541       unsigned long long retval;
25542       unsigned long junk;
25543       __asm__ __volatile__ ("\n\
25544           1:      mftbu   %1\n\
25545                   mftb    %L0\n\
25546                   mftbu   %0\n\
25547                   cmpw    %0,%1\n\
25548                   bne     1b"
25549                   : "=r" (retval), "=r" (junk));
25550       return retval;
25551   }
25552
25553 #else
25554
25555   #error Need implementation of sqlite3Hwtime() for your platform.
25556
25557   /*
25558   ** To compile without implementing sqlite3Hwtime() for your platform,
25559   ** you can remove the above #error and use the following
25560   ** stub function.  You will lose timing support for many
25561   ** of the debugging and testing utilities, but it should at
25562   ** least compile and run.
25563   */
25564 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
25565
25566 #endif
25567
25568 #endif /* !defined(_HWTIME_H_) */
25569
25570 /************** End of hwtime.h **********************************************/
25571 /************** Continuing where we left off in os_common.h ******************/
25572
25573 static sqlite_uint64 g_start;
25574 static sqlite_uint64 g_elapsed;
25575 #define TIMER_START       g_start=sqlite3Hwtime()
25576 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
25577 #define TIMER_ELAPSED     g_elapsed
25578 #else
25579 #define TIMER_START
25580 #define TIMER_END
25581 #define TIMER_ELAPSED     ((sqlite_uint64)0)
25582 #endif
25583
25584 /*
25585 ** If we compile with the SQLITE_TEST macro set, then the following block
25586 ** of code will give us the ability to simulate a disk I/O error.  This
25587 ** is used for testing the I/O recovery logic.
25588 */
25589 #ifdef SQLITE_TEST
25590 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
25591 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
25592 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
25593 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
25594 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
25595 SQLITE_API int sqlite3_diskfull_pending = 0;
25596 SQLITE_API int sqlite3_diskfull = 0;
25597 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
25598 #define SimulateIOError(CODE)  \
25599   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
25600        || sqlite3_io_error_pending-- == 1 )  \
25601               { local_ioerr(); CODE; }
25602 static void local_ioerr(){
25603   IOTRACE(("IOERR\n"));
25604   sqlite3_io_error_hit++;
25605   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
25606 }
25607 #define SimulateDiskfullError(CODE) \
25608    if( sqlite3_diskfull_pending ){ \
25609      if( sqlite3_diskfull_pending == 1 ){ \
25610        local_ioerr(); \
25611        sqlite3_diskfull = 1; \
25612        sqlite3_io_error_hit = 1; \
25613        CODE; \
25614      }else{ \
25615        sqlite3_diskfull_pending--; \
25616      } \
25617    }
25618 #else
25619 #define SimulateIOErrorBenign(X)
25620 #define SimulateIOError(A)
25621 #define SimulateDiskfullError(A)
25622 #endif
25623
25624 /*
25625 ** When testing, keep a count of the number of open files.
25626 */
25627 #ifdef SQLITE_TEST
25628 SQLITE_API int sqlite3_open_file_count = 0;
25629 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
25630 #else
25631 #define OpenCounter(X)
25632 #endif
25633
25634 #endif /* !defined(_OS_COMMON_H_) */
25635
25636 /************** End of os_common.h *******************************************/
25637 /************** Continuing where we left off in os_unix.c ********************/
25638
25639 /*
25640 ** Define various macros that are missing from some systems.
25641 */
25642 #ifndef O_LARGEFILE
25643 # define O_LARGEFILE 0
25644 #endif
25645 #ifdef SQLITE_DISABLE_LFS
25646 # undef O_LARGEFILE
25647 # define O_LARGEFILE 0
25648 #endif
25649 #ifndef O_NOFOLLOW
25650 # define O_NOFOLLOW 0
25651 #endif
25652 #ifndef O_BINARY
25653 # define O_BINARY 0
25654 #endif
25655
25656 /*
25657 ** The threadid macro resolves to the thread-id or to 0.  Used for
25658 ** testing and debugging only.
25659 */
25660 #if SQLITE_THREADSAFE
25661 #define threadid pthread_self()
25662 #else
25663 #define threadid 0
25664 #endif
25665
25666 /*
25667 ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
25668 */
25669 #if !defined(HAVE_MREMAP)
25670 # if defined(__linux__) && defined(_GNU_SOURCE)
25671 #  define HAVE_MREMAP 1
25672 # else
25673 #  define HAVE_MREMAP 0
25674 # endif
25675 #endif
25676
25677 /*
25678 ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
25679 ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
25680 */
25681 #ifdef __ANDROID__
25682 # define lseek lseek64
25683 #endif
25684
25685 /*
25686 ** Different Unix systems declare open() in different ways.  Same use
25687 ** open(const char*,int,mode_t).  Others use open(const char*,int,...).
25688 ** The difference is important when using a pointer to the function.
25689 **
25690 ** The safest way to deal with the problem is to always use this wrapper
25691 ** which always has the same well-defined interface.
25692 */
25693 static int posixOpen(const char *zFile, int flags, int mode){
25694   return open(zFile, flags, mode);
25695 }
25696
25697 /*
25698 ** On some systems, calls to fchown() will trigger a message in a security
25699 ** log if they come from non-root processes.  So avoid calling fchown() if
25700 ** we are not running as root.
25701 */
25702 static int posixFchown(int fd, uid_t uid, gid_t gid){
25703 #if OS_VXWORKS
25704   return 0;
25705 #else
25706   return geteuid() ? 0 : fchown(fd,uid,gid);
25707 #endif
25708 }
25709
25710 /* Forward reference */
25711 static int openDirectory(const char*, int*);
25712 static int unixGetpagesize(void);
25713
25714 /*
25715 ** Many system calls are accessed through pointer-to-functions so that
25716 ** they may be overridden at runtime to facilitate fault injection during
25717 ** testing and sandboxing.  The following array holds the names and pointers
25718 ** to all overrideable system calls.
25719 */
25720 static struct unix_syscall {
25721   const char *zName;            /* Name of the system call */
25722   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
25723   sqlite3_syscall_ptr pDefault; /* Default value */
25724 } aSyscall[] = {
25725   { "open",         (sqlite3_syscall_ptr)posixOpen,  0  },
25726 #define osOpen      ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
25727
25728   { "close",        (sqlite3_syscall_ptr)close,      0  },
25729 #define osClose     ((int(*)(int))aSyscall[1].pCurrent)
25730
25731   { "access",       (sqlite3_syscall_ptr)access,     0  },
25732 #define osAccess    ((int(*)(const char*,int))aSyscall[2].pCurrent)
25733
25734   { "getcwd",       (sqlite3_syscall_ptr)getcwd,     0  },
25735 #define osGetcwd    ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
25736
25737   { "stat",         (sqlite3_syscall_ptr)stat,       0  },
25738 #define osStat      ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
25739
25740 /*
25741 ** The DJGPP compiler environment looks mostly like Unix, but it
25742 ** lacks the fcntl() system call.  So redefine fcntl() to be something
25743 ** that always succeeds.  This means that locking does not occur under
25744 ** DJGPP.  But it is DOS - what did you expect?
25745 */
25746 #ifdef __DJGPP__
25747   { "fstat",        0,                 0  },
25748 #define osFstat(a,b,c)    0
25749 #else     
25750   { "fstat",        (sqlite3_syscall_ptr)fstat,      0  },
25751 #define osFstat     ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
25752 #endif
25753
25754   { "ftruncate",    (sqlite3_syscall_ptr)ftruncate,  0  },
25755 #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
25756
25757   { "fcntl",        (sqlite3_syscall_ptr)fcntl,      0  },
25758 #define osFcntl     ((int(*)(int,int,...))aSyscall[7].pCurrent)
25759
25760   { "read",         (sqlite3_syscall_ptr)read,       0  },
25761 #define osRead      ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
25762
25763 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
25764   { "pread",        (sqlite3_syscall_ptr)pread,      0  },
25765 #else
25766   { "pread",        (sqlite3_syscall_ptr)0,          0  },
25767 #endif
25768 #define osPread     ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
25769
25770 #if defined(USE_PREAD64)
25771   { "pread64",      (sqlite3_syscall_ptr)pread64,    0  },
25772 #else
25773   { "pread64",      (sqlite3_syscall_ptr)0,          0  },
25774 #endif
25775 #define osPread64   ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
25776
25777   { "write",        (sqlite3_syscall_ptr)write,      0  },
25778 #define osWrite     ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
25779
25780 #if defined(USE_PREAD) || SQLITE_ENABLE_LOCKING_STYLE
25781   { "pwrite",       (sqlite3_syscall_ptr)pwrite,     0  },
25782 #else
25783   { "pwrite",       (sqlite3_syscall_ptr)0,          0  },
25784 #endif
25785 #define osPwrite    ((ssize_t(*)(int,const void*,size_t,off_t))\
25786                     aSyscall[12].pCurrent)
25787
25788 #if defined(USE_PREAD64)
25789   { "pwrite64",     (sqlite3_syscall_ptr)pwrite64,   0  },
25790 #else
25791   { "pwrite64",     (sqlite3_syscall_ptr)0,          0  },
25792 #endif
25793 #define osPwrite64  ((ssize_t(*)(int,const void*,size_t,off_t))\
25794                     aSyscall[13].pCurrent)
25795
25796   { "fchmod",       (sqlite3_syscall_ptr)fchmod,     0  },
25797 #define osFchmod    ((int(*)(int,mode_t))aSyscall[14].pCurrent)
25798
25799 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
25800   { "fallocate",    (sqlite3_syscall_ptr)posix_fallocate,  0 },
25801 #else
25802   { "fallocate",    (sqlite3_syscall_ptr)0,                0 },
25803 #endif
25804 #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
25805
25806   { "unlink",       (sqlite3_syscall_ptr)unlink,           0 },
25807 #define osUnlink    ((int(*)(const char*))aSyscall[16].pCurrent)
25808
25809   { "openDirectory",    (sqlite3_syscall_ptr)openDirectory,      0 },
25810 #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
25811
25812   { "mkdir",        (sqlite3_syscall_ptr)mkdir,           0 },
25813 #define osMkdir     ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
25814
25815   { "rmdir",        (sqlite3_syscall_ptr)rmdir,           0 },
25816 #define osRmdir     ((int(*)(const char*))aSyscall[19].pCurrent)
25817
25818   { "fchown",       (sqlite3_syscall_ptr)posixFchown,     0 },
25819 #define osFchown    ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
25820
25821 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
25822   { "mmap",       (sqlite3_syscall_ptr)mmap,     0 },
25823 #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
25824
25825   { "munmap",       (sqlite3_syscall_ptr)munmap,          0 },
25826 #define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
25827
25828 #if HAVE_MREMAP
25829   { "mremap",       (sqlite3_syscall_ptr)mremap,          0 },
25830 #else
25831   { "mremap",       (sqlite3_syscall_ptr)0,               0 },
25832 #endif
25833 #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
25834   { "getpagesize",  (sqlite3_syscall_ptr)unixGetpagesize, 0 },
25835 #define osGetpagesize ((int(*)(void))aSyscall[24].pCurrent)
25836
25837 #endif
25838
25839 }; /* End of the overrideable system calls */
25840
25841 /*
25842 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
25843 ** "unix" VFSes.  Return SQLITE_OK opon successfully updating the
25844 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
25845 ** system call named zName.
25846 */
25847 static int unixSetSystemCall(
25848   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
25849   const char *zName,            /* Name of system call to override */
25850   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
25851 ){
25852   unsigned int i;
25853   int rc = SQLITE_NOTFOUND;
25854
25855   UNUSED_PARAMETER(pNotUsed);
25856   if( zName==0 ){
25857     /* If no zName is given, restore all system calls to their default
25858     ** settings and return NULL
25859     */
25860     rc = SQLITE_OK;
25861     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25862       if( aSyscall[i].pDefault ){
25863         aSyscall[i].pCurrent = aSyscall[i].pDefault;
25864       }
25865     }
25866   }else{
25867     /* If zName is specified, operate on only the one system call
25868     ** specified.
25869     */
25870     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25871       if( strcmp(zName, aSyscall[i].zName)==0 ){
25872         if( aSyscall[i].pDefault==0 ){
25873           aSyscall[i].pDefault = aSyscall[i].pCurrent;
25874         }
25875         rc = SQLITE_OK;
25876         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
25877         aSyscall[i].pCurrent = pNewFunc;
25878         break;
25879       }
25880     }
25881   }
25882   return rc;
25883 }
25884
25885 /*
25886 ** Return the value of a system call.  Return NULL if zName is not a
25887 ** recognized system call name.  NULL is also returned if the system call
25888 ** is currently undefined.
25889 */
25890 static sqlite3_syscall_ptr unixGetSystemCall(
25891   sqlite3_vfs *pNotUsed,
25892   const char *zName
25893 ){
25894   unsigned int i;
25895
25896   UNUSED_PARAMETER(pNotUsed);
25897   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
25898     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
25899   }
25900   return 0;
25901 }
25902
25903 /*
25904 ** Return the name of the first system call after zName.  If zName==NULL
25905 ** then return the name of the first system call.  Return NULL if zName
25906 ** is the last system call or if zName is not the name of a valid
25907 ** system call.
25908 */
25909 static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
25910   int i = -1;
25911
25912   UNUSED_PARAMETER(p);
25913   if( zName ){
25914     for(i=0; i<ArraySize(aSyscall)-1; i++){
25915       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
25916     }
25917   }
25918   for(i++; i<ArraySize(aSyscall); i++){
25919     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
25920   }
25921   return 0;
25922 }
25923
25924 /*
25925 ** Do not accept any file descriptor less than this value, in order to avoid
25926 ** opening database file using file descriptors that are commonly used for 
25927 ** standard input, output, and error.
25928 */
25929 #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
25930 # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
25931 #endif
25932
25933 /*
25934 ** Invoke open().  Do so multiple times, until it either succeeds or
25935 ** fails for some reason other than EINTR.
25936 **
25937 ** If the file creation mode "m" is 0 then set it to the default for
25938 ** SQLite.  The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
25939 ** 0644) as modified by the system umask.  If m is not 0, then
25940 ** make the file creation mode be exactly m ignoring the umask.
25941 **
25942 ** The m parameter will be non-zero only when creating -wal, -journal,
25943 ** and -shm files.  We want those files to have *exactly* the same
25944 ** permissions as their original database, unadulterated by the umask.
25945 ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
25946 ** transaction crashes and leaves behind hot journals, then any
25947 ** process that is able to write to the database will also be able to
25948 ** recover the hot journals.
25949 */
25950 static int robust_open(const char *z, int f, mode_t m){
25951   int fd;
25952   mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
25953   while(1){
25954 #if defined(O_CLOEXEC)
25955     fd = osOpen(z,f|O_CLOEXEC,m2);
25956 #else
25957     fd = osOpen(z,f,m2);
25958 #endif
25959     if( fd<0 ){
25960       if( errno==EINTR ) continue;
25961       break;
25962     }
25963     if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
25964     osClose(fd);
25965     sqlite3_log(SQLITE_WARNING, 
25966                 "attempt to open \"%s\" as file descriptor %d", z, fd);
25967     fd = -1;
25968     if( osOpen("/dev/null", f, m)<0 ) break;
25969   }
25970   if( fd>=0 ){
25971     if( m!=0 ){
25972       struct stat statbuf;
25973       if( osFstat(fd, &statbuf)==0 
25974        && statbuf.st_size==0
25975        && (statbuf.st_mode&0777)!=m 
25976       ){
25977         osFchmod(fd, m);
25978       }
25979     }
25980 #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
25981     osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
25982 #endif
25983   }
25984   return fd;
25985 }
25986
25987 /*
25988 ** Helper functions to obtain and relinquish the global mutex. The
25989 ** global mutex is used to protect the unixInodeInfo and
25990 ** vxworksFileId objects used by this file, all of which may be 
25991 ** shared by multiple threads.
25992 **
25993 ** Function unixMutexHeld() is used to assert() that the global mutex 
25994 ** is held when required. This function is only used as part of assert() 
25995 ** statements. e.g.
25996 **
25997 **   unixEnterMutex()
25998 **     assert( unixMutexHeld() );
25999 **   unixEnterLeave()
26000 */
26001 static void unixEnterMutex(void){
26002   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
26003 }
26004 static void unixLeaveMutex(void){
26005   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
26006 }
26007 #ifdef SQLITE_DEBUG
26008 static int unixMutexHeld(void) {
26009   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
26010 }
26011 #endif
26012
26013
26014 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
26015 /*
26016 ** Helper function for printing out trace information from debugging
26017 ** binaries. This returns the string representation of the supplied
26018 ** integer lock-type.
26019 */
26020 static const char *azFileLock(int eFileLock){
26021   switch( eFileLock ){
26022     case NO_LOCK: return "NONE";
26023     case SHARED_LOCK: return "SHARED";
26024     case RESERVED_LOCK: return "RESERVED";
26025     case PENDING_LOCK: return "PENDING";
26026     case EXCLUSIVE_LOCK: return "EXCLUSIVE";
26027   }
26028   return "ERROR";
26029 }
26030 #endif
26031
26032 #ifdef SQLITE_LOCK_TRACE
26033 /*
26034 ** Print out information about all locking operations.
26035 **
26036 ** This routine is used for troubleshooting locks on multithreaded
26037 ** platforms.  Enable by compiling with the -DSQLITE_LOCK_TRACE
26038 ** command-line option on the compiler.  This code is normally
26039 ** turned off.
26040 */
26041 static int lockTrace(int fd, int op, struct flock *p){
26042   char *zOpName, *zType;
26043   int s;
26044   int savedErrno;
26045   if( op==F_GETLK ){
26046     zOpName = "GETLK";
26047   }else if( op==F_SETLK ){
26048     zOpName = "SETLK";
26049   }else{
26050     s = osFcntl(fd, op, p);
26051     sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
26052     return s;
26053   }
26054   if( p->l_type==F_RDLCK ){
26055     zType = "RDLCK";
26056   }else if( p->l_type==F_WRLCK ){
26057     zType = "WRLCK";
26058   }else if( p->l_type==F_UNLCK ){
26059     zType = "UNLCK";
26060   }else{
26061     assert( 0 );
26062   }
26063   assert( p->l_whence==SEEK_SET );
26064   s = osFcntl(fd, op, p);
26065   savedErrno = errno;
26066   sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
26067      threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
26068      (int)p->l_pid, s);
26069   if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
26070     struct flock l2;
26071     l2 = *p;
26072     osFcntl(fd, F_GETLK, &l2);
26073     if( l2.l_type==F_RDLCK ){
26074       zType = "RDLCK";
26075     }else if( l2.l_type==F_WRLCK ){
26076       zType = "WRLCK";
26077     }else if( l2.l_type==F_UNLCK ){
26078       zType = "UNLCK";
26079     }else{
26080       assert( 0 );
26081     }
26082     sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
26083        zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
26084   }
26085   errno = savedErrno;
26086   return s;
26087 }
26088 #undef osFcntl
26089 #define osFcntl lockTrace
26090 #endif /* SQLITE_LOCK_TRACE */
26091
26092 /*
26093 ** Retry ftruncate() calls that fail due to EINTR
26094 **
26095 ** All calls to ftruncate() within this file should be made through
26096 ** this wrapper.  On the Android platform, bypassing the logic below
26097 ** could lead to a corrupt database.
26098 */
26099 static int robust_ftruncate(int h, sqlite3_int64 sz){
26100   int rc;
26101 #ifdef __ANDROID__
26102   /* On Android, ftruncate() always uses 32-bit offsets, even if 
26103   ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
26104   ** truncate a file to any size larger than 2GiB. Silently ignore any
26105   ** such attempts.  */
26106   if( sz>(sqlite3_int64)0x7FFFFFFF ){
26107     rc = SQLITE_OK;
26108   }else
26109 #endif
26110   do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
26111   return rc;
26112 }
26113
26114 /*
26115 ** This routine translates a standard POSIX errno code into something
26116 ** useful to the clients of the sqlite3 functions.  Specifically, it is
26117 ** intended to translate a variety of "try again" errors into SQLITE_BUSY
26118 ** and a variety of "please close the file descriptor NOW" errors into 
26119 ** SQLITE_IOERR
26120 ** 
26121 ** Errors during initialization of locks, or file system support for locks,
26122 ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
26123 */
26124 static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
26125   switch (posixError) {
26126 #if 0
26127   /* At one point this code was not commented out. In theory, this branch
26128   ** should never be hit, as this function should only be called after
26129   ** a locking-related function (i.e. fcntl()) has returned non-zero with
26130   ** the value of errno as the first argument. Since a system call has failed,
26131   ** errno should be non-zero.
26132   **
26133   ** Despite this, if errno really is zero, we still don't want to return
26134   ** SQLITE_OK. The system call failed, and *some* SQLite error should be
26135   ** propagated back to the caller. Commenting this branch out means errno==0
26136   ** will be handled by the "default:" case below.
26137   */
26138   case 0: 
26139     return SQLITE_OK;
26140 #endif
26141
26142   case EAGAIN:
26143   case ETIMEDOUT:
26144   case EBUSY:
26145   case EINTR:
26146   case ENOLCK:  
26147     /* random NFS retry error, unless during file system support 
26148      * introspection, in which it actually means what it says */
26149     return SQLITE_BUSY;
26150     
26151   case EACCES: 
26152     /* EACCES is like EAGAIN during locking operations, but not any other time*/
26153     if( (sqliteIOErr == SQLITE_IOERR_LOCK) || 
26154         (sqliteIOErr == SQLITE_IOERR_UNLOCK) || 
26155         (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
26156         (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
26157       return SQLITE_BUSY;
26158     }
26159     /* else fall through */
26160   case EPERM: 
26161     return SQLITE_PERM;
26162     
26163 #if EOPNOTSUPP!=ENOTSUP
26164   case EOPNOTSUPP: 
26165     /* something went terribly awry, unless during file system support 
26166      * introspection, in which it actually means what it says */
26167 #endif
26168 #ifdef ENOTSUP
26169   case ENOTSUP: 
26170     /* invalid fd, unless during file system support introspection, in which 
26171      * it actually means what it says */
26172 #endif
26173   case EIO:
26174   case EBADF:
26175   case EINVAL:
26176   case ENOTCONN:
26177   case ENODEV:
26178   case ENXIO:
26179   case ENOENT:
26180 #ifdef ESTALE                     /* ESTALE is not defined on Interix systems */
26181   case ESTALE:
26182 #endif
26183   case ENOSYS:
26184     /* these should force the client to close the file and reconnect */
26185     
26186   default: 
26187     return sqliteIOErr;
26188   }
26189 }
26190
26191
26192 /******************************************************************************
26193 ****************** Begin Unique File ID Utility Used By VxWorks ***************
26194 **
26195 ** On most versions of unix, we can get a unique ID for a file by concatenating
26196 ** the device number and the inode number.  But this does not work on VxWorks.
26197 ** On VxWorks, a unique file id must be based on the canonical filename.
26198 **
26199 ** A pointer to an instance of the following structure can be used as a
26200 ** unique file ID in VxWorks.  Each instance of this structure contains
26201 ** a copy of the canonical filename.  There is also a reference count.  
26202 ** The structure is reclaimed when the number of pointers to it drops to
26203 ** zero.
26204 **
26205 ** There are never very many files open at one time and lookups are not
26206 ** a performance-critical path, so it is sufficient to put these
26207 ** structures on a linked list.
26208 */
26209 struct vxworksFileId {
26210   struct vxworksFileId *pNext;  /* Next in a list of them all */
26211   int nRef;                     /* Number of references to this one */
26212   int nName;                    /* Length of the zCanonicalName[] string */
26213   char *zCanonicalName;         /* Canonical filename */
26214 };
26215
26216 #if OS_VXWORKS
26217 /* 
26218 ** All unique filenames are held on a linked list headed by this
26219 ** variable:
26220 */
26221 static struct vxworksFileId *vxworksFileList = 0;
26222
26223 /*
26224 ** Simplify a filename into its canonical form
26225 ** by making the following changes:
26226 **
26227 **  * removing any trailing and duplicate /
26228 **  * convert /./ into just /
26229 **  * convert /A/../ where A is any simple name into just /
26230 **
26231 ** Changes are made in-place.  Return the new name length.
26232 **
26233 ** The original filename is in z[0..n-1].  Return the number of
26234 ** characters in the simplified name.
26235 */
26236 static int vxworksSimplifyName(char *z, int n){
26237   int i, j;
26238   while( n>1 && z[n-1]=='/' ){ n--; }
26239   for(i=j=0; i<n; i++){
26240     if( z[i]=='/' ){
26241       if( z[i+1]=='/' ) continue;
26242       if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
26243         i += 1;
26244         continue;
26245       }
26246       if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
26247         while( j>0 && z[j-1]!='/' ){ j--; }
26248         if( j>0 ){ j--; }
26249         i += 2;
26250         continue;
26251       }
26252     }
26253     z[j++] = z[i];
26254   }
26255   z[j] = 0;
26256   return j;
26257 }
26258
26259 /*
26260 ** Find a unique file ID for the given absolute pathname.  Return
26261 ** a pointer to the vxworksFileId object.  This pointer is the unique
26262 ** file ID.
26263 **
26264 ** The nRef field of the vxworksFileId object is incremented before
26265 ** the object is returned.  A new vxworksFileId object is created
26266 ** and added to the global list if necessary.
26267 **
26268 ** If a memory allocation error occurs, return NULL.
26269 */
26270 static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
26271   struct vxworksFileId *pNew;         /* search key and new file ID */
26272   struct vxworksFileId *pCandidate;   /* For looping over existing file IDs */
26273   int n;                              /* Length of zAbsoluteName string */
26274
26275   assert( zAbsoluteName[0]=='/' );
26276   n = (int)strlen(zAbsoluteName);
26277   pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
26278   if( pNew==0 ) return 0;
26279   pNew->zCanonicalName = (char*)&pNew[1];
26280   memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
26281   n = vxworksSimplifyName(pNew->zCanonicalName, n);
26282
26283   /* Search for an existing entry that matching the canonical name.
26284   ** If found, increment the reference count and return a pointer to
26285   ** the existing file ID.
26286   */
26287   unixEnterMutex();
26288   for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
26289     if( pCandidate->nName==n 
26290      && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
26291     ){
26292        sqlite3_free(pNew);
26293        pCandidate->nRef++;
26294        unixLeaveMutex();
26295        return pCandidate;
26296     }
26297   }
26298
26299   /* No match was found.  We will make a new file ID */
26300   pNew->nRef = 1;
26301   pNew->nName = n;
26302   pNew->pNext = vxworksFileList;
26303   vxworksFileList = pNew;
26304   unixLeaveMutex();
26305   return pNew;
26306 }
26307
26308 /*
26309 ** Decrement the reference count on a vxworksFileId object.  Free
26310 ** the object when the reference count reaches zero.
26311 */
26312 static void vxworksReleaseFileId(struct vxworksFileId *pId){
26313   unixEnterMutex();
26314   assert( pId->nRef>0 );
26315   pId->nRef--;
26316   if( pId->nRef==0 ){
26317     struct vxworksFileId **pp;
26318     for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
26319     assert( *pp==pId );
26320     *pp = pId->pNext;
26321     sqlite3_free(pId);
26322   }
26323   unixLeaveMutex();
26324 }
26325 #endif /* OS_VXWORKS */
26326 /*************** End of Unique File ID Utility Used By VxWorks ****************
26327 ******************************************************************************/
26328
26329
26330 /******************************************************************************
26331 *************************** Posix Advisory Locking ****************************
26332 **
26333 ** POSIX advisory locks are broken by design.  ANSI STD 1003.1 (1996)
26334 ** section 6.5.2.2 lines 483 through 490 specify that when a process
26335 ** sets or clears a lock, that operation overrides any prior locks set
26336 ** by the same process.  It does not explicitly say so, but this implies
26337 ** that it overrides locks set by the same process using a different
26338 ** file descriptor.  Consider this test case:
26339 **
26340 **       int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
26341 **       int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
26342 **
26343 ** Suppose ./file1 and ./file2 are really the same file (because
26344 ** one is a hard or symbolic link to the other) then if you set
26345 ** an exclusive lock on fd1, then try to get an exclusive lock
26346 ** on fd2, it works.  I would have expected the second lock to
26347 ** fail since there was already a lock on the file due to fd1.
26348 ** But not so.  Since both locks came from the same process, the
26349 ** second overrides the first, even though they were on different
26350 ** file descriptors opened on different file names.
26351 **
26352 ** This means that we cannot use POSIX locks to synchronize file access
26353 ** among competing threads of the same process.  POSIX locks will work fine
26354 ** to synchronize access for threads in separate processes, but not
26355 ** threads within the same process.
26356 **
26357 ** To work around the problem, SQLite has to manage file locks internally
26358 ** on its own.  Whenever a new database is opened, we have to find the
26359 ** specific inode of the database file (the inode is determined by the
26360 ** st_dev and st_ino fields of the stat structure that fstat() fills in)
26361 ** and check for locks already existing on that inode.  When locks are
26362 ** created or removed, we have to look at our own internal record of the
26363 ** locks to see if another thread has previously set a lock on that same
26364 ** inode.
26365 **
26366 ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
26367 ** For VxWorks, we have to use the alternative unique ID system based on
26368 ** canonical filename and implemented in the previous division.)
26369 **
26370 ** The sqlite3_file structure for POSIX is no longer just an integer file
26371 ** descriptor.  It is now a structure that holds the integer file
26372 ** descriptor and a pointer to a structure that describes the internal
26373 ** locks on the corresponding inode.  There is one locking structure
26374 ** per inode, so if the same inode is opened twice, both unixFile structures
26375 ** point to the same locking structure.  The locking structure keeps
26376 ** a reference count (so we will know when to delete it) and a "cnt"
26377 ** field that tells us its internal lock status.  cnt==0 means the
26378 ** file is unlocked.  cnt==-1 means the file has an exclusive lock.
26379 ** cnt>0 means there are cnt shared locks on the file.
26380 **
26381 ** Any attempt to lock or unlock a file first checks the locking
26382 ** structure.  The fcntl() system call is only invoked to set a 
26383 ** POSIX lock if the internal lock structure transitions between
26384 ** a locked and an unlocked state.
26385 **
26386 ** But wait:  there are yet more problems with POSIX advisory locks.
26387 **
26388 ** If you close a file descriptor that points to a file that has locks,
26389 ** all locks on that file that are owned by the current process are
26390 ** released.  To work around this problem, each unixInodeInfo object
26391 ** maintains a count of the number of pending locks on tha inode.
26392 ** When an attempt is made to close an unixFile, if there are
26393 ** other unixFile open on the same inode that are holding locks, the call
26394 ** to close() the file descriptor is deferred until all of the locks clear.
26395 ** The unixInodeInfo structure keeps a list of file descriptors that need to
26396 ** be closed and that list is walked (and cleared) when the last lock
26397 ** clears.
26398 **
26399 ** Yet another problem:  LinuxThreads do not play well with posix locks.
26400 **
26401 ** Many older versions of linux use the LinuxThreads library which is
26402 ** not posix compliant.  Under LinuxThreads, a lock created by thread
26403 ** A cannot be modified or overridden by a different thread B.
26404 ** Only thread A can modify the lock.  Locking behavior is correct
26405 ** if the appliation uses the newer Native Posix Thread Library (NPTL)
26406 ** on linux - with NPTL a lock created by thread A can override locks
26407 ** in thread B.  But there is no way to know at compile-time which
26408 ** threading library is being used.  So there is no way to know at
26409 ** compile-time whether or not thread A can override locks on thread B.
26410 ** One has to do a run-time check to discover the behavior of the
26411 ** current process.
26412 **
26413 ** SQLite used to support LinuxThreads.  But support for LinuxThreads
26414 ** was dropped beginning with version 3.7.0.  SQLite will still work with
26415 ** LinuxThreads provided that (1) there is no more than one connection 
26416 ** per database file in the same process and (2) database connections
26417 ** do not move across threads.
26418 */
26419
26420 /*
26421 ** An instance of the following structure serves as the key used
26422 ** to locate a particular unixInodeInfo object.
26423 */
26424 struct unixFileId {
26425   dev_t dev;                  /* Device number */
26426 #if OS_VXWORKS
26427   struct vxworksFileId *pId;  /* Unique file ID for vxworks. */
26428 #else
26429   ino_t ino;                  /* Inode number */
26430 #endif
26431 };
26432
26433 /*
26434 ** An instance of the following structure is allocated for each open
26435 ** inode.  Or, on LinuxThreads, there is one of these structures for
26436 ** each inode opened by each thread.
26437 **
26438 ** A single inode can have multiple file descriptors, so each unixFile
26439 ** structure contains a pointer to an instance of this object and this
26440 ** object keeps a count of the number of unixFile pointing to it.
26441 */
26442 struct unixInodeInfo {
26443   struct unixFileId fileId;       /* The lookup key */
26444   int nShared;                    /* Number of SHARED locks held */
26445   unsigned char eFileLock;        /* One of SHARED_LOCK, RESERVED_LOCK etc. */
26446   unsigned char bProcessLock;     /* An exclusive process lock is held */
26447   int nRef;                       /* Number of pointers to this structure */
26448   unixShmNode *pShmNode;          /* Shared memory associated with this inode */
26449   int nLock;                      /* Number of outstanding file locks */
26450   UnixUnusedFd *pUnused;          /* Unused file descriptors to close */
26451   unixInodeInfo *pNext;           /* List of all unixInodeInfo objects */
26452   unixInodeInfo *pPrev;           /*    .... doubly linked */
26453 #if SQLITE_ENABLE_LOCKING_STYLE
26454   unsigned long long sharedByte;  /* for AFP simulated shared lock */
26455 #endif
26456 #if OS_VXWORKS
26457   sem_t *pSem;                    /* Named POSIX semaphore */
26458   char aSemName[MAX_PATHNAME+2];  /* Name of that semaphore */
26459 #endif
26460 };
26461
26462 /*
26463 ** A lists of all unixInodeInfo objects.
26464 */
26465 static unixInodeInfo *inodeList = 0;
26466
26467 /*
26468 **
26469 ** This function - unixLogError_x(), is only ever called via the macro
26470 ** unixLogError().
26471 **
26472 ** It is invoked after an error occurs in an OS function and errno has been
26473 ** set. It logs a message using sqlite3_log() containing the current value of
26474 ** errno and, if possible, the human-readable equivalent from strerror() or
26475 ** strerror_r().
26476 **
26477 ** The first argument passed to the macro should be the error code that
26478 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN). 
26479 ** The two subsequent arguments should be the name of the OS function that
26480 ** failed (e.g. "unlink", "open") and the associated file-system path,
26481 ** if any.
26482 */
26483 #define unixLogError(a,b,c)     unixLogErrorAtLine(a,b,c,__LINE__)
26484 static int unixLogErrorAtLine(
26485   int errcode,                    /* SQLite error code */
26486   const char *zFunc,              /* Name of OS function that failed */
26487   const char *zPath,              /* File path associated with error */
26488   int iLine                       /* Source line number where error occurred */
26489 ){
26490   char *zErr;                     /* Message from strerror() or equivalent */
26491   int iErrno = errno;             /* Saved syscall error number */
26492
26493   /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
26494   ** the strerror() function to obtain the human-readable error message
26495   ** equivalent to errno. Otherwise, use strerror_r().
26496   */ 
26497 #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
26498   char aErr[80];
26499   memset(aErr, 0, sizeof(aErr));
26500   zErr = aErr;
26501
26502   /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
26503   ** assume that the system provides the GNU version of strerror_r() that
26504   ** returns a pointer to a buffer containing the error message. That pointer 
26505   ** may point to aErr[], or it may point to some static storage somewhere. 
26506   ** Otherwise, assume that the system provides the POSIX version of 
26507   ** strerror_r(), which always writes an error message into aErr[].
26508   **
26509   ** If the code incorrectly assumes that it is the POSIX version that is
26510   ** available, the error message will often be an empty string. Not a
26511   ** huge problem. Incorrectly concluding that the GNU version is available 
26512   ** could lead to a segfault though.
26513   */
26514 #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
26515   zErr = 
26516 # endif
26517   strerror_r(iErrno, aErr, sizeof(aErr)-1);
26518
26519 #elif SQLITE_THREADSAFE
26520   /* This is a threadsafe build, but strerror_r() is not available. */
26521   zErr = "";
26522 #else
26523   /* Non-threadsafe build, use strerror(). */
26524   zErr = strerror(iErrno);
26525 #endif
26526
26527   if( zPath==0 ) zPath = "";
26528   sqlite3_log(errcode,
26529       "os_unix.c:%d: (%d) %s(%s) - %s",
26530       iLine, iErrno, zFunc, zPath, zErr
26531   );
26532
26533   return errcode;
26534 }
26535
26536 /*
26537 ** Close a file descriptor.
26538 **
26539 ** We assume that close() almost always works, since it is only in a
26540 ** very sick application or on a very sick platform that it might fail.
26541 ** If it does fail, simply leak the file descriptor, but do log the
26542 ** error.
26543 **
26544 ** Note that it is not safe to retry close() after EINTR since the
26545 ** file descriptor might have already been reused by another thread.
26546 ** So we don't even try to recover from an EINTR.  Just log the error
26547 ** and move on.
26548 */
26549 static void robust_close(unixFile *pFile, int h, int lineno){
26550   if( osClose(h) ){
26551     unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
26552                        pFile ? pFile->zPath : 0, lineno);
26553   }
26554 }
26555
26556 /*
26557 ** Set the pFile->lastErrno.  Do this in a subroutine as that provides
26558 ** a convenient place to set a breakpoint.
26559 */
26560 static void storeLastErrno(unixFile *pFile, int error){
26561   pFile->lastErrno = error;
26562 }
26563
26564 /*
26565 ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
26566 */ 
26567 static void closePendingFds(unixFile *pFile){
26568   unixInodeInfo *pInode = pFile->pInode;
26569   UnixUnusedFd *p;
26570   UnixUnusedFd *pNext;
26571   for(p=pInode->pUnused; p; p=pNext){
26572     pNext = p->pNext;
26573     robust_close(pFile, p->fd, __LINE__);
26574     sqlite3_free(p);
26575   }
26576   pInode->pUnused = 0;
26577 }
26578
26579 /*
26580 ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
26581 **
26582 ** The mutex entered using the unixEnterMutex() function must be held
26583 ** when this function is called.
26584 */
26585 static void releaseInodeInfo(unixFile *pFile){
26586   unixInodeInfo *pInode = pFile->pInode;
26587   assert( unixMutexHeld() );
26588   if( ALWAYS(pInode) ){
26589     pInode->nRef--;
26590     if( pInode->nRef==0 ){
26591       assert( pInode->pShmNode==0 );
26592       closePendingFds(pFile);
26593       if( pInode->pPrev ){
26594         assert( pInode->pPrev->pNext==pInode );
26595         pInode->pPrev->pNext = pInode->pNext;
26596       }else{
26597         assert( inodeList==pInode );
26598         inodeList = pInode->pNext;
26599       }
26600       if( pInode->pNext ){
26601         assert( pInode->pNext->pPrev==pInode );
26602         pInode->pNext->pPrev = pInode->pPrev;
26603       }
26604       sqlite3_free(pInode);
26605     }
26606   }
26607 }
26608
26609 /*
26610 ** Given a file descriptor, locate the unixInodeInfo object that
26611 ** describes that file descriptor.  Create a new one if necessary.  The
26612 ** return value might be uninitialized if an error occurs.
26613 **
26614 ** The mutex entered using the unixEnterMutex() function must be held
26615 ** when this function is called.
26616 **
26617 ** Return an appropriate error code.
26618 */
26619 static int findInodeInfo(
26620   unixFile *pFile,               /* Unix file with file desc used in the key */
26621   unixInodeInfo **ppInode        /* Return the unixInodeInfo object here */
26622 ){
26623   int rc;                        /* System call return code */
26624   int fd;                        /* The file descriptor for pFile */
26625   struct unixFileId fileId;      /* Lookup key for the unixInodeInfo */
26626   struct stat statbuf;           /* Low-level file information */
26627   unixInodeInfo *pInode = 0;     /* Candidate unixInodeInfo object */
26628
26629   assert( unixMutexHeld() );
26630
26631   /* Get low-level information about the file that we can used to
26632   ** create a unique name for the file.
26633   */
26634   fd = pFile->h;
26635   rc = osFstat(fd, &statbuf);
26636   if( rc!=0 ){
26637     storeLastErrno(pFile, errno);
26638 #ifdef EOVERFLOW
26639     if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
26640 #endif
26641     return SQLITE_IOERR;
26642   }
26643
26644 #ifdef __APPLE__
26645   /* On OS X on an msdos filesystem, the inode number is reported
26646   ** incorrectly for zero-size files.  See ticket #3260.  To work
26647   ** around this problem (we consider it a bug in OS X, not SQLite)
26648   ** we always increase the file size to 1 by writing a single byte
26649   ** prior to accessing the inode number.  The one byte written is
26650   ** an ASCII 'S' character which also happens to be the first byte
26651   ** in the header of every SQLite database.  In this way, if there
26652   ** is a race condition such that another thread has already populated
26653   ** the first page of the database, no damage is done.
26654   */
26655   if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
26656     do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
26657     if( rc!=1 ){
26658       storeLastErrno(pFile, errno);
26659       return SQLITE_IOERR;
26660     }
26661     rc = osFstat(fd, &statbuf);
26662     if( rc!=0 ){
26663       storeLastErrno(pFile, errno);
26664       return SQLITE_IOERR;
26665     }
26666   }
26667 #endif
26668
26669   memset(&fileId, 0, sizeof(fileId));
26670   fileId.dev = statbuf.st_dev;
26671 #if OS_VXWORKS
26672   fileId.pId = pFile->pId;
26673 #else
26674   fileId.ino = statbuf.st_ino;
26675 #endif
26676   pInode = inodeList;
26677   while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
26678     pInode = pInode->pNext;
26679   }
26680   if( pInode==0 ){
26681     pInode = sqlite3_malloc( sizeof(*pInode) );
26682     if( pInode==0 ){
26683       return SQLITE_NOMEM;
26684     }
26685     memset(pInode, 0, sizeof(*pInode));
26686     memcpy(&pInode->fileId, &fileId, sizeof(fileId));
26687     pInode->nRef = 1;
26688     pInode->pNext = inodeList;
26689     pInode->pPrev = 0;
26690     if( inodeList ) inodeList->pPrev = pInode;
26691     inodeList = pInode;
26692   }else{
26693     pInode->nRef++;
26694   }
26695   *ppInode = pInode;
26696   return SQLITE_OK;
26697 }
26698
26699 /*
26700 ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
26701 */
26702 static int fileHasMoved(unixFile *pFile){
26703 #if OS_VXWORKS
26704   return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
26705 #else
26706   struct stat buf;
26707   return pFile->pInode!=0 &&
26708       (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
26709 #endif
26710 }
26711
26712
26713 /*
26714 ** Check a unixFile that is a database.  Verify the following:
26715 **
26716 ** (1) There is exactly one hard link on the file
26717 ** (2) The file is not a symbolic link
26718 ** (3) The file has not been renamed or unlinked
26719 **
26720 ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
26721 */
26722 static void verifyDbFile(unixFile *pFile){
26723   struct stat buf;
26724   int rc;
26725   if( pFile->ctrlFlags & UNIXFILE_WARNED ){
26726     /* One or more of the following warnings have already been issued.  Do not
26727     ** repeat them so as not to clutter the error log */
26728     return;
26729   }
26730   rc = osFstat(pFile->h, &buf);
26731   if( rc!=0 ){
26732     sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
26733     pFile->ctrlFlags |= UNIXFILE_WARNED;
26734     return;
26735   }
26736   if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
26737     sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
26738     pFile->ctrlFlags |= UNIXFILE_WARNED;
26739     return;
26740   }
26741   if( buf.st_nlink>1 ){
26742     sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
26743     pFile->ctrlFlags |= UNIXFILE_WARNED;
26744     return;
26745   }
26746   if( fileHasMoved(pFile) ){
26747     sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
26748     pFile->ctrlFlags |= UNIXFILE_WARNED;
26749     return;
26750   }
26751 }
26752
26753
26754 /*
26755 ** This routine checks if there is a RESERVED lock held on the specified
26756 ** file by this or any other process. If such a lock is held, set *pResOut
26757 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
26758 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
26759 */
26760 static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
26761   int rc = SQLITE_OK;
26762   int reserved = 0;
26763   unixFile *pFile = (unixFile*)id;
26764
26765   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
26766
26767   assert( pFile );
26768   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
26769
26770   /* Check if a thread in this process holds such a lock */
26771   if( pFile->pInode->eFileLock>SHARED_LOCK ){
26772     reserved = 1;
26773   }
26774
26775   /* Otherwise see if some other process holds it.
26776   */
26777 #ifndef __DJGPP__
26778   if( !reserved && !pFile->pInode->bProcessLock ){
26779     struct flock lock;
26780     lock.l_whence = SEEK_SET;
26781     lock.l_start = RESERVED_BYTE;
26782     lock.l_len = 1;
26783     lock.l_type = F_WRLCK;
26784     if( osFcntl(pFile->h, F_GETLK, &lock) ){
26785       rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
26786       storeLastErrno(pFile, errno);
26787     } else if( lock.l_type!=F_UNLCK ){
26788       reserved = 1;
26789     }
26790   }
26791 #endif
26792   
26793   unixLeaveMutex();
26794   OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
26795
26796   *pResOut = reserved;
26797   return rc;
26798 }
26799
26800 /*
26801 ** Attempt to set a system-lock on the file pFile.  The lock is 
26802 ** described by pLock.
26803 **
26804 ** If the pFile was opened read/write from unix-excl, then the only lock
26805 ** ever obtained is an exclusive lock, and it is obtained exactly once
26806 ** the first time any lock is attempted.  All subsequent system locking
26807 ** operations become no-ops.  Locking operations still happen internally,
26808 ** in order to coordinate access between separate database connections
26809 ** within this process, but all of that is handled in memory and the
26810 ** operating system does not participate.
26811 **
26812 ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
26813 ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
26814 ** and is read-only.
26815 **
26816 ** Zero is returned if the call completes successfully, or -1 if a call
26817 ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
26818 */
26819 static int unixFileLock(unixFile *pFile, struct flock *pLock){
26820   int rc;
26821   unixInodeInfo *pInode = pFile->pInode;
26822   assert( unixMutexHeld() );
26823   assert( pInode!=0 );
26824   if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
26825    && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
26826   ){
26827     if( pInode->bProcessLock==0 ){
26828       struct flock lock;
26829       assert( pInode->nLock==0 );
26830       lock.l_whence = SEEK_SET;
26831       lock.l_start = SHARED_FIRST;
26832       lock.l_len = SHARED_SIZE;
26833       lock.l_type = F_WRLCK;
26834       rc = osFcntl(pFile->h, F_SETLK, &lock);
26835       if( rc<0 ) return rc;
26836       pInode->bProcessLock = 1;
26837       pInode->nLock++;
26838     }else{
26839       rc = 0;
26840     }
26841   }else{
26842     rc = osFcntl(pFile->h, F_SETLK, pLock);
26843   }
26844   return rc;
26845 }
26846
26847 /*
26848 ** Lock the file with the lock specified by parameter eFileLock - one
26849 ** of the following:
26850 **
26851 **     (1) SHARED_LOCK
26852 **     (2) RESERVED_LOCK
26853 **     (3) PENDING_LOCK
26854 **     (4) EXCLUSIVE_LOCK
26855 **
26856 ** Sometimes when requesting one lock state, additional lock states
26857 ** are inserted in between.  The locking might fail on one of the later
26858 ** transitions leaving the lock state different from what it started but
26859 ** still short of its goal.  The following chart shows the allowed
26860 ** transitions and the inserted intermediate states:
26861 **
26862 **    UNLOCKED -> SHARED
26863 **    SHARED -> RESERVED
26864 **    SHARED -> (PENDING) -> EXCLUSIVE
26865 **    RESERVED -> (PENDING) -> EXCLUSIVE
26866 **    PENDING -> EXCLUSIVE
26867 **
26868 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
26869 ** routine to lower a locking level.
26870 */
26871 static int unixLock(sqlite3_file *id, int eFileLock){
26872   /* The following describes the implementation of the various locks and
26873   ** lock transitions in terms of the POSIX advisory shared and exclusive
26874   ** lock primitives (called read-locks and write-locks below, to avoid
26875   ** confusion with SQLite lock names). The algorithms are complicated
26876   ** slightly in order to be compatible with windows systems simultaneously
26877   ** accessing the same database file, in case that is ever required.
26878   **
26879   ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
26880   ** byte', each single bytes at well known offsets, and the 'shared byte
26881   ** range', a range of 510 bytes at a well known offset.
26882   **
26883   ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
26884   ** byte'.  If this is successful, a random byte from the 'shared byte
26885   ** range' is read-locked and the lock on the 'pending byte' released.
26886   **
26887   ** A process may only obtain a RESERVED lock after it has a SHARED lock.
26888   ** A RESERVED lock is implemented by grabbing a write-lock on the
26889   ** 'reserved byte'. 
26890   **
26891   ** A process may only obtain a PENDING lock after it has obtained a
26892   ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
26893   ** on the 'pending byte'. This ensures that no new SHARED locks can be
26894   ** obtained, but existing SHARED locks are allowed to persist. A process
26895   ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
26896   ** This property is used by the algorithm for rolling back a journal file
26897   ** after a crash.
26898   **
26899   ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
26900   ** implemented by obtaining a write-lock on the entire 'shared byte
26901   ** range'. Since all other locks require a read-lock on one of the bytes
26902   ** within this range, this ensures that no other locks are held on the
26903   ** database. 
26904   **
26905   ** The reason a single byte cannot be used instead of the 'shared byte
26906   ** range' is that some versions of windows do not support read-locks. By
26907   ** locking a random byte from a range, concurrent SHARED locks may exist
26908   ** even if the locking primitive used is always a write-lock.
26909   */
26910   int rc = SQLITE_OK;
26911   unixFile *pFile = (unixFile*)id;
26912   unixInodeInfo *pInode;
26913   struct flock lock;
26914   int tErrno = 0;
26915
26916   assert( pFile );
26917   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
26918       azFileLock(eFileLock), azFileLock(pFile->eFileLock),
26919       azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared,
26920       osGetpid(0)));
26921
26922   /* If there is already a lock of this type or more restrictive on the
26923   ** unixFile, do nothing. Don't use the end_lock: exit path, as
26924   ** unixEnterMutex() hasn't been called yet.
26925   */
26926   if( pFile->eFileLock>=eFileLock ){
26927     OSTRACE(("LOCK    %d %s ok (already held) (unix)\n", pFile->h,
26928             azFileLock(eFileLock)));
26929     return SQLITE_OK;
26930   }
26931
26932   /* Make sure the locking sequence is correct.
26933   **  (1) We never move from unlocked to anything higher than shared lock.
26934   **  (2) SQLite never explicitly requests a pendig lock.
26935   **  (3) A shared lock is always held when a reserve lock is requested.
26936   */
26937   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
26938   assert( eFileLock!=PENDING_LOCK );
26939   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
26940
26941   /* This mutex is needed because pFile->pInode is shared across threads
26942   */
26943   unixEnterMutex();
26944   pInode = pFile->pInode;
26945
26946   /* If some thread using this PID has a lock via a different unixFile*
26947   ** handle that precludes the requested lock, return BUSY.
26948   */
26949   if( (pFile->eFileLock!=pInode->eFileLock && 
26950           (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
26951   ){
26952     rc = SQLITE_BUSY;
26953     goto end_lock;
26954   }
26955
26956   /* If a SHARED lock is requested, and some thread using this PID already
26957   ** has a SHARED or RESERVED lock, then increment reference counts and
26958   ** return SQLITE_OK.
26959   */
26960   if( eFileLock==SHARED_LOCK && 
26961       (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
26962     assert( eFileLock==SHARED_LOCK );
26963     assert( pFile->eFileLock==0 );
26964     assert( pInode->nShared>0 );
26965     pFile->eFileLock = SHARED_LOCK;
26966     pInode->nShared++;
26967     pInode->nLock++;
26968     goto end_lock;
26969   }
26970
26971
26972   /* A PENDING lock is needed before acquiring a SHARED lock and before
26973   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
26974   ** be released.
26975   */
26976   lock.l_len = 1L;
26977   lock.l_whence = SEEK_SET;
26978   if( eFileLock==SHARED_LOCK 
26979       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
26980   ){
26981     lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
26982     lock.l_start = PENDING_BYTE;
26983     if( unixFileLock(pFile, &lock) ){
26984       tErrno = errno;
26985       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
26986       if( rc!=SQLITE_BUSY ){
26987         storeLastErrno(pFile, tErrno);
26988       }
26989       goto end_lock;
26990     }
26991   }
26992
26993
26994   /* If control gets to this point, then actually go ahead and make
26995   ** operating system calls for the specified lock.
26996   */
26997   if( eFileLock==SHARED_LOCK ){
26998     assert( pInode->nShared==0 );
26999     assert( pInode->eFileLock==0 );
27000     assert( rc==SQLITE_OK );
27001
27002     /* Now get the read-lock */
27003     lock.l_start = SHARED_FIRST;
27004     lock.l_len = SHARED_SIZE;
27005     if( unixFileLock(pFile, &lock) ){
27006       tErrno = errno;
27007       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27008     }
27009
27010     /* Drop the temporary PENDING lock */
27011     lock.l_start = PENDING_BYTE;
27012     lock.l_len = 1L;
27013     lock.l_type = F_UNLCK;
27014     if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
27015       /* This could happen with a network mount */
27016       tErrno = errno;
27017       rc = SQLITE_IOERR_UNLOCK; 
27018     }
27019
27020     if( rc ){
27021       if( rc!=SQLITE_BUSY ){
27022         storeLastErrno(pFile, tErrno);
27023       }
27024       goto end_lock;
27025     }else{
27026       pFile->eFileLock = SHARED_LOCK;
27027       pInode->nLock++;
27028       pInode->nShared = 1;
27029     }
27030   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
27031     /* We are trying for an exclusive lock but another thread in this
27032     ** same process is still holding a shared lock. */
27033     rc = SQLITE_BUSY;
27034   }else{
27035     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
27036     ** assumed that there is a SHARED or greater lock on the file
27037     ** already.
27038     */
27039     assert( 0!=pFile->eFileLock );
27040     lock.l_type = F_WRLCK;
27041
27042     assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
27043     if( eFileLock==RESERVED_LOCK ){
27044       lock.l_start = RESERVED_BYTE;
27045       lock.l_len = 1L;
27046     }else{
27047       lock.l_start = SHARED_FIRST;
27048       lock.l_len = SHARED_SIZE;
27049     }
27050
27051     if( unixFileLock(pFile, &lock) ){
27052       tErrno = errno;
27053       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27054       if( rc!=SQLITE_BUSY ){
27055         storeLastErrno(pFile, tErrno);
27056       }
27057     }
27058   }
27059   
27060
27061 #ifdef SQLITE_DEBUG
27062   /* Set up the transaction-counter change checking flags when
27063   ** transitioning from a SHARED to a RESERVED lock.  The change
27064   ** from SHARED to RESERVED marks the beginning of a normal
27065   ** write operation (not a hot journal rollback).
27066   */
27067   if( rc==SQLITE_OK
27068    && pFile->eFileLock<=SHARED_LOCK
27069    && eFileLock==RESERVED_LOCK
27070   ){
27071     pFile->transCntrChng = 0;
27072     pFile->dbUpdate = 0;
27073     pFile->inNormalWrite = 1;
27074   }
27075 #endif
27076
27077
27078   if( rc==SQLITE_OK ){
27079     pFile->eFileLock = eFileLock;
27080     pInode->eFileLock = eFileLock;
27081   }else if( eFileLock==EXCLUSIVE_LOCK ){
27082     pFile->eFileLock = PENDING_LOCK;
27083     pInode->eFileLock = PENDING_LOCK;
27084   }
27085
27086 end_lock:
27087   unixLeaveMutex();
27088   OSTRACE(("LOCK    %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock), 
27089       rc==SQLITE_OK ? "ok" : "failed"));
27090   return rc;
27091 }
27092
27093 /*
27094 ** Add the file descriptor used by file handle pFile to the corresponding
27095 ** pUnused list.
27096 */
27097 static void setPendingFd(unixFile *pFile){
27098   unixInodeInfo *pInode = pFile->pInode;
27099   UnixUnusedFd *p = pFile->pUnused;
27100   p->pNext = pInode->pUnused;
27101   pInode->pUnused = p;
27102   pFile->h = -1;
27103   pFile->pUnused = 0;
27104 }
27105
27106 /*
27107 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27108 ** must be either NO_LOCK or SHARED_LOCK.
27109 **
27110 ** If the locking level of the file descriptor is already at or below
27111 ** the requested locking level, this routine is a no-op.
27112 ** 
27113 ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
27114 ** the byte range is divided into 2 parts and the first part is unlocked then
27115 ** set to a read lock, then the other part is simply unlocked.  This works 
27116 ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to 
27117 ** remove the write lock on a region when a read lock is set.
27118 */
27119 static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
27120   unixFile *pFile = (unixFile*)id;
27121   unixInodeInfo *pInode;
27122   struct flock lock;
27123   int rc = SQLITE_OK;
27124
27125   assert( pFile );
27126   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
27127       pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
27128       osGetpid(0)));
27129
27130   assert( eFileLock<=SHARED_LOCK );
27131   if( pFile->eFileLock<=eFileLock ){
27132     return SQLITE_OK;
27133   }
27134   unixEnterMutex();
27135   pInode = pFile->pInode;
27136   assert( pInode->nShared!=0 );
27137   if( pFile->eFileLock>SHARED_LOCK ){
27138     assert( pInode->eFileLock==pFile->eFileLock );
27139
27140 #ifdef SQLITE_DEBUG
27141     /* When reducing a lock such that other processes can start
27142     ** reading the database file again, make sure that the
27143     ** transaction counter was updated if any part of the database
27144     ** file changed.  If the transaction counter is not updated,
27145     ** other connections to the same file might not realize that
27146     ** the file has changed and hence might not know to flush their
27147     ** cache.  The use of a stale cache can lead to database corruption.
27148     */
27149     pFile->inNormalWrite = 0;
27150 #endif
27151
27152     /* downgrading to a shared lock on NFS involves clearing the write lock
27153     ** before establishing the readlock - to avoid a race condition we downgrade
27154     ** the lock in 2 blocks, so that part of the range will be covered by a 
27155     ** write lock until the rest is covered by a read lock:
27156     **  1:   [WWWWW]
27157     **  2:   [....W]
27158     **  3:   [RRRRW]
27159     **  4:   [RRRR.]
27160     */
27161     if( eFileLock==SHARED_LOCK ){
27162 #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
27163       (void)handleNFSUnlock;
27164       assert( handleNFSUnlock==0 );
27165 #endif
27166 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
27167       if( handleNFSUnlock ){
27168         int tErrno;               /* Error code from system call errors */
27169         off_t divSize = SHARED_SIZE - 1;
27170         
27171         lock.l_type = F_UNLCK;
27172         lock.l_whence = SEEK_SET;
27173         lock.l_start = SHARED_FIRST;
27174         lock.l_len = divSize;
27175         if( unixFileLock(pFile, &lock)==(-1) ){
27176           tErrno = errno;
27177           rc = SQLITE_IOERR_UNLOCK;
27178           if( IS_LOCK_ERROR(rc) ){
27179             storeLastErrno(pFile, tErrno);
27180           }
27181           goto end_unlock;
27182         }
27183         lock.l_type = F_RDLCK;
27184         lock.l_whence = SEEK_SET;
27185         lock.l_start = SHARED_FIRST;
27186         lock.l_len = divSize;
27187         if( unixFileLock(pFile, &lock)==(-1) ){
27188           tErrno = errno;
27189           rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
27190           if( IS_LOCK_ERROR(rc) ){
27191             storeLastErrno(pFile, tErrno);
27192           }
27193           goto end_unlock;
27194         }
27195         lock.l_type = F_UNLCK;
27196         lock.l_whence = SEEK_SET;
27197         lock.l_start = SHARED_FIRST+divSize;
27198         lock.l_len = SHARED_SIZE-divSize;
27199         if( unixFileLock(pFile, &lock)==(-1) ){
27200           tErrno = errno;
27201           rc = SQLITE_IOERR_UNLOCK;
27202           if( IS_LOCK_ERROR(rc) ){
27203             storeLastErrno(pFile, tErrno);
27204           }
27205           goto end_unlock;
27206         }
27207       }else
27208 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
27209       {
27210         lock.l_type = F_RDLCK;
27211         lock.l_whence = SEEK_SET;
27212         lock.l_start = SHARED_FIRST;
27213         lock.l_len = SHARED_SIZE;
27214         if( unixFileLock(pFile, &lock) ){
27215           /* In theory, the call to unixFileLock() cannot fail because another
27216           ** process is holding an incompatible lock. If it does, this 
27217           ** indicates that the other process is not following the locking
27218           ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
27219           ** SQLITE_BUSY would confuse the upper layer (in practice it causes 
27220           ** an assert to fail). */ 
27221           rc = SQLITE_IOERR_RDLOCK;
27222           storeLastErrno(pFile, errno);
27223           goto end_unlock;
27224         }
27225       }
27226     }
27227     lock.l_type = F_UNLCK;
27228     lock.l_whence = SEEK_SET;
27229     lock.l_start = PENDING_BYTE;
27230     lock.l_len = 2L;  assert( PENDING_BYTE+1==RESERVED_BYTE );
27231     if( unixFileLock(pFile, &lock)==0 ){
27232       pInode->eFileLock = SHARED_LOCK;
27233     }else{
27234       rc = SQLITE_IOERR_UNLOCK;
27235       storeLastErrno(pFile, errno);
27236       goto end_unlock;
27237     }
27238   }
27239   if( eFileLock==NO_LOCK ){
27240     /* Decrement the shared lock counter.  Release the lock using an
27241     ** OS call only when all threads in this same process have released
27242     ** the lock.
27243     */
27244     pInode->nShared--;
27245     if( pInode->nShared==0 ){
27246       lock.l_type = F_UNLCK;
27247       lock.l_whence = SEEK_SET;
27248       lock.l_start = lock.l_len = 0L;
27249       if( unixFileLock(pFile, &lock)==0 ){
27250         pInode->eFileLock = NO_LOCK;
27251       }else{
27252         rc = SQLITE_IOERR_UNLOCK;
27253         storeLastErrno(pFile, errno);
27254         pInode->eFileLock = NO_LOCK;
27255         pFile->eFileLock = NO_LOCK;
27256       }
27257     }
27258
27259     /* Decrement the count of locks against this same file.  When the
27260     ** count reaches zero, close any other file descriptors whose close
27261     ** was deferred because of outstanding locks.
27262     */
27263     pInode->nLock--;
27264     assert( pInode->nLock>=0 );
27265     if( pInode->nLock==0 ){
27266       closePendingFds(pFile);
27267     }
27268   }
27269
27270 end_unlock:
27271   unixLeaveMutex();
27272   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
27273   return rc;
27274 }
27275
27276 /*
27277 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27278 ** must be either NO_LOCK or SHARED_LOCK.
27279 **
27280 ** If the locking level of the file descriptor is already at or below
27281 ** the requested locking level, this routine is a no-op.
27282 */
27283 static int unixUnlock(sqlite3_file *id, int eFileLock){
27284 #if SQLITE_MAX_MMAP_SIZE>0
27285   assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
27286 #endif
27287   return posixUnlock(id, eFileLock, 0);
27288 }
27289
27290 #if SQLITE_MAX_MMAP_SIZE>0
27291 static int unixMapfile(unixFile *pFd, i64 nByte);
27292 static void unixUnmapfile(unixFile *pFd);
27293 #endif
27294
27295 /*
27296 ** This function performs the parts of the "close file" operation 
27297 ** common to all locking schemes. It closes the directory and file
27298 ** handles, if they are valid, and sets all fields of the unixFile
27299 ** structure to 0.
27300 **
27301 ** It is *not* necessary to hold the mutex when this routine is called,
27302 ** even on VxWorks.  A mutex will be acquired on VxWorks by the
27303 ** vxworksReleaseFileId() routine.
27304 */
27305 static int closeUnixFile(sqlite3_file *id){
27306   unixFile *pFile = (unixFile*)id;
27307 #if SQLITE_MAX_MMAP_SIZE>0
27308   unixUnmapfile(pFile);
27309 #endif
27310   if( pFile->h>=0 ){
27311     robust_close(pFile, pFile->h, __LINE__);
27312     pFile->h = -1;
27313   }
27314 #if OS_VXWORKS
27315   if( pFile->pId ){
27316     if( pFile->ctrlFlags & UNIXFILE_DELETE ){
27317       osUnlink(pFile->pId->zCanonicalName);
27318     }
27319     vxworksReleaseFileId(pFile->pId);
27320     pFile->pId = 0;
27321   }
27322 #endif
27323 #ifdef SQLITE_UNLINK_AFTER_CLOSE
27324   if( pFile->ctrlFlags & UNIXFILE_DELETE ){
27325     osUnlink(pFile->zPath);
27326     sqlite3_free(*(char**)&pFile->zPath);
27327     pFile->zPath = 0;
27328   }
27329 #endif
27330   OSTRACE(("CLOSE   %-3d\n", pFile->h));
27331   OpenCounter(-1);
27332   sqlite3_free(pFile->pUnused);
27333   memset(pFile, 0, sizeof(unixFile));
27334   return SQLITE_OK;
27335 }
27336
27337 /*
27338 ** Close a file.
27339 */
27340 static int unixClose(sqlite3_file *id){
27341   int rc = SQLITE_OK;
27342   unixFile *pFile = (unixFile *)id;
27343   verifyDbFile(pFile);
27344   unixUnlock(id, NO_LOCK);
27345   unixEnterMutex();
27346
27347   /* unixFile.pInode is always valid here. Otherwise, a different close
27348   ** routine (e.g. nolockClose()) would be called instead.
27349   */
27350   assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
27351   if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
27352     /* If there are outstanding locks, do not actually close the file just
27353     ** yet because that would clear those locks.  Instead, add the file
27354     ** descriptor to pInode->pUnused list.  It will be automatically closed 
27355     ** when the last lock is cleared.
27356     */
27357     setPendingFd(pFile);
27358   }
27359   releaseInodeInfo(pFile);
27360   rc = closeUnixFile(id);
27361   unixLeaveMutex();
27362   return rc;
27363 }
27364
27365 /************** End of the posix advisory lock implementation *****************
27366 ******************************************************************************/
27367
27368 /******************************************************************************
27369 ****************************** No-op Locking **********************************
27370 **
27371 ** Of the various locking implementations available, this is by far the
27372 ** simplest:  locking is ignored.  No attempt is made to lock the database
27373 ** file for reading or writing.
27374 **
27375 ** This locking mode is appropriate for use on read-only databases
27376 ** (ex: databases that are burned into CD-ROM, for example.)  It can
27377 ** also be used if the application employs some external mechanism to
27378 ** prevent simultaneous access of the same database by two or more
27379 ** database connections.  But there is a serious risk of database
27380 ** corruption if this locking mode is used in situations where multiple
27381 ** database connections are accessing the same database file at the same
27382 ** time and one or more of those connections are writing.
27383 */
27384
27385 static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
27386   UNUSED_PARAMETER(NotUsed);
27387   *pResOut = 0;
27388   return SQLITE_OK;
27389 }
27390 static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
27391   UNUSED_PARAMETER2(NotUsed, NotUsed2);
27392   return SQLITE_OK;
27393 }
27394 static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
27395   UNUSED_PARAMETER2(NotUsed, NotUsed2);
27396   return SQLITE_OK;
27397 }
27398
27399 /*
27400 ** Close the file.
27401 */
27402 static int nolockClose(sqlite3_file *id) {
27403   return closeUnixFile(id);
27404 }
27405
27406 /******************* End of the no-op lock implementation *********************
27407 ******************************************************************************/
27408
27409 /******************************************************************************
27410 ************************* Begin dot-file Locking ******************************
27411 **
27412 ** The dotfile locking implementation uses the existence of separate lock
27413 ** files (really a directory) to control access to the database.  This works
27414 ** on just about every filesystem imaginable.  But there are serious downsides:
27415 **
27416 **    (1)  There is zero concurrency.  A single reader blocks all other
27417 **         connections from reading or writing the database.
27418 **
27419 **    (2)  An application crash or power loss can leave stale lock files
27420 **         sitting around that need to be cleared manually.
27421 **
27422 ** Nevertheless, a dotlock is an appropriate locking mode for use if no
27423 ** other locking strategy is available.
27424 **
27425 ** Dotfile locking works by creating a subdirectory in the same directory as
27426 ** the database and with the same name but with a ".lock" extension added.
27427 ** The existence of a lock directory implies an EXCLUSIVE lock.  All other
27428 ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
27429 */
27430
27431 /*
27432 ** The file suffix added to the data base filename in order to create the
27433 ** lock directory.
27434 */
27435 #define DOTLOCK_SUFFIX ".lock"
27436
27437 /*
27438 ** This routine checks if there is a RESERVED lock held on the specified
27439 ** file by this or any other process. If such a lock is held, set *pResOut
27440 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
27441 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27442 **
27443 ** In dotfile locking, either a lock exists or it does not.  So in this
27444 ** variation of CheckReservedLock(), *pResOut is set to true if any lock
27445 ** is held on the file and false if the file is unlocked.
27446 */
27447 static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
27448   int rc = SQLITE_OK;
27449   int reserved = 0;
27450   unixFile *pFile = (unixFile*)id;
27451
27452   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27453   
27454   assert( pFile );
27455
27456   /* Check if a thread in this process holds such a lock */
27457   if( pFile->eFileLock>SHARED_LOCK ){
27458     /* Either this connection or some other connection in the same process
27459     ** holds a lock on the file.  No need to check further. */
27460     reserved = 1;
27461   }else{
27462     /* The lock is held if and only if the lockfile exists */
27463     const char *zLockFile = (const char*)pFile->lockingContext;
27464     reserved = osAccess(zLockFile, 0)==0;
27465   }
27466   OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
27467   *pResOut = reserved;
27468   return rc;
27469 }
27470
27471 /*
27472 ** Lock the file with the lock specified by parameter eFileLock - one
27473 ** of the following:
27474 **
27475 **     (1) SHARED_LOCK
27476 **     (2) RESERVED_LOCK
27477 **     (3) PENDING_LOCK
27478 **     (4) EXCLUSIVE_LOCK
27479 **
27480 ** Sometimes when requesting one lock state, additional lock states
27481 ** are inserted in between.  The locking might fail on one of the later
27482 ** transitions leaving the lock state different from what it started but
27483 ** still short of its goal.  The following chart shows the allowed
27484 ** transitions and the inserted intermediate states:
27485 **
27486 **    UNLOCKED -> SHARED
27487 **    SHARED -> RESERVED
27488 **    SHARED -> (PENDING) -> EXCLUSIVE
27489 **    RESERVED -> (PENDING) -> EXCLUSIVE
27490 **    PENDING -> EXCLUSIVE
27491 **
27492 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27493 ** routine to lower a locking level.
27494 **
27495 ** With dotfile locking, we really only support state (4): EXCLUSIVE.
27496 ** But we track the other locking levels internally.
27497 */
27498 static int dotlockLock(sqlite3_file *id, int eFileLock) {
27499   unixFile *pFile = (unixFile*)id;
27500   char *zLockFile = (char *)pFile->lockingContext;
27501   int rc = SQLITE_OK;
27502
27503
27504   /* If we have any lock, then the lock file already exists.  All we have
27505   ** to do is adjust our internal record of the lock level.
27506   */
27507   if( pFile->eFileLock > NO_LOCK ){
27508     pFile->eFileLock = eFileLock;
27509     /* Always update the timestamp on the old file */
27510 #ifdef HAVE_UTIME
27511     utime(zLockFile, NULL);
27512 #else
27513     utimes(zLockFile, NULL);
27514 #endif
27515     return SQLITE_OK;
27516   }
27517   
27518   /* grab an exclusive lock */
27519   rc = osMkdir(zLockFile, 0777);
27520   if( rc<0 ){
27521     /* failed to open/create the lock directory */
27522     int tErrno = errno;
27523     if( EEXIST == tErrno ){
27524       rc = SQLITE_BUSY;
27525     } else {
27526       rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27527       if( IS_LOCK_ERROR(rc) ){
27528         storeLastErrno(pFile, tErrno);
27529       }
27530     }
27531     return rc;
27532   } 
27533   
27534   /* got it, set the type and return ok */
27535   pFile->eFileLock = eFileLock;
27536   return rc;
27537 }
27538
27539 /*
27540 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27541 ** must be either NO_LOCK or SHARED_LOCK.
27542 **
27543 ** If the locking level of the file descriptor is already at or below
27544 ** the requested locking level, this routine is a no-op.
27545 **
27546 ** When the locking level reaches NO_LOCK, delete the lock file.
27547 */
27548 static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
27549   unixFile *pFile = (unixFile*)id;
27550   char *zLockFile = (char *)pFile->lockingContext;
27551   int rc;
27552
27553   assert( pFile );
27554   OSTRACE(("UNLOCK  %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
27555            pFile->eFileLock, osGetpid(0)));
27556   assert( eFileLock<=SHARED_LOCK );
27557   
27558   /* no-op if possible */
27559   if( pFile->eFileLock==eFileLock ){
27560     return SQLITE_OK;
27561   }
27562
27563   /* To downgrade to shared, simply update our internal notion of the
27564   ** lock state.  No need to mess with the file on disk.
27565   */
27566   if( eFileLock==SHARED_LOCK ){
27567     pFile->eFileLock = SHARED_LOCK;
27568     return SQLITE_OK;
27569   }
27570   
27571   /* To fully unlock the database, delete the lock file */
27572   assert( eFileLock==NO_LOCK );
27573   rc = osRmdir(zLockFile);
27574   if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
27575   if( rc<0 ){
27576     int tErrno = errno;
27577     rc = 0;
27578     if( ENOENT != tErrno ){
27579       rc = SQLITE_IOERR_UNLOCK;
27580     }
27581     if( IS_LOCK_ERROR(rc) ){
27582       storeLastErrno(pFile, tErrno);
27583     }
27584     return rc; 
27585   }
27586   pFile->eFileLock = NO_LOCK;
27587   return SQLITE_OK;
27588 }
27589
27590 /*
27591 ** Close a file.  Make sure the lock has been released before closing.
27592 */
27593 static int dotlockClose(sqlite3_file *id) {
27594   int rc = SQLITE_OK;
27595   if( id ){
27596     unixFile *pFile = (unixFile*)id;
27597     dotlockUnlock(id, NO_LOCK);
27598     sqlite3_free(pFile->lockingContext);
27599     rc = closeUnixFile(id);
27600   }
27601   return rc;
27602 }
27603 /****************** End of the dot-file lock implementation *******************
27604 ******************************************************************************/
27605
27606 /******************************************************************************
27607 ************************** Begin flock Locking ********************************
27608 **
27609 ** Use the flock() system call to do file locking.
27610 **
27611 ** flock() locking is like dot-file locking in that the various
27612 ** fine-grain locking levels supported by SQLite are collapsed into
27613 ** a single exclusive lock.  In other words, SHARED, RESERVED, and
27614 ** PENDING locks are the same thing as an EXCLUSIVE lock.  SQLite
27615 ** still works when you do this, but concurrency is reduced since
27616 ** only a single process can be reading the database at a time.
27617 **
27618 ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off
27619 */
27620 #if SQLITE_ENABLE_LOCKING_STYLE
27621
27622 /*
27623 ** Retry flock() calls that fail with EINTR
27624 */
27625 #ifdef EINTR
27626 static int robust_flock(int fd, int op){
27627   int rc;
27628   do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
27629   return rc;
27630 }
27631 #else
27632 # define robust_flock(a,b) flock(a,b)
27633 #endif
27634      
27635
27636 /*
27637 ** This routine checks if there is a RESERVED lock held on the specified
27638 ** file by this or any other process. If such a lock is held, set *pResOut
27639 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
27640 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27641 */
27642 static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
27643   int rc = SQLITE_OK;
27644   int reserved = 0;
27645   unixFile *pFile = (unixFile*)id;
27646   
27647   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27648   
27649   assert( pFile );
27650   
27651   /* Check if a thread in this process holds such a lock */
27652   if( pFile->eFileLock>SHARED_LOCK ){
27653     reserved = 1;
27654   }
27655   
27656   /* Otherwise see if some other process holds it. */
27657   if( !reserved ){
27658     /* attempt to get the lock */
27659     int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
27660     if( !lrc ){
27661       /* got the lock, unlock it */
27662       lrc = robust_flock(pFile->h, LOCK_UN);
27663       if ( lrc ) {
27664         int tErrno = errno;
27665         /* unlock failed with an error */
27666         lrc = SQLITE_IOERR_UNLOCK; 
27667         if( IS_LOCK_ERROR(lrc) ){
27668           storeLastErrno(pFile, tErrno);
27669           rc = lrc;
27670         }
27671       }
27672     } else {
27673       int tErrno = errno;
27674       reserved = 1;
27675       /* someone else might have it reserved */
27676       lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK); 
27677       if( IS_LOCK_ERROR(lrc) ){
27678         storeLastErrno(pFile, tErrno);
27679         rc = lrc;
27680       }
27681     }
27682   }
27683   OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
27684
27685 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27686   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
27687     rc = SQLITE_OK;
27688     reserved=1;
27689   }
27690 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27691   *pResOut = reserved;
27692   return rc;
27693 }
27694
27695 /*
27696 ** Lock the file with the lock specified by parameter eFileLock - one
27697 ** of the following:
27698 **
27699 **     (1) SHARED_LOCK
27700 **     (2) RESERVED_LOCK
27701 **     (3) PENDING_LOCK
27702 **     (4) EXCLUSIVE_LOCK
27703 **
27704 ** Sometimes when requesting one lock state, additional lock states
27705 ** are inserted in between.  The locking might fail on one of the later
27706 ** transitions leaving the lock state different from what it started but
27707 ** still short of its goal.  The following chart shows the allowed
27708 ** transitions and the inserted intermediate states:
27709 **
27710 **    UNLOCKED -> SHARED
27711 **    SHARED -> RESERVED
27712 **    SHARED -> (PENDING) -> EXCLUSIVE
27713 **    RESERVED -> (PENDING) -> EXCLUSIVE
27714 **    PENDING -> EXCLUSIVE
27715 **
27716 ** flock() only really support EXCLUSIVE locks.  We track intermediate
27717 ** lock states in the sqlite3_file structure, but all locks SHARED or
27718 ** above are really EXCLUSIVE locks and exclude all other processes from
27719 ** access the file.
27720 **
27721 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27722 ** routine to lower a locking level.
27723 */
27724 static int flockLock(sqlite3_file *id, int eFileLock) {
27725   int rc = SQLITE_OK;
27726   unixFile *pFile = (unixFile*)id;
27727
27728   assert( pFile );
27729
27730   /* if we already have a lock, it is exclusive.  
27731   ** Just adjust level and punt on outta here. */
27732   if (pFile->eFileLock > NO_LOCK) {
27733     pFile->eFileLock = eFileLock;
27734     return SQLITE_OK;
27735   }
27736   
27737   /* grab an exclusive lock */
27738   
27739   if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
27740     int tErrno = errno;
27741     /* didn't get, must be busy */
27742     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
27743     if( IS_LOCK_ERROR(rc) ){
27744       storeLastErrno(pFile, tErrno);
27745     }
27746   } else {
27747     /* got it, set the type and return ok */
27748     pFile->eFileLock = eFileLock;
27749   }
27750   OSTRACE(("LOCK    %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock), 
27751            rc==SQLITE_OK ? "ok" : "failed"));
27752 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27753   if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
27754     rc = SQLITE_BUSY;
27755   }
27756 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27757   return rc;
27758 }
27759
27760
27761 /*
27762 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27763 ** must be either NO_LOCK or SHARED_LOCK.
27764 **
27765 ** If the locking level of the file descriptor is already at or below
27766 ** the requested locking level, this routine is a no-op.
27767 */
27768 static int flockUnlock(sqlite3_file *id, int eFileLock) {
27769   unixFile *pFile = (unixFile*)id;
27770   
27771   assert( pFile );
27772   OSTRACE(("UNLOCK  %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
27773            pFile->eFileLock, osGetpid(0)));
27774   assert( eFileLock<=SHARED_LOCK );
27775   
27776   /* no-op if possible */
27777   if( pFile->eFileLock==eFileLock ){
27778     return SQLITE_OK;
27779   }
27780   
27781   /* shared can just be set because we always have an exclusive */
27782   if (eFileLock==SHARED_LOCK) {
27783     pFile->eFileLock = eFileLock;
27784     return SQLITE_OK;
27785   }
27786   
27787   /* no, really, unlock. */
27788   if( robust_flock(pFile->h, LOCK_UN) ){
27789 #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
27790     return SQLITE_OK;
27791 #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
27792     return SQLITE_IOERR_UNLOCK;
27793   }else{
27794     pFile->eFileLock = NO_LOCK;
27795     return SQLITE_OK;
27796   }
27797 }
27798
27799 /*
27800 ** Close a file.
27801 */
27802 static int flockClose(sqlite3_file *id) {
27803   int rc = SQLITE_OK;
27804   if( id ){
27805     flockUnlock(id, NO_LOCK);
27806     rc = closeUnixFile(id);
27807   }
27808   return rc;
27809 }
27810
27811 #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
27812
27813 /******************* End of the flock lock implementation *********************
27814 ******************************************************************************/
27815
27816 /******************************************************************************
27817 ************************ Begin Named Semaphore Locking ************************
27818 **
27819 ** Named semaphore locking is only supported on VxWorks.
27820 **
27821 ** Semaphore locking is like dot-lock and flock in that it really only
27822 ** supports EXCLUSIVE locking.  Only a single process can read or write
27823 ** the database file at a time.  This reduces potential concurrency, but
27824 ** makes the lock implementation much easier.
27825 */
27826 #if OS_VXWORKS
27827
27828 /*
27829 ** This routine checks if there is a RESERVED lock held on the specified
27830 ** file by this or any other process. If such a lock is held, set *pResOut
27831 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
27832 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
27833 */
27834 static int semXCheckReservedLock(sqlite3_file *id, int *pResOut) {
27835   int rc = SQLITE_OK;
27836   int reserved = 0;
27837   unixFile *pFile = (unixFile*)id;
27838
27839   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
27840   
27841   assert( pFile );
27842
27843   /* Check if a thread in this process holds such a lock */
27844   if( pFile->eFileLock>SHARED_LOCK ){
27845     reserved = 1;
27846   }
27847   
27848   /* Otherwise see if some other process holds it. */
27849   if( !reserved ){
27850     sem_t *pSem = pFile->pInode->pSem;
27851
27852     if( sem_trywait(pSem)==-1 ){
27853       int tErrno = errno;
27854       if( EAGAIN != tErrno ){
27855         rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
27856         storeLastErrno(pFile, tErrno);
27857       } else {
27858         /* someone else has the lock when we are in NO_LOCK */
27859         reserved = (pFile->eFileLock < SHARED_LOCK);
27860       }
27861     }else{
27862       /* we could have it if we want it */
27863       sem_post(pSem);
27864     }
27865   }
27866   OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
27867
27868   *pResOut = reserved;
27869   return rc;
27870 }
27871
27872 /*
27873 ** Lock the file with the lock specified by parameter eFileLock - one
27874 ** of the following:
27875 **
27876 **     (1) SHARED_LOCK
27877 **     (2) RESERVED_LOCK
27878 **     (3) PENDING_LOCK
27879 **     (4) EXCLUSIVE_LOCK
27880 **
27881 ** Sometimes when requesting one lock state, additional lock states
27882 ** are inserted in between.  The locking might fail on one of the later
27883 ** transitions leaving the lock state different from what it started but
27884 ** still short of its goal.  The following chart shows the allowed
27885 ** transitions and the inserted intermediate states:
27886 **
27887 **    UNLOCKED -> SHARED
27888 **    SHARED -> RESERVED
27889 **    SHARED -> (PENDING) -> EXCLUSIVE
27890 **    RESERVED -> (PENDING) -> EXCLUSIVE
27891 **    PENDING -> EXCLUSIVE
27892 **
27893 ** Semaphore locks only really support EXCLUSIVE locks.  We track intermediate
27894 ** lock states in the sqlite3_file structure, but all locks SHARED or
27895 ** above are really EXCLUSIVE locks and exclude all other processes from
27896 ** access the file.
27897 **
27898 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
27899 ** routine to lower a locking level.
27900 */
27901 static int semXLock(sqlite3_file *id, int eFileLock) {
27902   unixFile *pFile = (unixFile*)id;
27903   sem_t *pSem = pFile->pInode->pSem;
27904   int rc = SQLITE_OK;
27905
27906   /* if we already have a lock, it is exclusive.  
27907   ** Just adjust level and punt on outta here. */
27908   if (pFile->eFileLock > NO_LOCK) {
27909     pFile->eFileLock = eFileLock;
27910     rc = SQLITE_OK;
27911     goto sem_end_lock;
27912   }
27913   
27914   /* lock semaphore now but bail out when already locked. */
27915   if( sem_trywait(pSem)==-1 ){
27916     rc = SQLITE_BUSY;
27917     goto sem_end_lock;
27918   }
27919
27920   /* got it, set the type and return ok */
27921   pFile->eFileLock = eFileLock;
27922
27923  sem_end_lock:
27924   return rc;
27925 }
27926
27927 /*
27928 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
27929 ** must be either NO_LOCK or SHARED_LOCK.
27930 **
27931 ** If the locking level of the file descriptor is already at or below
27932 ** the requested locking level, this routine is a no-op.
27933 */
27934 static int semXUnlock(sqlite3_file *id, int eFileLock) {
27935   unixFile *pFile = (unixFile*)id;
27936   sem_t *pSem = pFile->pInode->pSem;
27937
27938   assert( pFile );
27939   assert( pSem );
27940   OSTRACE(("UNLOCK  %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
27941            pFile->eFileLock, osGetpid(0)));
27942   assert( eFileLock<=SHARED_LOCK );
27943   
27944   /* no-op if possible */
27945   if( pFile->eFileLock==eFileLock ){
27946     return SQLITE_OK;
27947   }
27948   
27949   /* shared can just be set because we always have an exclusive */
27950   if (eFileLock==SHARED_LOCK) {
27951     pFile->eFileLock = eFileLock;
27952     return SQLITE_OK;
27953   }
27954   
27955   /* no, really unlock. */
27956   if ( sem_post(pSem)==-1 ) {
27957     int rc, tErrno = errno;
27958     rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
27959     if( IS_LOCK_ERROR(rc) ){
27960       storeLastErrno(pFile, tErrno);
27961     }
27962     return rc; 
27963   }
27964   pFile->eFileLock = NO_LOCK;
27965   return SQLITE_OK;
27966 }
27967
27968 /*
27969  ** Close a file.
27970  */
27971 static int semXClose(sqlite3_file *id) {
27972   if( id ){
27973     unixFile *pFile = (unixFile*)id;
27974     semXUnlock(id, NO_LOCK);
27975     assert( pFile );
27976     unixEnterMutex();
27977     releaseInodeInfo(pFile);
27978     unixLeaveMutex();
27979     closeUnixFile(id);
27980   }
27981   return SQLITE_OK;
27982 }
27983
27984 #endif /* OS_VXWORKS */
27985 /*
27986 ** Named semaphore locking is only available on VxWorks.
27987 **
27988 *************** End of the named semaphore lock implementation ****************
27989 ******************************************************************************/
27990
27991
27992 /******************************************************************************
27993 *************************** Begin AFP Locking *********************************
27994 **
27995 ** AFP is the Apple Filing Protocol.  AFP is a network filesystem found
27996 ** on Apple Macintosh computers - both OS9 and OSX.
27997 **
27998 ** Third-party implementations of AFP are available.  But this code here
27999 ** only works on OSX.
28000 */
28001
28002 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28003 /*
28004 ** The afpLockingContext structure contains all afp lock specific state
28005 */
28006 typedef struct afpLockingContext afpLockingContext;
28007 struct afpLockingContext {
28008   int reserved;
28009   const char *dbPath;             /* Name of the open file */
28010 };
28011
28012 struct ByteRangeLockPB2
28013 {
28014   unsigned long long offset;        /* offset to first byte to lock */
28015   unsigned long long length;        /* nbr of bytes to lock */
28016   unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
28017   unsigned char unLockFlag;         /* 1 = unlock, 0 = lock */
28018   unsigned char startEndFlag;       /* 1=rel to end of fork, 0=rel to start */
28019   int fd;                           /* file desc to assoc this lock with */
28020 };
28021
28022 #define afpfsByteRangeLock2FSCTL        _IOWR('z', 23, struct ByteRangeLockPB2)
28023
28024 /*
28025 ** This is a utility for setting or clearing a bit-range lock on an
28026 ** AFP filesystem.
28027 ** 
28028 ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
28029 */
28030 static int afpSetLock(
28031   const char *path,              /* Name of the file to be locked or unlocked */
28032   unixFile *pFile,               /* Open file descriptor on path */
28033   unsigned long long offset,     /* First byte to be locked */
28034   unsigned long long length,     /* Number of bytes to lock */
28035   int setLockFlag                /* True to set lock.  False to clear lock */
28036 ){
28037   struct ByteRangeLockPB2 pb;
28038   int err;
28039   
28040   pb.unLockFlag = setLockFlag ? 0 : 1;
28041   pb.startEndFlag = 0;
28042   pb.offset = offset;
28043   pb.length = length; 
28044   pb.fd = pFile->h;
28045   
28046   OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n", 
28047     (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
28048     offset, length));
28049   err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
28050   if ( err==-1 ) {
28051     int rc;
28052     int tErrno = errno;
28053     OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
28054              path, tErrno, strerror(tErrno)));
28055 #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
28056     rc = SQLITE_BUSY;
28057 #else
28058     rc = sqliteErrorFromPosixError(tErrno,
28059                     setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
28060 #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
28061     if( IS_LOCK_ERROR(rc) ){
28062       storeLastErrno(pFile, tErrno);
28063     }
28064     return rc;
28065   } else {
28066     return SQLITE_OK;
28067   }
28068 }
28069
28070 /*
28071 ** This routine checks if there is a RESERVED lock held on the specified
28072 ** file by this or any other process. If such a lock is held, set *pResOut
28073 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
28074 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
28075 */
28076 static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
28077   int rc = SQLITE_OK;
28078   int reserved = 0;
28079   unixFile *pFile = (unixFile*)id;
28080   afpLockingContext *context;
28081   
28082   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
28083   
28084   assert( pFile );
28085   context = (afpLockingContext *) pFile->lockingContext;
28086   if( context->reserved ){
28087     *pResOut = 1;
28088     return SQLITE_OK;
28089   }
28090   unixEnterMutex(); /* Because pFile->pInode is shared across threads */
28091   
28092   /* Check if a thread in this process holds such a lock */
28093   if( pFile->pInode->eFileLock>SHARED_LOCK ){
28094     reserved = 1;
28095   }
28096   
28097   /* Otherwise see if some other process holds it.
28098    */
28099   if( !reserved ){
28100     /* lock the RESERVED byte */
28101     int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);  
28102     if( SQLITE_OK==lrc ){
28103       /* if we succeeded in taking the reserved lock, unlock it to restore
28104       ** the original state */
28105       lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
28106     } else {
28107       /* if we failed to get the lock then someone else must have it */
28108       reserved = 1;
28109     }
28110     if( IS_LOCK_ERROR(lrc) ){
28111       rc=lrc;
28112     }
28113   }
28114   
28115   unixLeaveMutex();
28116   OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
28117   
28118   *pResOut = reserved;
28119   return rc;
28120 }
28121
28122 /*
28123 ** Lock the file with the lock specified by parameter eFileLock - one
28124 ** of the following:
28125 **
28126 **     (1) SHARED_LOCK
28127 **     (2) RESERVED_LOCK
28128 **     (3) PENDING_LOCK
28129 **     (4) EXCLUSIVE_LOCK
28130 **
28131 ** Sometimes when requesting one lock state, additional lock states
28132 ** are inserted in between.  The locking might fail on one of the later
28133 ** transitions leaving the lock state different from what it started but
28134 ** still short of its goal.  The following chart shows the allowed
28135 ** transitions and the inserted intermediate states:
28136 **
28137 **    UNLOCKED -> SHARED
28138 **    SHARED -> RESERVED
28139 **    SHARED -> (PENDING) -> EXCLUSIVE
28140 **    RESERVED -> (PENDING) -> EXCLUSIVE
28141 **    PENDING -> EXCLUSIVE
28142 **
28143 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
28144 ** routine to lower a locking level.
28145 */
28146 static int afpLock(sqlite3_file *id, int eFileLock){
28147   int rc = SQLITE_OK;
28148   unixFile *pFile = (unixFile*)id;
28149   unixInodeInfo *pInode = pFile->pInode;
28150   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
28151   
28152   assert( pFile );
28153   OSTRACE(("LOCK    %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
28154            azFileLock(eFileLock), azFileLock(pFile->eFileLock),
28155            azFileLock(pInode->eFileLock), pInode->nShared , osGetpid(0)));
28156
28157   /* If there is already a lock of this type or more restrictive on the
28158   ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
28159   ** unixEnterMutex() hasn't been called yet.
28160   */
28161   if( pFile->eFileLock>=eFileLock ){
28162     OSTRACE(("LOCK    %d %s ok (already held) (afp)\n", pFile->h,
28163            azFileLock(eFileLock)));
28164     return SQLITE_OK;
28165   }
28166
28167   /* Make sure the locking sequence is correct
28168   **  (1) We never move from unlocked to anything higher than shared lock.
28169   **  (2) SQLite never explicitly requests a pendig lock.
28170   **  (3) A shared lock is always held when a reserve lock is requested.
28171   */
28172   assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
28173   assert( eFileLock!=PENDING_LOCK );
28174   assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
28175   
28176   /* This mutex is needed because pFile->pInode is shared across threads
28177   */
28178   unixEnterMutex();
28179   pInode = pFile->pInode;
28180
28181   /* If some thread using this PID has a lock via a different unixFile*
28182   ** handle that precludes the requested lock, return BUSY.
28183   */
28184   if( (pFile->eFileLock!=pInode->eFileLock && 
28185        (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
28186      ){
28187     rc = SQLITE_BUSY;
28188     goto afp_end_lock;
28189   }
28190   
28191   /* If a SHARED lock is requested, and some thread using this PID already
28192   ** has a SHARED or RESERVED lock, then increment reference counts and
28193   ** return SQLITE_OK.
28194   */
28195   if( eFileLock==SHARED_LOCK && 
28196      (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
28197     assert( eFileLock==SHARED_LOCK );
28198     assert( pFile->eFileLock==0 );
28199     assert( pInode->nShared>0 );
28200     pFile->eFileLock = SHARED_LOCK;
28201     pInode->nShared++;
28202     pInode->nLock++;
28203     goto afp_end_lock;
28204   }
28205     
28206   /* A PENDING lock is needed before acquiring a SHARED lock and before
28207   ** acquiring an EXCLUSIVE lock.  For the SHARED lock, the PENDING will
28208   ** be released.
28209   */
28210   if( eFileLock==SHARED_LOCK 
28211       || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
28212   ){
28213     int failed;
28214     failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
28215     if (failed) {
28216       rc = failed;
28217       goto afp_end_lock;
28218     }
28219   }
28220   
28221   /* If control gets to this point, then actually go ahead and make
28222   ** operating system calls for the specified lock.
28223   */
28224   if( eFileLock==SHARED_LOCK ){
28225     int lrc1, lrc2, lrc1Errno = 0;
28226     long lk, mask;
28227     
28228     assert( pInode->nShared==0 );
28229     assert( pInode->eFileLock==0 );
28230         
28231     mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
28232     /* Now get the read-lock SHARED_LOCK */
28233     /* note that the quality of the randomness doesn't matter that much */
28234     lk = random(); 
28235     pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
28236     lrc1 = afpSetLock(context->dbPath, pFile, 
28237           SHARED_FIRST+pInode->sharedByte, 1, 1);
28238     if( IS_LOCK_ERROR(lrc1) ){
28239       lrc1Errno = pFile->lastErrno;
28240     }
28241     /* Drop the temporary PENDING lock */
28242     lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
28243     
28244     if( IS_LOCK_ERROR(lrc1) ) {
28245       storeLastErrno(pFile, lrc1Errno);
28246       rc = lrc1;
28247       goto afp_end_lock;
28248     } else if( IS_LOCK_ERROR(lrc2) ){
28249       rc = lrc2;
28250       goto afp_end_lock;
28251     } else if( lrc1 != SQLITE_OK ) {
28252       rc = lrc1;
28253     } else {
28254       pFile->eFileLock = SHARED_LOCK;
28255       pInode->nLock++;
28256       pInode->nShared = 1;
28257     }
28258   }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
28259     /* We are trying for an exclusive lock but another thread in this
28260      ** same process is still holding a shared lock. */
28261     rc = SQLITE_BUSY;
28262   }else{
28263     /* The request was for a RESERVED or EXCLUSIVE lock.  It is
28264     ** assumed that there is a SHARED or greater lock on the file
28265     ** already.
28266     */
28267     int failed = 0;
28268     assert( 0!=pFile->eFileLock );
28269     if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
28270         /* Acquire a RESERVED lock */
28271         failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
28272       if( !failed ){
28273         context->reserved = 1;
28274       }
28275     }
28276     if (!failed && eFileLock == EXCLUSIVE_LOCK) {
28277       /* Acquire an EXCLUSIVE lock */
28278         
28279       /* Remove the shared lock before trying the range.  we'll need to 
28280       ** reestablish the shared lock if we can't get the  afpUnlock
28281       */
28282       if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
28283                          pInode->sharedByte, 1, 0)) ){
28284         int failed2 = SQLITE_OK;
28285         /* now attemmpt to get the exclusive lock range */
28286         failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST, 
28287                                SHARED_SIZE, 1);
28288         if( failed && (failed2 = afpSetLock(context->dbPath, pFile, 
28289                        SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
28290           /* Can't reestablish the shared lock.  Sqlite can't deal, this is
28291           ** a critical I/O error
28292           */
28293           rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 : 
28294                SQLITE_IOERR_LOCK;
28295           goto afp_end_lock;
28296         } 
28297       }else{
28298         rc = failed; 
28299       }
28300     }
28301     if( failed ){
28302       rc = failed;
28303     }
28304   }
28305   
28306   if( rc==SQLITE_OK ){
28307     pFile->eFileLock = eFileLock;
28308     pInode->eFileLock = eFileLock;
28309   }else if( eFileLock==EXCLUSIVE_LOCK ){
28310     pFile->eFileLock = PENDING_LOCK;
28311     pInode->eFileLock = PENDING_LOCK;
28312   }
28313   
28314 afp_end_lock:
28315   unixLeaveMutex();
28316   OSTRACE(("LOCK    %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock), 
28317          rc==SQLITE_OK ? "ok" : "failed"));
28318   return rc;
28319 }
28320
28321 /*
28322 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28323 ** must be either NO_LOCK or SHARED_LOCK.
28324 **
28325 ** If the locking level of the file descriptor is already at or below
28326 ** the requested locking level, this routine is a no-op.
28327 */
28328 static int afpUnlock(sqlite3_file *id, int eFileLock) {
28329   int rc = SQLITE_OK;
28330   unixFile *pFile = (unixFile*)id;
28331   unixInodeInfo *pInode;
28332   afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
28333   int skipShared = 0;
28334 #ifdef SQLITE_TEST
28335   int h = pFile->h;
28336 #endif
28337
28338   assert( pFile );
28339   OSTRACE(("UNLOCK  %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
28340            pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
28341            osGetpid(0)));
28342
28343   assert( eFileLock<=SHARED_LOCK );
28344   if( pFile->eFileLock<=eFileLock ){
28345     return SQLITE_OK;
28346   }
28347   unixEnterMutex();
28348   pInode = pFile->pInode;
28349   assert( pInode->nShared!=0 );
28350   if( pFile->eFileLock>SHARED_LOCK ){
28351     assert( pInode->eFileLock==pFile->eFileLock );
28352     SimulateIOErrorBenign(1);
28353     SimulateIOError( h=(-1) )
28354     SimulateIOErrorBenign(0);
28355     
28356 #ifdef SQLITE_DEBUG
28357     /* When reducing a lock such that other processes can start
28358     ** reading the database file again, make sure that the
28359     ** transaction counter was updated if any part of the database
28360     ** file changed.  If the transaction counter is not updated,
28361     ** other connections to the same file might not realize that
28362     ** the file has changed and hence might not know to flush their
28363     ** cache.  The use of a stale cache can lead to database corruption.
28364     */
28365     assert( pFile->inNormalWrite==0
28366            || pFile->dbUpdate==0
28367            || pFile->transCntrChng==1 );
28368     pFile->inNormalWrite = 0;
28369 #endif
28370     
28371     if( pFile->eFileLock==EXCLUSIVE_LOCK ){
28372       rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
28373       if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
28374         /* only re-establish the shared lock if necessary */
28375         int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
28376         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
28377       } else {
28378         skipShared = 1;
28379       }
28380     }
28381     if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
28382       rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
28383     } 
28384     if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
28385       rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
28386       if( !rc ){ 
28387         context->reserved = 0; 
28388       }
28389     }
28390     if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
28391       pInode->eFileLock = SHARED_LOCK;
28392     }
28393   }
28394   if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
28395
28396     /* Decrement the shared lock counter.  Release the lock using an
28397     ** OS call only when all threads in this same process have released
28398     ** the lock.
28399     */
28400     unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
28401     pInode->nShared--;
28402     if( pInode->nShared==0 ){
28403       SimulateIOErrorBenign(1);
28404       SimulateIOError( h=(-1) )
28405       SimulateIOErrorBenign(0);
28406       if( !skipShared ){
28407         rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
28408       }
28409       if( !rc ){
28410         pInode->eFileLock = NO_LOCK;
28411         pFile->eFileLock = NO_LOCK;
28412       }
28413     }
28414     if( rc==SQLITE_OK ){
28415       pInode->nLock--;
28416       assert( pInode->nLock>=0 );
28417       if( pInode->nLock==0 ){
28418         closePendingFds(pFile);
28419       }
28420     }
28421   }
28422   
28423   unixLeaveMutex();
28424   if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
28425   return rc;
28426 }
28427
28428 /*
28429 ** Close a file & cleanup AFP specific locking context 
28430 */
28431 static int afpClose(sqlite3_file *id) {
28432   int rc = SQLITE_OK;
28433   if( id ){
28434     unixFile *pFile = (unixFile*)id;
28435     afpUnlock(id, NO_LOCK);
28436     unixEnterMutex();
28437     if( pFile->pInode && pFile->pInode->nLock ){
28438       /* If there are outstanding locks, do not actually close the file just
28439       ** yet because that would clear those locks.  Instead, add the file
28440       ** descriptor to pInode->aPending.  It will be automatically closed when
28441       ** the last lock is cleared.
28442       */
28443       setPendingFd(pFile);
28444     }
28445     releaseInodeInfo(pFile);
28446     sqlite3_free(pFile->lockingContext);
28447     rc = closeUnixFile(id);
28448     unixLeaveMutex();
28449   }
28450   return rc;
28451 }
28452
28453 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28454 /*
28455 ** The code above is the AFP lock implementation.  The code is specific
28456 ** to MacOSX and does not work on other unix platforms.  No alternative
28457 ** is available.  If you don't compile for a mac, then the "unix-afp"
28458 ** VFS is not available.
28459 **
28460 ********************* End of the AFP lock implementation **********************
28461 ******************************************************************************/
28462
28463 /******************************************************************************
28464 *************************** Begin NFS Locking ********************************/
28465
28466 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
28467 /*
28468  ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
28469  ** must be either NO_LOCK or SHARED_LOCK.
28470  **
28471  ** If the locking level of the file descriptor is already at or below
28472  ** the requested locking level, this routine is a no-op.
28473  */
28474 static int nfsUnlock(sqlite3_file *id, int eFileLock){
28475   return posixUnlock(id, eFileLock, 1);
28476 }
28477
28478 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
28479 /*
28480 ** The code above is the NFS lock implementation.  The code is specific
28481 ** to MacOSX and does not work on other unix platforms.  No alternative
28482 ** is available.  
28483 **
28484 ********************* End of the NFS lock implementation **********************
28485 ******************************************************************************/
28486
28487 /******************************************************************************
28488 **************** Non-locking sqlite3_file methods *****************************
28489 **
28490 ** The next division contains implementations for all methods of the 
28491 ** sqlite3_file object other than the locking methods.  The locking
28492 ** methods were defined in divisions above (one locking method per
28493 ** division).  Those methods that are common to all locking modes
28494 ** are gather together into this division.
28495 */
28496
28497 /*
28498 ** Seek to the offset passed as the second argument, then read cnt 
28499 ** bytes into pBuf. Return the number of bytes actually read.
28500 **
28501 ** NB:  If you define USE_PREAD or USE_PREAD64, then it might also
28502 ** be necessary to define _XOPEN_SOURCE to be 500.  This varies from
28503 ** one system to another.  Since SQLite does not define USE_PREAD
28504 ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
28505 ** See tickets #2741 and #2681.
28506 **
28507 ** To avoid stomping the errno value on a failed read the lastErrno value
28508 ** is set before returning.
28509 */
28510 static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
28511   int got;
28512   int prior = 0;
28513 #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
28514   i64 newOffset;
28515 #endif
28516   TIMER_START;
28517   assert( cnt==(cnt&0x1ffff) );
28518   assert( id->h>2 );
28519   cnt &= 0x1ffff;
28520   do{
28521 #if defined(USE_PREAD)
28522     got = osPread(id->h, pBuf, cnt, offset);
28523     SimulateIOError( got = -1 );
28524 #elif defined(USE_PREAD64)
28525     got = osPread64(id->h, pBuf, cnt, offset);
28526     SimulateIOError( got = -1 );
28527 #else
28528     newOffset = lseek(id->h, offset, SEEK_SET);
28529     SimulateIOError( newOffset-- );
28530     if( newOffset!=offset ){
28531       if( newOffset == -1 ){
28532         storeLastErrno((unixFile*)id, errno);
28533       }else{
28534         storeLastErrno((unixFile*)id, 0);
28535       }
28536       return -1;
28537     }
28538     got = osRead(id->h, pBuf, cnt);
28539 #endif
28540     if( got==cnt ) break;
28541     if( got<0 ){
28542       if( errno==EINTR ){ got = 1; continue; }
28543       prior = 0;
28544       storeLastErrno((unixFile*)id,  errno);
28545       break;
28546     }else if( got>0 ){
28547       cnt -= got;
28548       offset += got;
28549       prior += got;
28550       pBuf = (void*)(got + (char*)pBuf);
28551     }
28552   }while( got>0 );
28553   TIMER_END;
28554   OSTRACE(("READ    %-3d %5d %7lld %llu\n",
28555             id->h, got+prior, offset-prior, TIMER_ELAPSED));
28556   return got+prior;
28557 }
28558
28559 /*
28560 ** Read data from a file into a buffer.  Return SQLITE_OK if all
28561 ** bytes were read successfully and SQLITE_IOERR if anything goes
28562 ** wrong.
28563 */
28564 static int unixRead(
28565   sqlite3_file *id, 
28566   void *pBuf, 
28567   int amt,
28568   sqlite3_int64 offset
28569 ){
28570   unixFile *pFile = (unixFile *)id;
28571   int got;
28572   assert( id );
28573   assert( offset>=0 );
28574   assert( amt>0 );
28575
28576   /* If this is a database file (not a journal, master-journal or temp
28577   ** file), the bytes in the locking range should never be read or written. */
28578 #if 0
28579   assert( pFile->pUnused==0
28580        || offset>=PENDING_BYTE+512
28581        || offset+amt<=PENDING_BYTE 
28582   );
28583 #endif
28584
28585 #if SQLITE_MAX_MMAP_SIZE>0
28586   /* Deal with as much of this read request as possible by transfering
28587   ** data from the memory mapping using memcpy().  */
28588   if( offset<pFile->mmapSize ){
28589     if( offset+amt <= pFile->mmapSize ){
28590       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
28591       return SQLITE_OK;
28592     }else{
28593       int nCopy = pFile->mmapSize - offset;
28594       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
28595       pBuf = &((u8 *)pBuf)[nCopy];
28596       amt -= nCopy;
28597       offset += nCopy;
28598     }
28599   }
28600 #endif
28601
28602   got = seekAndRead(pFile, offset, pBuf, amt);
28603   if( got==amt ){
28604     return SQLITE_OK;
28605   }else if( got<0 ){
28606     /* lastErrno set by seekAndRead */
28607     return SQLITE_IOERR_READ;
28608   }else{
28609     storeLastErrno(pFile, 0);   /* not a system error */
28610     /* Unread parts of the buffer must be zero-filled */
28611     memset(&((char*)pBuf)[got], 0, amt-got);
28612     return SQLITE_IOERR_SHORT_READ;
28613   }
28614 }
28615
28616 /*
28617 ** Attempt to seek the file-descriptor passed as the first argument to
28618 ** absolute offset iOff, then attempt to write nBuf bytes of data from
28619 ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise, 
28620 ** return the actual number of bytes written (which may be less than
28621 ** nBuf).
28622 */
28623 static int seekAndWriteFd(
28624   int fd,                         /* File descriptor to write to */
28625   i64 iOff,                       /* File offset to begin writing at */
28626   const void *pBuf,               /* Copy data from this buffer to the file */
28627   int nBuf,                       /* Size of buffer pBuf in bytes */
28628   int *piErrno                    /* OUT: Error number if error occurs */
28629 ){
28630   int rc = 0;                     /* Value returned by system call */
28631
28632   assert( nBuf==(nBuf&0x1ffff) );
28633   assert( fd>2 );
28634   nBuf &= 0x1ffff;
28635   TIMER_START;
28636
28637 #if defined(USE_PREAD)
28638   do{ rc = (int)osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
28639 #elif defined(USE_PREAD64)
28640   do{ rc = (int)osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
28641 #else
28642   do{
28643     i64 iSeek = lseek(fd, iOff, SEEK_SET);
28644     SimulateIOError( iSeek-- );
28645
28646     if( iSeek!=iOff ){
28647       if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
28648       return -1;
28649     }
28650     rc = osWrite(fd, pBuf, nBuf);
28651   }while( rc<0 && errno==EINTR );
28652 #endif
28653
28654   TIMER_END;
28655   OSTRACE(("WRITE   %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
28656
28657   if( rc<0 && piErrno ) *piErrno = errno;
28658   return rc;
28659 }
28660
28661
28662 /*
28663 ** Seek to the offset in id->offset then read cnt bytes into pBuf.
28664 ** Return the number of bytes actually read.  Update the offset.
28665 **
28666 ** To avoid stomping the errno value on a failed write the lastErrno value
28667 ** is set before returning.
28668 */
28669 static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
28670   return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
28671 }
28672
28673
28674 /*
28675 ** Write data from a buffer into a file.  Return SQLITE_OK on success
28676 ** or some other error code on failure.
28677 */
28678 static int unixWrite(
28679   sqlite3_file *id, 
28680   const void *pBuf, 
28681   int amt,
28682   sqlite3_int64 offset 
28683 ){
28684   unixFile *pFile = (unixFile*)id;
28685   int wrote = 0;
28686   assert( id );
28687   assert( amt>0 );
28688
28689   /* If this is a database file (not a journal, master-journal or temp
28690   ** file), the bytes in the locking range should never be read or written. */
28691 #if 0
28692   assert( pFile->pUnused==0
28693        || offset>=PENDING_BYTE+512
28694        || offset+amt<=PENDING_BYTE 
28695   );
28696 #endif
28697
28698 #ifdef SQLITE_DEBUG
28699   /* If we are doing a normal write to a database file (as opposed to
28700   ** doing a hot-journal rollback or a write to some file other than a
28701   ** normal database file) then record the fact that the database
28702   ** has changed.  If the transaction counter is modified, record that
28703   ** fact too.
28704   */
28705   if( pFile->inNormalWrite ){
28706     pFile->dbUpdate = 1;  /* The database has been modified */
28707     if( offset<=24 && offset+amt>=27 ){
28708       int rc;
28709       char oldCntr[4];
28710       SimulateIOErrorBenign(1);
28711       rc = seekAndRead(pFile, 24, oldCntr, 4);
28712       SimulateIOErrorBenign(0);
28713       if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
28714         pFile->transCntrChng = 1;  /* The transaction counter has changed */
28715       }
28716     }
28717   }
28718 #endif
28719
28720 #if SQLITE_MAX_MMAP_SIZE>0
28721   /* Deal with as much of this write request as possible by transfering
28722   ** data from the memory mapping using memcpy().  */
28723   if( offset<pFile->mmapSize ){
28724     if( offset+amt <= pFile->mmapSize ){
28725       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
28726       return SQLITE_OK;
28727     }else{
28728       int nCopy = pFile->mmapSize - offset;
28729       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
28730       pBuf = &((u8 *)pBuf)[nCopy];
28731       amt -= nCopy;
28732       offset += nCopy;
28733     }
28734   }
28735 #endif
28736
28737   while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
28738     amt -= wrote;
28739     offset += wrote;
28740     pBuf = &((char*)pBuf)[wrote];
28741   }
28742   SimulateIOError(( wrote=(-1), amt=1 ));
28743   SimulateDiskfullError(( wrote=0, amt=1 ));
28744
28745   if( amt>0 ){
28746     if( wrote<0 && pFile->lastErrno!=ENOSPC ){
28747       /* lastErrno set by seekAndWrite */
28748       return SQLITE_IOERR_WRITE;
28749     }else{
28750       storeLastErrno(pFile, 0); /* not a system error */
28751       return SQLITE_FULL;
28752     }
28753   }
28754
28755   return SQLITE_OK;
28756 }
28757
28758 #ifdef SQLITE_TEST
28759 /*
28760 ** Count the number of fullsyncs and normal syncs.  This is used to test
28761 ** that syncs and fullsyncs are occurring at the right times.
28762 */
28763 SQLITE_API int sqlite3_sync_count = 0;
28764 SQLITE_API int sqlite3_fullsync_count = 0;
28765 #endif
28766
28767 /*
28768 ** We do not trust systems to provide a working fdatasync().  Some do.
28769 ** Others do no.  To be safe, we will stick with the (slightly slower)
28770 ** fsync(). If you know that your system does support fdatasync() correctly,
28771 ** then simply compile with -Dfdatasync=fdatasync or -DHAVE_FDATASYNC
28772 */
28773 #if !defined(fdatasync) && !HAVE_FDATASYNC
28774 # define fdatasync fsync
28775 #endif
28776
28777 /*
28778 ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
28779 ** the F_FULLFSYNC macro is defined.  F_FULLFSYNC is currently
28780 ** only available on Mac OS X.  But that could change.
28781 */
28782 #ifdef F_FULLFSYNC
28783 # define HAVE_FULLFSYNC 1
28784 #else
28785 # define HAVE_FULLFSYNC 0
28786 #endif
28787
28788
28789 /*
28790 ** The fsync() system call does not work as advertised on many
28791 ** unix systems.  The following procedure is an attempt to make
28792 ** it work better.
28793 **
28794 ** The SQLITE_NO_SYNC macro disables all fsync()s.  This is useful
28795 ** for testing when we want to run through the test suite quickly.
28796 ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
28797 ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
28798 ** or power failure will likely corrupt the database file.
28799 **
28800 ** SQLite sets the dataOnly flag if the size of the file is unchanged.
28801 ** The idea behind dataOnly is that it should only write the file content
28802 ** to disk, not the inode.  We only set dataOnly if the file size is 
28803 ** unchanged since the file size is part of the inode.  However, 
28804 ** Ted Ts'o tells us that fdatasync() will also write the inode if the
28805 ** file size has changed.  The only real difference between fdatasync()
28806 ** and fsync(), Ted tells us, is that fdatasync() will not flush the
28807 ** inode if the mtime or owner or other inode attributes have changed.
28808 ** We only care about the file size, not the other file attributes, so
28809 ** as far as SQLite is concerned, an fdatasync() is always adequate.
28810 ** So, we always use fdatasync() if it is available, regardless of
28811 ** the value of the dataOnly flag.
28812 */
28813 static int full_fsync(int fd, int fullSync, int dataOnly){
28814   int rc;
28815
28816   /* The following "ifdef/elif/else/" block has the same structure as
28817   ** the one below. It is replicated here solely to avoid cluttering 
28818   ** up the real code with the UNUSED_PARAMETER() macros.
28819   */
28820 #ifdef SQLITE_NO_SYNC
28821   UNUSED_PARAMETER(fd);
28822   UNUSED_PARAMETER(fullSync);
28823   UNUSED_PARAMETER(dataOnly);
28824 #elif HAVE_FULLFSYNC
28825   UNUSED_PARAMETER(dataOnly);
28826 #else
28827   UNUSED_PARAMETER(fullSync);
28828   UNUSED_PARAMETER(dataOnly);
28829 #endif
28830
28831   /* Record the number of times that we do a normal fsync() and 
28832   ** FULLSYNC.  This is used during testing to verify that this procedure
28833   ** gets called with the correct arguments.
28834   */
28835 #ifdef SQLITE_TEST
28836   if( fullSync ) sqlite3_fullsync_count++;
28837   sqlite3_sync_count++;
28838 #endif
28839
28840   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
28841   ** no-op
28842   */
28843 #ifdef SQLITE_NO_SYNC
28844   rc = SQLITE_OK;
28845 #elif HAVE_FULLFSYNC
28846   if( fullSync ){
28847     rc = osFcntl(fd, F_FULLFSYNC, 0);
28848   }else{
28849     rc = 1;
28850   }
28851   /* If the FULLFSYNC failed, fall back to attempting an fsync().
28852   ** It shouldn't be possible for fullfsync to fail on the local 
28853   ** file system (on OSX), so failure indicates that FULLFSYNC
28854   ** isn't supported for this file system. So, attempt an fsync 
28855   ** and (for now) ignore the overhead of a superfluous fcntl call.  
28856   ** It'd be better to detect fullfsync support once and avoid 
28857   ** the fcntl call every time sync is called.
28858   */
28859   if( rc ) rc = fsync(fd);
28860
28861 #elif defined(__APPLE__)
28862   /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
28863   ** so currently we default to the macro that redefines fdatasync to fsync
28864   */
28865   rc = fsync(fd);
28866 #else 
28867   rc = fdatasync(fd);
28868 #if OS_VXWORKS
28869   if( rc==-1 && errno==ENOTSUP ){
28870     rc = fsync(fd);
28871   }
28872 #endif /* OS_VXWORKS */
28873 #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
28874
28875   if( OS_VXWORKS && rc!= -1 ){
28876     rc = 0;
28877   }
28878   return rc;
28879 }
28880
28881 /*
28882 ** Open a file descriptor to the directory containing file zFilename.
28883 ** If successful, *pFd is set to the opened file descriptor and
28884 ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
28885 ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
28886 ** value.
28887 **
28888 ** The directory file descriptor is used for only one thing - to
28889 ** fsync() a directory to make sure file creation and deletion events
28890 ** are flushed to disk.  Such fsyncs are not needed on newer
28891 ** journaling filesystems, but are required on older filesystems.
28892 **
28893 ** This routine can be overridden using the xSetSysCall interface.
28894 ** The ability to override this routine was added in support of the
28895 ** chromium sandbox.  Opening a directory is a security risk (we are
28896 ** told) so making it overrideable allows the chromium sandbox to
28897 ** replace this routine with a harmless no-op.  To make this routine
28898 ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
28899 ** *pFd set to a negative number.
28900 **
28901 ** If SQLITE_OK is returned, the caller is responsible for closing
28902 ** the file descriptor *pFd using close().
28903 */
28904 static int openDirectory(const char *zFilename, int *pFd){
28905   int ii;
28906   int fd = -1;
28907   char zDirname[MAX_PATHNAME+1];
28908
28909   sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
28910   for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
28911   if( ii>0 ){
28912     zDirname[ii] = '\0';
28913     fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
28914     if( fd>=0 ){
28915       OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
28916     }
28917   }
28918   *pFd = fd;
28919   return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
28920 }
28921
28922 /*
28923 ** Make sure all writes to a particular file are committed to disk.
28924 **
28925 ** If dataOnly==0 then both the file itself and its metadata (file
28926 ** size, access time, etc) are synced.  If dataOnly!=0 then only the
28927 ** file data is synced.
28928 **
28929 ** Under Unix, also make sure that the directory entry for the file
28930 ** has been created by fsync-ing the directory that contains the file.
28931 ** If we do not do this and we encounter a power failure, the directory
28932 ** entry for the journal might not exist after we reboot.  The next
28933 ** SQLite to access the file will not know that the journal exists (because
28934 ** the directory entry for the journal was never created) and the transaction
28935 ** will not roll back - possibly leading to database corruption.
28936 */
28937 static int unixSync(sqlite3_file *id, int flags){
28938   int rc;
28939   unixFile *pFile = (unixFile*)id;
28940
28941   int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
28942   int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
28943
28944   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
28945   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
28946       || (flags&0x0F)==SQLITE_SYNC_FULL
28947   );
28948
28949   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
28950   ** line is to test that doing so does not cause any problems.
28951   */
28952   SimulateDiskfullError( return SQLITE_FULL );
28953
28954   assert( pFile );
28955   OSTRACE(("SYNC    %-3d\n", pFile->h));
28956   rc = full_fsync(pFile->h, isFullsync, isDataOnly);
28957   SimulateIOError( rc=1 );
28958   if( rc ){
28959     storeLastErrno(pFile, errno);
28960     return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
28961   }
28962
28963   /* Also fsync the directory containing the file if the DIRSYNC flag
28964   ** is set.  This is a one-time occurrence.  Many systems (examples: AIX)
28965   ** are unable to fsync a directory, so ignore errors on the fsync.
28966   */
28967   if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
28968     int dirfd;
28969     OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
28970             HAVE_FULLFSYNC, isFullsync));
28971     rc = osOpenDirectory(pFile->zPath, &dirfd);
28972     if( rc==SQLITE_OK && dirfd>=0 ){
28973       full_fsync(dirfd, 0, 0);
28974       robust_close(pFile, dirfd, __LINE__);
28975     }else if( rc==SQLITE_CANTOPEN ){
28976       rc = SQLITE_OK;
28977     }
28978     pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
28979   }
28980   return rc;
28981 }
28982
28983 /*
28984 ** Truncate an open file to a specified size
28985 */
28986 static int unixTruncate(sqlite3_file *id, i64 nByte){
28987   unixFile *pFile = (unixFile *)id;
28988   int rc;
28989   assert( pFile );
28990   SimulateIOError( return SQLITE_IOERR_TRUNCATE );
28991
28992   /* If the user has configured a chunk-size for this file, truncate the
28993   ** file so that it consists of an integer number of chunks (i.e. the
28994   ** actual file size after the operation may be larger than the requested
28995   ** size).
28996   */
28997   if( pFile->szChunk>0 ){
28998     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
28999   }
29000
29001   rc = robust_ftruncate(pFile->h, nByte);
29002   if( rc ){
29003     storeLastErrno(pFile, errno);
29004     return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
29005   }else{
29006 #ifdef SQLITE_DEBUG
29007     /* If we are doing a normal write to a database file (as opposed to
29008     ** doing a hot-journal rollback or a write to some file other than a
29009     ** normal database file) and we truncate the file to zero length,
29010     ** that effectively updates the change counter.  This might happen
29011     ** when restoring a database using the backup API from a zero-length
29012     ** source.
29013     */
29014     if( pFile->inNormalWrite && nByte==0 ){
29015       pFile->transCntrChng = 1;
29016     }
29017 #endif
29018
29019 #if SQLITE_MAX_MMAP_SIZE>0
29020     /* If the file was just truncated to a size smaller than the currently
29021     ** mapped region, reduce the effective mapping size as well. SQLite will
29022     ** use read() and write() to access data beyond this point from now on.  
29023     */
29024     if( nByte<pFile->mmapSize ){
29025       pFile->mmapSize = nByte;
29026     }
29027 #endif
29028
29029     return SQLITE_OK;
29030   }
29031 }
29032
29033 /*
29034 ** Determine the current size of a file in bytes
29035 */
29036 static int unixFileSize(sqlite3_file *id, i64 *pSize){
29037   int rc;
29038   struct stat buf;
29039   assert( id );
29040   rc = osFstat(((unixFile*)id)->h, &buf);
29041   SimulateIOError( rc=1 );
29042   if( rc!=0 ){
29043     storeLastErrno((unixFile*)id, errno);
29044     return SQLITE_IOERR_FSTAT;
29045   }
29046   *pSize = buf.st_size;
29047
29048   /* When opening a zero-size database, the findInodeInfo() procedure
29049   ** writes a single byte into that file in order to work around a bug
29050   ** in the OS-X msdos filesystem.  In order to avoid problems with upper
29051   ** layers, we need to report this file size as zero even though it is
29052   ** really 1.   Ticket #3260.
29053   */
29054   if( *pSize==1 ) *pSize = 0;
29055
29056
29057   return SQLITE_OK;
29058 }
29059
29060 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29061 /*
29062 ** Handler for proxy-locking file-control verbs.  Defined below in the
29063 ** proxying locking division.
29064 */
29065 static int proxyFileControl(sqlite3_file*,int,void*);
29066 #endif
29067
29068 /* 
29069 ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT 
29070 ** file-control operation.  Enlarge the database to nBytes in size
29071 ** (rounded up to the next chunk-size).  If the database is already
29072 ** nBytes or larger, this routine is a no-op.
29073 */
29074 static int fcntlSizeHint(unixFile *pFile, i64 nByte){
29075   if( pFile->szChunk>0 ){
29076     i64 nSize;                    /* Required file size */
29077     struct stat buf;              /* Used to hold return values of fstat() */
29078    
29079     if( osFstat(pFile->h, &buf) ){
29080       return SQLITE_IOERR_FSTAT;
29081     }
29082
29083     nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
29084     if( nSize>(i64)buf.st_size ){
29085
29086 #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
29087       /* The code below is handling the return value of osFallocate() 
29088       ** correctly. posix_fallocate() is defined to "returns zero on success, 
29089       ** or an error number on  failure". See the manpage for details. */
29090       int err;
29091       do{
29092         err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
29093       }while( err==EINTR );
29094       if( err ) return SQLITE_IOERR_WRITE;
29095 #else
29096       /* If the OS does not have posix_fallocate(), fake it. Write a 
29097       ** single byte to the last byte in each block that falls entirely
29098       ** within the extended region. Then, if required, a single byte
29099       ** at offset (nSize-1), to set the size of the file correctly.
29100       ** This is a similar technique to that used by glibc on systems
29101       ** that do not have a real fallocate() call.
29102       */
29103       int nBlk = buf.st_blksize;  /* File-system block size */
29104       int nWrite = 0;             /* Number of bytes written by seekAndWrite */
29105       i64 iWrite;                 /* Next offset to write to */
29106
29107       iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
29108       assert( iWrite>=buf.st_size );
29109       assert( (iWrite/nBlk)==((buf.st_size+nBlk-1)/nBlk) );
29110       assert( ((iWrite+1)%nBlk)==0 );
29111       for(/*no-op*/; iWrite<nSize; iWrite+=nBlk ){
29112         nWrite = seekAndWrite(pFile, iWrite, "", 1);
29113         if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
29114       }
29115       if( nWrite==0 || (nSize%nBlk) ){
29116         nWrite = seekAndWrite(pFile, nSize-1, "", 1);
29117         if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
29118       }
29119 #endif
29120     }
29121   }
29122
29123 #if SQLITE_MAX_MMAP_SIZE>0
29124   if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
29125     int rc;
29126     if( pFile->szChunk<=0 ){
29127       if( robust_ftruncate(pFile->h, nByte) ){
29128         storeLastErrno(pFile, errno);
29129         return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
29130       }
29131     }
29132
29133     rc = unixMapfile(pFile, nByte);
29134     return rc;
29135   }
29136 #endif
29137
29138   return SQLITE_OK;
29139 }
29140
29141 /*
29142 ** If *pArg is initially negative then this is a query.  Set *pArg to
29143 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
29144 **
29145 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
29146 */
29147 static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
29148   if( *pArg<0 ){
29149     *pArg = (pFile->ctrlFlags & mask)!=0;
29150   }else if( (*pArg)==0 ){
29151     pFile->ctrlFlags &= ~mask;
29152   }else{
29153     pFile->ctrlFlags |= mask;
29154   }
29155 }
29156
29157 /* Forward declaration */
29158 static int unixGetTempname(int nBuf, char *zBuf);
29159
29160 /*
29161 ** Information and control of an open file handle.
29162 */
29163 static int unixFileControl(sqlite3_file *id, int op, void *pArg){
29164   unixFile *pFile = (unixFile*)id;
29165   switch( op ){
29166     case SQLITE_FCNTL_WAL_BLOCK: {
29167       /* pFile->ctrlFlags |= UNIXFILE_BLOCK; // Deferred feature */
29168       return SQLITE_OK;
29169     }
29170     case SQLITE_FCNTL_LOCKSTATE: {
29171       *(int*)pArg = pFile->eFileLock;
29172       return SQLITE_OK;
29173     }
29174     case SQLITE_FCNTL_LAST_ERRNO: {
29175       *(int*)pArg = pFile->lastErrno;
29176       return SQLITE_OK;
29177     }
29178     case SQLITE_FCNTL_CHUNK_SIZE: {
29179       pFile->szChunk = *(int *)pArg;
29180       return SQLITE_OK;
29181     }
29182     case SQLITE_FCNTL_SIZE_HINT: {
29183       int rc;
29184       SimulateIOErrorBenign(1);
29185       rc = fcntlSizeHint(pFile, *(i64 *)pArg);
29186       SimulateIOErrorBenign(0);
29187       return rc;
29188     }
29189     case SQLITE_FCNTL_PERSIST_WAL: {
29190       unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
29191       return SQLITE_OK;
29192     }
29193     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
29194       unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
29195       return SQLITE_OK;
29196     }
29197     case SQLITE_FCNTL_VFSNAME: {
29198       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
29199       return SQLITE_OK;
29200     }
29201     case SQLITE_FCNTL_TEMPFILENAME: {
29202       char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
29203       if( zTFile ){
29204         unixGetTempname(pFile->pVfs->mxPathname, zTFile);
29205         *(char**)pArg = zTFile;
29206       }
29207       return SQLITE_OK;
29208     }
29209     case SQLITE_FCNTL_HAS_MOVED: {
29210       *(int*)pArg = fileHasMoved(pFile);
29211       return SQLITE_OK;
29212     }
29213 #if SQLITE_MAX_MMAP_SIZE>0
29214     case SQLITE_FCNTL_MMAP_SIZE: {
29215       i64 newLimit = *(i64*)pArg;
29216       int rc = SQLITE_OK;
29217       if( newLimit>sqlite3GlobalConfig.mxMmap ){
29218         newLimit = sqlite3GlobalConfig.mxMmap;
29219       }
29220       *(i64*)pArg = pFile->mmapSizeMax;
29221       if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
29222         pFile->mmapSizeMax = newLimit;
29223         if( pFile->mmapSize>0 ){
29224           unixUnmapfile(pFile);
29225           rc = unixMapfile(pFile, -1);
29226         }
29227       }
29228       return rc;
29229     }
29230 #endif
29231 #ifdef SQLITE_DEBUG
29232     /* The pager calls this method to signal that it has done
29233     ** a rollback and that the database is therefore unchanged and
29234     ** it hence it is OK for the transaction change counter to be
29235     ** unchanged.
29236     */
29237     case SQLITE_FCNTL_DB_UNCHANGED: {
29238       ((unixFile*)id)->dbUpdate = 0;
29239       return SQLITE_OK;
29240     }
29241 #endif
29242 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
29243     case SQLITE_FCNTL_SET_LOCKPROXYFILE:
29244     case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
29245       return proxyFileControl(id,op,pArg);
29246     }
29247 #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
29248   }
29249   return SQLITE_NOTFOUND;
29250 }
29251
29252 /*
29253 ** Return the sector size in bytes of the underlying block device for
29254 ** the specified file. This is almost always 512 bytes, but may be
29255 ** larger for some devices.
29256 **
29257 ** SQLite code assumes this function cannot fail. It also assumes that
29258 ** if two files are created in the same file-system directory (i.e.
29259 ** a database and its journal file) that the sector size will be the
29260 ** same for both.
29261 */
29262 #ifndef __QNXNTO__ 
29263 static int unixSectorSize(sqlite3_file *NotUsed){
29264   UNUSED_PARAMETER(NotUsed);
29265   return SQLITE_DEFAULT_SECTOR_SIZE;
29266 }
29267 #endif
29268
29269 /*
29270 ** The following version of unixSectorSize() is optimized for QNX.
29271 */
29272 #ifdef __QNXNTO__
29273 #include <sys/dcmd_blk.h>
29274 #include <sys/statvfs.h>
29275 static int unixSectorSize(sqlite3_file *id){
29276   unixFile *pFile = (unixFile*)id;
29277   if( pFile->sectorSize == 0 ){
29278     struct statvfs fsInfo;
29279        
29280     /* Set defaults for non-supported filesystems */
29281     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
29282     pFile->deviceCharacteristics = 0;
29283     if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
29284       return pFile->sectorSize;
29285     }
29286
29287     if( !strcmp(fsInfo.f_basetype, "tmp") ) {
29288       pFile->sectorSize = fsInfo.f_bsize;
29289       pFile->deviceCharacteristics =
29290         SQLITE_IOCAP_ATOMIC4K |       /* All ram filesystem writes are atomic */
29291         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
29292                                       ** the write succeeds */
29293         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
29294                                       ** so it is ordered */
29295         0;
29296     }else if( strstr(fsInfo.f_basetype, "etfs") ){
29297       pFile->sectorSize = fsInfo.f_bsize;
29298       pFile->deviceCharacteristics =
29299         /* etfs cluster size writes are atomic */
29300         (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
29301         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
29302                                       ** the write succeeds */
29303         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
29304                                       ** so it is ordered */
29305         0;
29306     }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
29307       pFile->sectorSize = fsInfo.f_bsize;
29308       pFile->deviceCharacteristics =
29309         SQLITE_IOCAP_ATOMIC |         /* All filesystem writes are atomic */
29310         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
29311                                       ** the write succeeds */
29312         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
29313                                       ** so it is ordered */
29314         0;
29315     }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
29316       pFile->sectorSize = fsInfo.f_bsize;
29317       pFile->deviceCharacteristics =
29318         /* full bitset of atomics from max sector size and smaller */
29319         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
29320         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
29321                                       ** so it is ordered */
29322         0;
29323     }else if( strstr(fsInfo.f_basetype, "dos") ){
29324       pFile->sectorSize = fsInfo.f_bsize;
29325       pFile->deviceCharacteristics =
29326         /* full bitset of atomics from max sector size and smaller */
29327         ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
29328         SQLITE_IOCAP_SEQUENTIAL |     /* The ram filesystem has no write behind
29329                                       ** so it is ordered */
29330         0;
29331     }else{
29332       pFile->deviceCharacteristics =
29333         SQLITE_IOCAP_ATOMIC512 |      /* blocks are atomic */
29334         SQLITE_IOCAP_SAFE_APPEND |    /* growing the file does not occur until
29335                                       ** the write succeeds */
29336         0;
29337     }
29338   }
29339   /* Last chance verification.  If the sector size isn't a multiple of 512
29340   ** then it isn't valid.*/
29341   if( pFile->sectorSize % 512 != 0 ){
29342     pFile->deviceCharacteristics = 0;
29343     pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
29344   }
29345   return pFile->sectorSize;
29346 }
29347 #endif /* __QNXNTO__ */
29348
29349 /*
29350 ** Return the device characteristics for the file.
29351 **
29352 ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
29353 ** However, that choice is controversial since technically the underlying
29354 ** file system does not always provide powersafe overwrites.  (In other
29355 ** words, after a power-loss event, parts of the file that were never
29356 ** written might end up being altered.)  However, non-PSOW behavior is very,
29357 ** very rare.  And asserting PSOW makes a large reduction in the amount
29358 ** of required I/O for journaling, since a lot of padding is eliminated.
29359 **  Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
29360 ** available to turn it off and URI query parameter available to turn it off.
29361 */
29362 static int unixDeviceCharacteristics(sqlite3_file *id){
29363   unixFile *p = (unixFile*)id;
29364   int rc = 0;
29365 #ifdef __QNXNTO__
29366   if( p->sectorSize==0 ) unixSectorSize(id);
29367   rc = p->deviceCharacteristics;
29368 #endif
29369   if( p->ctrlFlags & UNIXFILE_PSOW ){
29370     rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
29371   }
29372   return rc;
29373 }
29374
29375 #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
29376
29377 /*
29378 ** Return the system page size.
29379 **
29380 ** This function should not be called directly by other code in this file. 
29381 ** Instead, it should be called via macro osGetpagesize().
29382 */
29383 static int unixGetpagesize(void){
29384 #if OS_VXWORKS
29385   return 1024;
29386 #elif defined(_BSD_SOURCE)
29387   return getpagesize();
29388 #else
29389   return (int)sysconf(_SC_PAGESIZE);
29390 #endif
29391 }
29392
29393 #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
29394
29395 #ifndef SQLITE_OMIT_WAL
29396
29397 /*
29398 ** Object used to represent an shared memory buffer.  
29399 **
29400 ** When multiple threads all reference the same wal-index, each thread
29401 ** has its own unixShm object, but they all point to a single instance
29402 ** of this unixShmNode object.  In other words, each wal-index is opened
29403 ** only once per process.
29404 **
29405 ** Each unixShmNode object is connected to a single unixInodeInfo object.
29406 ** We could coalesce this object into unixInodeInfo, but that would mean
29407 ** every open file that does not use shared memory (in other words, most
29408 ** open files) would have to carry around this extra information.  So
29409 ** the unixInodeInfo object contains a pointer to this unixShmNode object
29410 ** and the unixShmNode object is created only when needed.
29411 **
29412 ** unixMutexHeld() must be true when creating or destroying
29413 ** this object or while reading or writing the following fields:
29414 **
29415 **      nRef
29416 **
29417 ** The following fields are read-only after the object is created:
29418 ** 
29419 **      fid
29420 **      zFilename
29421 **
29422 ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
29423 ** unixMutexHeld() is true when reading or writing any other field
29424 ** in this structure.
29425 */
29426 struct unixShmNode {
29427   unixInodeInfo *pInode;     /* unixInodeInfo that owns this SHM node */
29428   sqlite3_mutex *mutex;      /* Mutex to access this object */
29429   char *zFilename;           /* Name of the mmapped file */
29430   int h;                     /* Open file descriptor */
29431   int szRegion;              /* Size of shared-memory regions */
29432   u16 nRegion;               /* Size of array apRegion */
29433   u8 isReadonly;             /* True if read-only */
29434   char **apRegion;           /* Array of mapped shared-memory regions */
29435   int nRef;                  /* Number of unixShm objects pointing to this */
29436   unixShm *pFirst;           /* All unixShm objects pointing to this */
29437 #ifdef SQLITE_DEBUG
29438   u8 exclMask;               /* Mask of exclusive locks held */
29439   u8 sharedMask;             /* Mask of shared locks held */
29440   u8 nextShmId;              /* Next available unixShm.id value */
29441 #endif
29442 };
29443
29444 /*
29445 ** Structure used internally by this VFS to record the state of an
29446 ** open shared memory connection.
29447 **
29448 ** The following fields are initialized when this object is created and
29449 ** are read-only thereafter:
29450 **
29451 **    unixShm.pFile
29452 **    unixShm.id
29453 **
29454 ** All other fields are read/write.  The unixShm.pFile->mutex must be held
29455 ** while accessing any read/write fields.
29456 */
29457 struct unixShm {
29458   unixShmNode *pShmNode;     /* The underlying unixShmNode object */
29459   unixShm *pNext;            /* Next unixShm with the same unixShmNode */
29460   u8 hasMutex;               /* True if holding the unixShmNode mutex */
29461   u8 id;                     /* Id of this connection within its unixShmNode */
29462   u16 sharedMask;            /* Mask of shared locks held */
29463   u16 exclMask;              /* Mask of exclusive locks held */
29464 };
29465
29466 /*
29467 ** Constants used for locking
29468 */
29469 #define UNIX_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)         /* first lock byte */
29470 #define UNIX_SHM_DMS    (UNIX_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
29471
29472 /*
29473 ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
29474 **
29475 ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
29476 ** otherwise.
29477 */
29478 static int unixShmSystemLock(
29479   unixFile *pFile,       /* Open connection to the WAL file */
29480   int lockType,          /* F_UNLCK, F_RDLCK, or F_WRLCK */
29481   int ofst,              /* First byte of the locking range */
29482   int n                  /* Number of bytes to lock */
29483 ){
29484   unixShmNode *pShmNode; /* Apply locks to this open shared-memory segment */
29485   struct flock f;        /* The posix advisory locking structure */
29486   int rc = SQLITE_OK;    /* Result code form fcntl() */
29487
29488   /* Access to the unixShmNode object is serialized by the caller */
29489   pShmNode = pFile->pInode->pShmNode;
29490   assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
29491
29492   /* Shared locks never span more than one byte */
29493   assert( n==1 || lockType!=F_RDLCK );
29494
29495   /* Locks are within range */
29496   assert( n>=1 && n<SQLITE_SHM_NLOCK );
29497
29498   if( pShmNode->h>=0 ){
29499     int lkType;
29500     /* Initialize the locking parameters */
29501     memset(&f, 0, sizeof(f));
29502     f.l_type = lockType;
29503     f.l_whence = SEEK_SET;
29504     f.l_start = ofst;
29505     f.l_len = n;
29506
29507     lkType = (pFile->ctrlFlags & UNIXFILE_BLOCK)!=0 ? F_SETLKW : F_SETLK;
29508     rc = osFcntl(pShmNode->h, lkType, &f);
29509     rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
29510     pFile->ctrlFlags &= ~UNIXFILE_BLOCK;
29511   }
29512
29513   /* Update the global lock state and do debug tracing */
29514 #ifdef SQLITE_DEBUG
29515   { u16 mask;
29516   OSTRACE(("SHM-LOCK "));
29517   mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
29518   if( rc==SQLITE_OK ){
29519     if( lockType==F_UNLCK ){
29520       OSTRACE(("unlock %d ok", ofst));
29521       pShmNode->exclMask &= ~mask;
29522       pShmNode->sharedMask &= ~mask;
29523     }else if( lockType==F_RDLCK ){
29524       OSTRACE(("read-lock %d ok", ofst));
29525       pShmNode->exclMask &= ~mask;
29526       pShmNode->sharedMask |= mask;
29527     }else{
29528       assert( lockType==F_WRLCK );
29529       OSTRACE(("write-lock %d ok", ofst));
29530       pShmNode->exclMask |= mask;
29531       pShmNode->sharedMask &= ~mask;
29532     }
29533   }else{
29534     if( lockType==F_UNLCK ){
29535       OSTRACE(("unlock %d failed", ofst));
29536     }else if( lockType==F_RDLCK ){
29537       OSTRACE(("read-lock failed"));
29538     }else{
29539       assert( lockType==F_WRLCK );
29540       OSTRACE(("write-lock %d failed", ofst));
29541     }
29542   }
29543   OSTRACE((" - afterwards %03x,%03x\n",
29544            pShmNode->sharedMask, pShmNode->exclMask));
29545   }
29546 #endif
29547
29548   return rc;        
29549 }
29550
29551 /*
29552 ** Return the minimum number of 32KB shm regions that should be mapped at
29553 ** a time, assuming that each mapping must be an integer multiple of the
29554 ** current system page-size.
29555 **
29556 ** Usually, this is 1. The exception seems to be systems that are configured
29557 ** to use 64KB pages - in this case each mapping must cover at least two
29558 ** shm regions.
29559 */
29560 static int unixShmRegionPerMap(void){
29561   int shmsz = 32*1024;            /* SHM region size */
29562   int pgsz = osGetpagesize();   /* System page size */
29563   assert( ((pgsz-1)&pgsz)==0 );   /* Page size must be a power of 2 */
29564   if( pgsz<shmsz ) return 1;
29565   return pgsz/shmsz;
29566 }
29567
29568 /*
29569 ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
29570 **
29571 ** This is not a VFS shared-memory method; it is a utility function called
29572 ** by VFS shared-memory methods.
29573 */
29574 static void unixShmPurge(unixFile *pFd){
29575   unixShmNode *p = pFd->pInode->pShmNode;
29576   assert( unixMutexHeld() );
29577   if( p && p->nRef==0 ){
29578     int nShmPerMap = unixShmRegionPerMap();
29579     int i;
29580     assert( p->pInode==pFd->pInode );
29581     sqlite3_mutex_free(p->mutex);
29582     for(i=0; i<p->nRegion; i+=nShmPerMap){
29583       if( p->h>=0 ){
29584         osMunmap(p->apRegion[i], p->szRegion);
29585       }else{
29586         sqlite3_free(p->apRegion[i]);
29587       }
29588     }
29589     sqlite3_free(p->apRegion);
29590     if( p->h>=0 ){
29591       robust_close(pFd, p->h, __LINE__);
29592       p->h = -1;
29593     }
29594     p->pInode->pShmNode = 0;
29595     sqlite3_free(p);
29596   }
29597 }
29598
29599 /*
29600 ** Open a shared-memory area associated with open database file pDbFd.  
29601 ** This particular implementation uses mmapped files.
29602 **
29603 ** The file used to implement shared-memory is in the same directory
29604 ** as the open database file and has the same name as the open database
29605 ** file with the "-shm" suffix added.  For example, if the database file
29606 ** is "/home/user1/config.db" then the file that is created and mmapped
29607 ** for shared memory will be called "/home/user1/config.db-shm".  
29608 **
29609 ** Another approach to is to use files in /dev/shm or /dev/tmp or an
29610 ** some other tmpfs mount. But if a file in a different directory
29611 ** from the database file is used, then differing access permissions
29612 ** or a chroot() might cause two different processes on the same
29613 ** database to end up using different files for shared memory - 
29614 ** meaning that their memory would not really be shared - resulting
29615 ** in database corruption.  Nevertheless, this tmpfs file usage
29616 ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
29617 ** or the equivalent.  The use of the SQLITE_SHM_DIRECTORY compile-time
29618 ** option results in an incompatible build of SQLite;  builds of SQLite
29619 ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
29620 ** same database file at the same time, database corruption will likely
29621 ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
29622 ** "unsupported" and may go away in a future SQLite release.
29623 **
29624 ** When opening a new shared-memory file, if no other instances of that
29625 ** file are currently open, in this process or in other processes, then
29626 ** the file must be truncated to zero length or have its header cleared.
29627 **
29628 ** If the original database file (pDbFd) is using the "unix-excl" VFS
29629 ** that means that an exclusive lock is held on the database file and
29630 ** that no other processes are able to read or write the database.  In
29631 ** that case, we do not really need shared memory.  No shared memory
29632 ** file is created.  The shared memory will be simulated with heap memory.
29633 */
29634 static int unixOpenSharedMemory(unixFile *pDbFd){
29635   struct unixShm *p = 0;          /* The connection to be opened */
29636   struct unixShmNode *pShmNode;   /* The underlying mmapped file */
29637   int rc;                         /* Result code */
29638   unixInodeInfo *pInode;          /* The inode of fd */
29639   char *zShmFilename;             /* Name of the file used for SHM */
29640   int nShmFilename;               /* Size of the SHM filename in bytes */
29641
29642   /* Allocate space for the new unixShm object. */
29643   p = sqlite3_malloc( sizeof(*p) );
29644   if( p==0 ) return SQLITE_NOMEM;
29645   memset(p, 0, sizeof(*p));
29646   assert( pDbFd->pShm==0 );
29647
29648   /* Check to see if a unixShmNode object already exists. Reuse an existing
29649   ** one if present. Create a new one if necessary.
29650   */
29651   unixEnterMutex();
29652   pInode = pDbFd->pInode;
29653   pShmNode = pInode->pShmNode;
29654   if( pShmNode==0 ){
29655     struct stat sStat;                 /* fstat() info for database file */
29656 #ifndef SQLITE_SHM_DIRECTORY
29657     const char *zBasePath = pDbFd->zPath;
29658 #endif
29659
29660     /* Call fstat() to figure out the permissions on the database file. If
29661     ** a new *-shm file is created, an attempt will be made to create it
29662     ** with the same permissions.
29663     */
29664     if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
29665       rc = SQLITE_IOERR_FSTAT;
29666       goto shm_open_err;
29667     }
29668
29669 #ifdef SQLITE_SHM_DIRECTORY
29670     nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
29671 #else
29672     nShmFilename = 6 + (int)strlen(zBasePath);
29673 #endif
29674     pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
29675     if( pShmNode==0 ){
29676       rc = SQLITE_NOMEM;
29677       goto shm_open_err;
29678     }
29679     memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
29680     zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
29681 #ifdef SQLITE_SHM_DIRECTORY
29682     sqlite3_snprintf(nShmFilename, zShmFilename, 
29683                      SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
29684                      (u32)sStat.st_ino, (u32)sStat.st_dev);
29685 #else
29686     sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", zBasePath);
29687     sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
29688 #endif
29689     pShmNode->h = -1;
29690     pDbFd->pInode->pShmNode = pShmNode;
29691     pShmNode->pInode = pDbFd->pInode;
29692     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
29693     if( pShmNode->mutex==0 ){
29694       rc = SQLITE_NOMEM;
29695       goto shm_open_err;
29696     }
29697
29698     if( pInode->bProcessLock==0 ){
29699       int openFlags = O_RDWR | O_CREAT;
29700       if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
29701         openFlags = O_RDONLY;
29702         pShmNode->isReadonly = 1;
29703       }
29704       pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
29705       if( pShmNode->h<0 ){
29706         rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
29707         goto shm_open_err;
29708       }
29709
29710       /* If this process is running as root, make sure that the SHM file
29711       ** is owned by the same user that owns the original database.  Otherwise,
29712       ** the original owner will not be able to connect.
29713       */
29714       osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
29715   
29716       /* Check to see if another process is holding the dead-man switch.
29717       ** If not, truncate the file to zero length. 
29718       */
29719       rc = SQLITE_OK;
29720       if( unixShmSystemLock(pDbFd, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
29721         if( robust_ftruncate(pShmNode->h, 0) ){
29722           rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
29723         }
29724       }
29725       if( rc==SQLITE_OK ){
29726         rc = unixShmSystemLock(pDbFd, F_RDLCK, UNIX_SHM_DMS, 1);
29727       }
29728       if( rc ) goto shm_open_err;
29729     }
29730   }
29731
29732   /* Make the new connection a child of the unixShmNode */
29733   p->pShmNode = pShmNode;
29734 #ifdef SQLITE_DEBUG
29735   p->id = pShmNode->nextShmId++;
29736 #endif
29737   pShmNode->nRef++;
29738   pDbFd->pShm = p;
29739   unixLeaveMutex();
29740
29741   /* The reference count on pShmNode has already been incremented under
29742   ** the cover of the unixEnterMutex() mutex and the pointer from the
29743   ** new (struct unixShm) object to the pShmNode has been set. All that is
29744   ** left to do is to link the new object into the linked list starting
29745   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex 
29746   ** mutex.
29747   */
29748   sqlite3_mutex_enter(pShmNode->mutex);
29749   p->pNext = pShmNode->pFirst;
29750   pShmNode->pFirst = p;
29751   sqlite3_mutex_leave(pShmNode->mutex);
29752   return SQLITE_OK;
29753
29754   /* Jump here on any error */
29755 shm_open_err:
29756   unixShmPurge(pDbFd);       /* This call frees pShmNode if required */
29757   sqlite3_free(p);
29758   unixLeaveMutex();
29759   return rc;
29760 }
29761
29762 /*
29763 ** This function is called to obtain a pointer to region iRegion of the 
29764 ** shared-memory associated with the database file fd. Shared-memory regions 
29765 ** are numbered starting from zero. Each shared-memory region is szRegion 
29766 ** bytes in size.
29767 **
29768 ** If an error occurs, an error code is returned and *pp is set to NULL.
29769 **
29770 ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
29771 ** region has not been allocated (by any client, including one running in a
29772 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If 
29773 ** bExtend is non-zero and the requested shared-memory region has not yet 
29774 ** been allocated, it is allocated by this function.
29775 **
29776 ** If the shared-memory region has already been allocated or is allocated by
29777 ** this call as described above, then it is mapped into this processes 
29778 ** address space (if it is not already), *pp is set to point to the mapped 
29779 ** memory and SQLITE_OK returned.
29780 */
29781 static int unixShmMap(
29782   sqlite3_file *fd,               /* Handle open on database file */
29783   int iRegion,                    /* Region to retrieve */
29784   int szRegion,                   /* Size of regions */
29785   int bExtend,                    /* True to extend file if necessary */
29786   void volatile **pp              /* OUT: Mapped memory */
29787 ){
29788   unixFile *pDbFd = (unixFile*)fd;
29789   unixShm *p;
29790   unixShmNode *pShmNode;
29791   int rc = SQLITE_OK;
29792   int nShmPerMap = unixShmRegionPerMap();
29793   int nReqRegion;
29794
29795   /* If the shared-memory file has not yet been opened, open it now. */
29796   if( pDbFd->pShm==0 ){
29797     rc = unixOpenSharedMemory(pDbFd);
29798     if( rc!=SQLITE_OK ) return rc;
29799   }
29800
29801   p = pDbFd->pShm;
29802   pShmNode = p->pShmNode;
29803   sqlite3_mutex_enter(pShmNode->mutex);
29804   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
29805   assert( pShmNode->pInode==pDbFd->pInode );
29806   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
29807   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
29808
29809   /* Minimum number of regions required to be mapped. */
29810   nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
29811
29812   if( pShmNode->nRegion<nReqRegion ){
29813     char **apNew;                      /* New apRegion[] array */
29814     int nByte = nReqRegion*szRegion;   /* Minimum required file size */
29815     struct stat sStat;                 /* Used by fstat() */
29816
29817     pShmNode->szRegion = szRegion;
29818
29819     if( pShmNode->h>=0 ){
29820       /* The requested region is not mapped into this processes address space.
29821       ** Check to see if it has been allocated (i.e. if the wal-index file is
29822       ** large enough to contain the requested region).
29823       */
29824       if( osFstat(pShmNode->h, &sStat) ){
29825         rc = SQLITE_IOERR_SHMSIZE;
29826         goto shmpage_out;
29827       }
29828   
29829       if( sStat.st_size<nByte ){
29830         /* The requested memory region does not exist. If bExtend is set to
29831         ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
29832         */
29833         if( !bExtend ){
29834           goto shmpage_out;
29835         }
29836
29837         /* Alternatively, if bExtend is true, extend the file. Do this by
29838         ** writing a single byte to the end of each (OS) page being
29839         ** allocated or extended. Technically, we need only write to the
29840         ** last page in order to extend the file. But writing to all new
29841         ** pages forces the OS to allocate them immediately, which reduces
29842         ** the chances of SIGBUS while accessing the mapped region later on.
29843         */
29844         else{
29845           static const int pgsz = 4096;
29846           int iPg;
29847
29848           /* Write to the last byte of each newly allocated or extended page */
29849           assert( (nByte % pgsz)==0 );
29850           for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
29851             if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
29852               const char *zFile = pShmNode->zFilename;
29853               rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
29854               goto shmpage_out;
29855             }
29856           }
29857         }
29858       }
29859     }
29860
29861     /* Map the requested memory region into this processes address space. */
29862     apNew = (char **)sqlite3_realloc(
29863         pShmNode->apRegion, nReqRegion*sizeof(char *)
29864     );
29865     if( !apNew ){
29866       rc = SQLITE_IOERR_NOMEM;
29867       goto shmpage_out;
29868     }
29869     pShmNode->apRegion = apNew;
29870     while( pShmNode->nRegion<nReqRegion ){
29871       int nMap = szRegion*nShmPerMap;
29872       int i;
29873       void *pMem;
29874       if( pShmNode->h>=0 ){
29875         pMem = osMmap(0, nMap,
29876             pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE, 
29877             MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
29878         );
29879         if( pMem==MAP_FAILED ){
29880           rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
29881           goto shmpage_out;
29882         }
29883       }else{
29884         pMem = sqlite3_malloc(szRegion);
29885         if( pMem==0 ){
29886           rc = SQLITE_NOMEM;
29887           goto shmpage_out;
29888         }
29889         memset(pMem, 0, szRegion);
29890       }
29891
29892       for(i=0; i<nShmPerMap; i++){
29893         pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
29894       }
29895       pShmNode->nRegion += nShmPerMap;
29896     }
29897   }
29898
29899 shmpage_out:
29900   if( pShmNode->nRegion>iRegion ){
29901     *pp = pShmNode->apRegion[iRegion];
29902   }else{
29903     *pp = 0;
29904   }
29905   if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
29906   sqlite3_mutex_leave(pShmNode->mutex);
29907   return rc;
29908 }
29909
29910 /*
29911 ** Change the lock state for a shared-memory segment.
29912 **
29913 ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
29914 ** different here than in posix.  In xShmLock(), one can go from unlocked
29915 ** to shared and back or from unlocked to exclusive and back.  But one may
29916 ** not go from shared to exclusive or from exclusive to shared.
29917 */
29918 static int unixShmLock(
29919   sqlite3_file *fd,          /* Database file holding the shared memory */
29920   int ofst,                  /* First lock to acquire or release */
29921   int n,                     /* Number of locks to acquire or release */
29922   int flags                  /* What to do with the lock */
29923 ){
29924   unixFile *pDbFd = (unixFile*)fd;      /* Connection holding shared memory */
29925   unixShm *p = pDbFd->pShm;             /* The shared memory being locked */
29926   unixShm *pX;                          /* For looping over all siblings */
29927   unixShmNode *pShmNode = p->pShmNode;  /* The underlying file iNode */
29928   int rc = SQLITE_OK;                   /* Result code */
29929   u16 mask;                             /* Mask of locks to take or release */
29930
29931   assert( pShmNode==pDbFd->pInode->pShmNode );
29932   assert( pShmNode->pInode==pDbFd->pInode );
29933   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
29934   assert( n>=1 );
29935   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
29936        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
29937        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
29938        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
29939   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
29940   assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
29941   assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
29942
29943   mask = (1<<(ofst+n)) - (1<<ofst);
29944   assert( n>1 || mask==(1<<ofst) );
29945   sqlite3_mutex_enter(pShmNode->mutex);
29946   if( flags & SQLITE_SHM_UNLOCK ){
29947     u16 allMask = 0; /* Mask of locks held by siblings */
29948
29949     /* See if any siblings hold this same lock */
29950     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
29951       if( pX==p ) continue;
29952       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
29953       allMask |= pX->sharedMask;
29954     }
29955
29956     /* Unlock the system-level locks */
29957     if( (mask & allMask)==0 ){
29958       rc = unixShmSystemLock(pDbFd, F_UNLCK, ofst+UNIX_SHM_BASE, n);
29959     }else{
29960       rc = SQLITE_OK;
29961     }
29962
29963     /* Undo the local locks */
29964     if( rc==SQLITE_OK ){
29965       p->exclMask &= ~mask;
29966       p->sharedMask &= ~mask;
29967     } 
29968   }else if( flags & SQLITE_SHM_SHARED ){
29969     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
29970
29971     /* Find out which shared locks are already held by sibling connections.
29972     ** If any sibling already holds an exclusive lock, go ahead and return
29973     ** SQLITE_BUSY.
29974     */
29975     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
29976       if( (pX->exclMask & mask)!=0 ){
29977         rc = SQLITE_BUSY;
29978         break;
29979       }
29980       allShared |= pX->sharedMask;
29981     }
29982
29983     /* Get shared locks at the system level, if necessary */
29984     if( rc==SQLITE_OK ){
29985       if( (allShared & mask)==0 ){
29986         rc = unixShmSystemLock(pDbFd, F_RDLCK, ofst+UNIX_SHM_BASE, n);
29987       }else{
29988         rc = SQLITE_OK;
29989       }
29990     }
29991
29992     /* Get the local shared locks */
29993     if( rc==SQLITE_OK ){
29994       p->sharedMask |= mask;
29995     }
29996   }else{
29997     /* Make sure no sibling connections hold locks that will block this
29998     ** lock.  If any do, return SQLITE_BUSY right away.
29999     */
30000     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
30001       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
30002         rc = SQLITE_BUSY;
30003         break;
30004       }
30005     }
30006   
30007     /* Get the exclusive locks at the system level.  Then if successful
30008     ** also mark the local connection as being locked.
30009     */
30010     if( rc==SQLITE_OK ){
30011       rc = unixShmSystemLock(pDbFd, F_WRLCK, ofst+UNIX_SHM_BASE, n);
30012       if( rc==SQLITE_OK ){
30013         assert( (p->sharedMask & mask)==0 );
30014         p->exclMask |= mask;
30015       }
30016     }
30017   }
30018   sqlite3_mutex_leave(pShmNode->mutex);
30019   OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
30020            p->id, osGetpid(0), p->sharedMask, p->exclMask));
30021   return rc;
30022 }
30023
30024 /*
30025 ** Implement a memory barrier or memory fence on shared memory.  
30026 **
30027 ** All loads and stores begun before the barrier must complete before
30028 ** any load or store begun after the barrier.
30029 */
30030 static void unixShmBarrier(
30031   sqlite3_file *fd                /* Database file holding the shared memory */
30032 ){
30033   UNUSED_PARAMETER(fd);
30034   unixEnterMutex();
30035   unixLeaveMutex();
30036 }
30037
30038 /*
30039 ** Close a connection to shared-memory.  Delete the underlying 
30040 ** storage if deleteFlag is true.
30041 **
30042 ** If there is no shared memory associated with the connection then this
30043 ** routine is a harmless no-op.
30044 */
30045 static int unixShmUnmap(
30046   sqlite3_file *fd,               /* The underlying database file */
30047   int deleteFlag                  /* Delete shared-memory if true */
30048 ){
30049   unixShm *p;                     /* The connection to be closed */
30050   unixShmNode *pShmNode;          /* The underlying shared-memory file */
30051   unixShm **pp;                   /* For looping over sibling connections */
30052   unixFile *pDbFd;                /* The underlying database file */
30053
30054   pDbFd = (unixFile*)fd;
30055   p = pDbFd->pShm;
30056   if( p==0 ) return SQLITE_OK;
30057   pShmNode = p->pShmNode;
30058
30059   assert( pShmNode==pDbFd->pInode->pShmNode );
30060   assert( pShmNode->pInode==pDbFd->pInode );
30061
30062   /* Remove connection p from the set of connections associated
30063   ** with pShmNode */
30064   sqlite3_mutex_enter(pShmNode->mutex);
30065   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
30066   *pp = p->pNext;
30067
30068   /* Free the connection p */
30069   sqlite3_free(p);
30070   pDbFd->pShm = 0;
30071   sqlite3_mutex_leave(pShmNode->mutex);
30072
30073   /* If pShmNode->nRef has reached 0, then close the underlying
30074   ** shared-memory file, too */
30075   unixEnterMutex();
30076   assert( pShmNode->nRef>0 );
30077   pShmNode->nRef--;
30078   if( pShmNode->nRef==0 ){
30079     if( deleteFlag && pShmNode->h>=0 ){
30080       osUnlink(pShmNode->zFilename);
30081     }
30082     unixShmPurge(pDbFd);
30083   }
30084   unixLeaveMutex();
30085
30086   return SQLITE_OK;
30087 }
30088
30089
30090 #else
30091 # define unixShmMap     0
30092 # define unixShmLock    0
30093 # define unixShmBarrier 0
30094 # define unixShmUnmap   0
30095 #endif /* #ifndef SQLITE_OMIT_WAL */
30096
30097 #if SQLITE_MAX_MMAP_SIZE>0
30098 /*
30099 ** If it is currently memory mapped, unmap file pFd.
30100 */
30101 static void unixUnmapfile(unixFile *pFd){
30102   assert( pFd->nFetchOut==0 );
30103   if( pFd->pMapRegion ){
30104     osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
30105     pFd->pMapRegion = 0;
30106     pFd->mmapSize = 0;
30107     pFd->mmapSizeActual = 0;
30108   }
30109 }
30110
30111 /*
30112 ** Attempt to set the size of the memory mapping maintained by file 
30113 ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
30114 **
30115 ** If successful, this function sets the following variables:
30116 **
30117 **       unixFile.pMapRegion
30118 **       unixFile.mmapSize
30119 **       unixFile.mmapSizeActual
30120 **
30121 ** If unsuccessful, an error message is logged via sqlite3_log() and
30122 ** the three variables above are zeroed. In this case SQLite should
30123 ** continue accessing the database using the xRead() and xWrite()
30124 ** methods.
30125 */
30126 static void unixRemapfile(
30127   unixFile *pFd,                  /* File descriptor object */
30128   i64 nNew                        /* Required mapping size */
30129 ){
30130   const char *zErr = "mmap";
30131   int h = pFd->h;                      /* File descriptor open on db file */
30132   u8 *pOrig = (u8 *)pFd->pMapRegion;   /* Pointer to current file mapping */
30133   i64 nOrig = pFd->mmapSizeActual;     /* Size of pOrig region in bytes */
30134   u8 *pNew = 0;                        /* Location of new mapping */
30135   int flags = PROT_READ;               /* Flags to pass to mmap() */
30136
30137   assert( pFd->nFetchOut==0 );
30138   assert( nNew>pFd->mmapSize );
30139   assert( nNew<=pFd->mmapSizeMax );
30140   assert( nNew>0 );
30141   assert( pFd->mmapSizeActual>=pFd->mmapSize );
30142   assert( MAP_FAILED!=0 );
30143
30144   if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
30145
30146   if( pOrig ){
30147 #if HAVE_MREMAP
30148     i64 nReuse = pFd->mmapSize;
30149 #else
30150     const int szSyspage = osGetpagesize();
30151     i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
30152 #endif
30153     u8 *pReq = &pOrig[nReuse];
30154
30155     /* Unmap any pages of the existing mapping that cannot be reused. */
30156     if( nReuse!=nOrig ){
30157       osMunmap(pReq, nOrig-nReuse);
30158     }
30159
30160 #if HAVE_MREMAP
30161     pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
30162     zErr = "mremap";
30163 #else
30164     pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
30165     if( pNew!=MAP_FAILED ){
30166       if( pNew!=pReq ){
30167         osMunmap(pNew, nNew - nReuse);
30168         pNew = 0;
30169       }else{
30170         pNew = pOrig;
30171       }
30172     }
30173 #endif
30174
30175     /* The attempt to extend the existing mapping failed. Free it. */
30176     if( pNew==MAP_FAILED || pNew==0 ){
30177       osMunmap(pOrig, nReuse);
30178     }
30179   }
30180
30181   /* If pNew is still NULL, try to create an entirely new mapping. */
30182   if( pNew==0 ){
30183     pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
30184   }
30185
30186   if( pNew==MAP_FAILED ){
30187     pNew = 0;
30188     nNew = 0;
30189     unixLogError(SQLITE_OK, zErr, pFd->zPath);
30190
30191     /* If the mmap() above failed, assume that all subsequent mmap() calls
30192     ** will probably fail too. Fall back to using xRead/xWrite exclusively
30193     ** in this case.  */
30194     pFd->mmapSizeMax = 0;
30195   }
30196   pFd->pMapRegion = (void *)pNew;
30197   pFd->mmapSize = pFd->mmapSizeActual = nNew;
30198 }
30199
30200 /*
30201 ** Memory map or remap the file opened by file-descriptor pFd (if the file
30202 ** is already mapped, the existing mapping is replaced by the new). Or, if 
30203 ** there already exists a mapping for this file, and there are still 
30204 ** outstanding xFetch() references to it, this function is a no-op.
30205 **
30206 ** If parameter nByte is non-negative, then it is the requested size of 
30207 ** the mapping to create. Otherwise, if nByte is less than zero, then the 
30208 ** requested size is the size of the file on disk. The actual size of the
30209 ** created mapping is either the requested size or the value configured 
30210 ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
30211 **
30212 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
30213 ** recreated as a result of outstanding references) or an SQLite error
30214 ** code otherwise.
30215 */
30216 static int unixMapfile(unixFile *pFd, i64 nByte){
30217   i64 nMap = nByte;
30218   int rc;
30219
30220   assert( nMap>=0 || pFd->nFetchOut==0 );
30221   if( pFd->nFetchOut>0 ) return SQLITE_OK;
30222
30223   if( nMap<0 ){
30224     struct stat statbuf;          /* Low-level file information */
30225     rc = osFstat(pFd->h, &statbuf);
30226     if( rc!=SQLITE_OK ){
30227       return SQLITE_IOERR_FSTAT;
30228     }
30229     nMap = statbuf.st_size;
30230   }
30231   if( nMap>pFd->mmapSizeMax ){
30232     nMap = pFd->mmapSizeMax;
30233   }
30234
30235   if( nMap!=pFd->mmapSize ){
30236     if( nMap>0 ){
30237       unixRemapfile(pFd, nMap);
30238     }else{
30239       unixUnmapfile(pFd);
30240     }
30241   }
30242
30243   return SQLITE_OK;
30244 }
30245 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
30246
30247 /*
30248 ** If possible, return a pointer to a mapping of file fd starting at offset
30249 ** iOff. The mapping must be valid for at least nAmt bytes.
30250 **
30251 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
30252 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
30253 ** Finally, if an error does occur, return an SQLite error code. The final
30254 ** value of *pp is undefined in this case.
30255 **
30256 ** If this function does return a pointer, the caller must eventually 
30257 ** release the reference by calling unixUnfetch().
30258 */
30259 static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
30260 #if SQLITE_MAX_MMAP_SIZE>0
30261   unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
30262 #endif
30263   *pp = 0;
30264
30265 #if SQLITE_MAX_MMAP_SIZE>0
30266   if( pFd->mmapSizeMax>0 ){
30267     if( pFd->pMapRegion==0 ){
30268       int rc = unixMapfile(pFd, -1);
30269       if( rc!=SQLITE_OK ) return rc;
30270     }
30271     if( pFd->mmapSize >= iOff+nAmt ){
30272       *pp = &((u8 *)pFd->pMapRegion)[iOff];
30273       pFd->nFetchOut++;
30274     }
30275   }
30276 #endif
30277   return SQLITE_OK;
30278 }
30279
30280 /*
30281 ** If the third argument is non-NULL, then this function releases a 
30282 ** reference obtained by an earlier call to unixFetch(). The second
30283 ** argument passed to this function must be the same as the corresponding
30284 ** argument that was passed to the unixFetch() invocation. 
30285 **
30286 ** Or, if the third argument is NULL, then this function is being called 
30287 ** to inform the VFS layer that, according to POSIX, any existing mapping 
30288 ** may now be invalid and should be unmapped.
30289 */
30290 static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
30291 #if SQLITE_MAX_MMAP_SIZE>0
30292   unixFile *pFd = (unixFile *)fd;   /* The underlying database file */
30293   UNUSED_PARAMETER(iOff);
30294
30295   /* If p==0 (unmap the entire file) then there must be no outstanding 
30296   ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
30297   ** then there must be at least one outstanding.  */
30298   assert( (p==0)==(pFd->nFetchOut==0) );
30299
30300   /* If p!=0, it must match the iOff value. */
30301   assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
30302
30303   if( p ){
30304     pFd->nFetchOut--;
30305   }else{
30306     unixUnmapfile(pFd);
30307   }
30308
30309   assert( pFd->nFetchOut>=0 );
30310 #else
30311   UNUSED_PARAMETER(fd);
30312   UNUSED_PARAMETER(p);
30313   UNUSED_PARAMETER(iOff);
30314 #endif
30315   return SQLITE_OK;
30316 }
30317
30318 /*
30319 ** Here ends the implementation of all sqlite3_file methods.
30320 **
30321 ********************** End sqlite3_file Methods *******************************
30322 ******************************************************************************/
30323
30324 /*
30325 ** This division contains definitions of sqlite3_io_methods objects that
30326 ** implement various file locking strategies.  It also contains definitions
30327 ** of "finder" functions.  A finder-function is used to locate the appropriate
30328 ** sqlite3_io_methods object for a particular database file.  The pAppData
30329 ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
30330 ** the correct finder-function for that VFS.
30331 **
30332 ** Most finder functions return a pointer to a fixed sqlite3_io_methods
30333 ** object.  The only interesting finder-function is autolockIoFinder, which
30334 ** looks at the filesystem type and tries to guess the best locking
30335 ** strategy from that.
30336 **
30337 ** For finder-function F, two objects are created:
30338 **
30339 **    (1) The real finder-function named "FImpt()".
30340 **
30341 **    (2) A constant pointer to this function named just "F".
30342 **
30343 **
30344 ** A pointer to the F pointer is used as the pAppData value for VFS
30345 ** objects.  We have to do this instead of letting pAppData point
30346 ** directly at the finder-function since C90 rules prevent a void*
30347 ** from be cast into a function pointer.
30348 **
30349 **
30350 ** Each instance of this macro generates two objects:
30351 **
30352 **   *  A constant sqlite3_io_methods object call METHOD that has locking
30353 **      methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
30354 **
30355 **   *  An I/O method finder function called FINDER that returns a pointer
30356 **      to the METHOD object in the previous bullet.
30357 */
30358 #define IOMETHODS(FINDER,METHOD,VERSION,CLOSE,LOCK,UNLOCK,CKLOCK,SHMMAP)     \
30359 static const sqlite3_io_methods METHOD = {                                   \
30360    VERSION,                    /* iVersion */                                \
30361    CLOSE,                      /* xClose */                                  \
30362    unixRead,                   /* xRead */                                   \
30363    unixWrite,                  /* xWrite */                                  \
30364    unixTruncate,               /* xTruncate */                               \
30365    unixSync,                   /* xSync */                                   \
30366    unixFileSize,               /* xFileSize */                               \
30367    LOCK,                       /* xLock */                                   \
30368    UNLOCK,                     /* xUnlock */                                 \
30369    CKLOCK,                     /* xCheckReservedLock */                      \
30370    unixFileControl,            /* xFileControl */                            \
30371    unixSectorSize,             /* xSectorSize */                             \
30372    unixDeviceCharacteristics,  /* xDeviceCapabilities */                     \
30373    SHMMAP,                     /* xShmMap */                                 \
30374    unixShmLock,                /* xShmLock */                                \
30375    unixShmBarrier,             /* xShmBarrier */                             \
30376    unixShmUnmap,               /* xShmUnmap */                               \
30377    unixFetch,                  /* xFetch */                                  \
30378    unixUnfetch,                /* xUnfetch */                                \
30379 };                                                                           \
30380 static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){   \
30381   UNUSED_PARAMETER(z); UNUSED_PARAMETER(p);                                  \
30382   return &METHOD;                                                            \
30383 }                                                                            \
30384 static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p)    \
30385     = FINDER##Impl;
30386
30387 /*
30388 ** Here are all of the sqlite3_io_methods objects for each of the
30389 ** locking strategies.  Functions that return pointers to these methods
30390 ** are also created.
30391 */
30392 IOMETHODS(
30393   posixIoFinder,            /* Finder function name */
30394   posixIoMethods,           /* sqlite3_io_methods object name */
30395   3,                        /* shared memory and mmap are enabled */
30396   unixClose,                /* xClose method */
30397   unixLock,                 /* xLock method */
30398   unixUnlock,               /* xUnlock method */
30399   unixCheckReservedLock,    /* xCheckReservedLock method */
30400   unixShmMap                /* xShmMap method */
30401 )
30402 IOMETHODS(
30403   nolockIoFinder,           /* Finder function name */
30404   nolockIoMethods,          /* sqlite3_io_methods object name */
30405   3,                        /* shared memory is disabled */
30406   nolockClose,              /* xClose method */
30407   nolockLock,               /* xLock method */
30408   nolockUnlock,             /* xUnlock method */
30409   nolockCheckReservedLock,  /* xCheckReservedLock method */
30410   0                         /* xShmMap method */
30411 )
30412 IOMETHODS(
30413   dotlockIoFinder,          /* Finder function name */
30414   dotlockIoMethods,         /* sqlite3_io_methods object name */
30415   1,                        /* shared memory is disabled */
30416   dotlockClose,             /* xClose method */
30417   dotlockLock,              /* xLock method */
30418   dotlockUnlock,            /* xUnlock method */
30419   dotlockCheckReservedLock, /* xCheckReservedLock method */
30420   0                         /* xShmMap method */
30421 )
30422
30423 #if SQLITE_ENABLE_LOCKING_STYLE
30424 IOMETHODS(
30425   flockIoFinder,            /* Finder function name */
30426   flockIoMethods,           /* sqlite3_io_methods object name */
30427   1,                        /* shared memory is disabled */
30428   flockClose,               /* xClose method */
30429   flockLock,                /* xLock method */
30430   flockUnlock,              /* xUnlock method */
30431   flockCheckReservedLock,   /* xCheckReservedLock method */
30432   0                         /* xShmMap method */
30433 )
30434 #endif
30435
30436 #if OS_VXWORKS
30437 IOMETHODS(
30438   semIoFinder,              /* Finder function name */
30439   semIoMethods,             /* sqlite3_io_methods object name */
30440   1,                        /* shared memory is disabled */
30441   semXClose,                /* xClose method */
30442   semXLock,                 /* xLock method */
30443   semXUnlock,               /* xUnlock method */
30444   semXCheckReservedLock,    /* xCheckReservedLock method */
30445   0                         /* xShmMap method */
30446 )
30447 #endif
30448
30449 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30450 IOMETHODS(
30451   afpIoFinder,              /* Finder function name */
30452   afpIoMethods,             /* sqlite3_io_methods object name */
30453   1,                        /* shared memory is disabled */
30454   afpClose,                 /* xClose method */
30455   afpLock,                  /* xLock method */
30456   afpUnlock,                /* xUnlock method */
30457   afpCheckReservedLock,     /* xCheckReservedLock method */
30458   0                         /* xShmMap method */
30459 )
30460 #endif
30461
30462 /*
30463 ** The proxy locking method is a "super-method" in the sense that it
30464 ** opens secondary file descriptors for the conch and lock files and
30465 ** it uses proxy, dot-file, AFP, and flock() locking methods on those
30466 ** secondary files.  For this reason, the division that implements
30467 ** proxy locking is located much further down in the file.  But we need
30468 ** to go ahead and define the sqlite3_io_methods and finder function
30469 ** for proxy locking here.  So we forward declare the I/O methods.
30470 */
30471 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30472 static int proxyClose(sqlite3_file*);
30473 static int proxyLock(sqlite3_file*, int);
30474 static int proxyUnlock(sqlite3_file*, int);
30475 static int proxyCheckReservedLock(sqlite3_file*, int*);
30476 IOMETHODS(
30477   proxyIoFinder,            /* Finder function name */
30478   proxyIoMethods,           /* sqlite3_io_methods object name */
30479   1,                        /* shared memory is disabled */
30480   proxyClose,               /* xClose method */
30481   proxyLock,                /* xLock method */
30482   proxyUnlock,              /* xUnlock method */
30483   proxyCheckReservedLock,   /* xCheckReservedLock method */
30484   0                         /* xShmMap method */
30485 )
30486 #endif
30487
30488 /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
30489 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30490 IOMETHODS(
30491   nfsIoFinder,               /* Finder function name */
30492   nfsIoMethods,              /* sqlite3_io_methods object name */
30493   1,                         /* shared memory is disabled */
30494   unixClose,                 /* xClose method */
30495   unixLock,                  /* xLock method */
30496   nfsUnlock,                 /* xUnlock method */
30497   unixCheckReservedLock,     /* xCheckReservedLock method */
30498   0                          /* xShmMap method */
30499 )
30500 #endif
30501
30502 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30503 /* 
30504 ** This "finder" function attempts to determine the best locking strategy 
30505 ** for the database file "filePath".  It then returns the sqlite3_io_methods
30506 ** object that implements that strategy.
30507 **
30508 ** This is for MacOSX only.
30509 */
30510 static const sqlite3_io_methods *autolockIoFinderImpl(
30511   const char *filePath,    /* name of the database file */
30512   unixFile *pNew           /* open file object for the database file */
30513 ){
30514   static const struct Mapping {
30515     const char *zFilesystem;              /* Filesystem type name */
30516     const sqlite3_io_methods *pMethods;   /* Appropriate locking method */
30517   } aMap[] = {
30518     { "hfs",    &posixIoMethods },
30519     { "ufs",    &posixIoMethods },
30520     { "afpfs",  &afpIoMethods },
30521     { "smbfs",  &afpIoMethods },
30522     { "webdav", &nolockIoMethods },
30523     { 0, 0 }
30524   };
30525   int i;
30526   struct statfs fsInfo;
30527   struct flock lockInfo;
30528
30529   if( !filePath ){
30530     /* If filePath==NULL that means we are dealing with a transient file
30531     ** that does not need to be locked. */
30532     return &nolockIoMethods;
30533   }
30534   if( statfs(filePath, &fsInfo) != -1 ){
30535     if( fsInfo.f_flags & MNT_RDONLY ){
30536       return &nolockIoMethods;
30537     }
30538     for(i=0; aMap[i].zFilesystem; i++){
30539       if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
30540         return aMap[i].pMethods;
30541       }
30542     }
30543   }
30544
30545   /* Default case. Handles, amongst others, "nfs".
30546   ** Test byte-range lock using fcntl(). If the call succeeds, 
30547   ** assume that the file-system supports POSIX style locks. 
30548   */
30549   lockInfo.l_len = 1;
30550   lockInfo.l_start = 0;
30551   lockInfo.l_whence = SEEK_SET;
30552   lockInfo.l_type = F_RDLCK;
30553   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
30554     if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
30555       return &nfsIoMethods;
30556     } else {
30557       return &posixIoMethods;
30558     }
30559   }else{
30560     return &dotlockIoMethods;
30561   }
30562 }
30563 static const sqlite3_io_methods 
30564   *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
30565
30566 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
30567
30568 #if OS_VXWORKS
30569 /*
30570 ** This "finder" function for VxWorks checks to see if posix advisory
30571 ** locking works.  If it does, then that is what is used.  If it does not
30572 ** work, then fallback to named semaphore locking.
30573 */
30574 static const sqlite3_io_methods *vxworksIoFinderImpl(
30575   const char *filePath,    /* name of the database file */
30576   unixFile *pNew           /* the open file object */
30577 ){
30578   struct flock lockInfo;
30579
30580   if( !filePath ){
30581     /* If filePath==NULL that means we are dealing with a transient file
30582     ** that does not need to be locked. */
30583     return &nolockIoMethods;
30584   }
30585
30586   /* Test if fcntl() is supported and use POSIX style locks.
30587   ** Otherwise fall back to the named semaphore method.
30588   */
30589   lockInfo.l_len = 1;
30590   lockInfo.l_start = 0;
30591   lockInfo.l_whence = SEEK_SET;
30592   lockInfo.l_type = F_RDLCK;
30593   if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
30594     return &posixIoMethods;
30595   }else{
30596     return &semIoMethods;
30597   }
30598 }
30599 static const sqlite3_io_methods 
30600   *(*const vxworksIoFinder)(const char*,unixFile*) = vxworksIoFinderImpl;
30601
30602 #endif /* OS_VXWORKS */
30603
30604 /*
30605 ** An abstract type for a pointer to an IO method finder function:
30606 */
30607 typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
30608
30609
30610 /****************************************************************************
30611 **************************** sqlite3_vfs methods ****************************
30612 **
30613 ** This division contains the implementation of methods on the
30614 ** sqlite3_vfs object.
30615 */
30616
30617 /*
30618 ** Initialize the contents of the unixFile structure pointed to by pId.
30619 */
30620 static int fillInUnixFile(
30621   sqlite3_vfs *pVfs,      /* Pointer to vfs object */
30622   int h,                  /* Open file descriptor of file being opened */
30623   sqlite3_file *pId,      /* Write to the unixFile structure here */
30624   const char *zFilename,  /* Name of the file being opened */
30625   int ctrlFlags           /* Zero or more UNIXFILE_* values */
30626 ){
30627   const sqlite3_io_methods *pLockingStyle;
30628   unixFile *pNew = (unixFile *)pId;
30629   int rc = SQLITE_OK;
30630
30631   assert( pNew->pInode==NULL );
30632
30633   /* Usually the path zFilename should not be a relative pathname. The
30634   ** exception is when opening the proxy "conch" file in builds that
30635   ** include the special Apple locking styles.
30636   */
30637 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30638   assert( zFilename==0 || zFilename[0]=='/' 
30639     || pVfs->pAppData==(void*)&autolockIoFinder );
30640 #else
30641   assert( zFilename==0 || zFilename[0]=='/' );
30642 #endif
30643
30644   /* No locking occurs in temporary files */
30645   assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
30646
30647   OSTRACE(("OPEN    %-3d %s\n", h, zFilename));
30648   pNew->h = h;
30649   pNew->pVfs = pVfs;
30650   pNew->zPath = zFilename;
30651   pNew->ctrlFlags = (u8)ctrlFlags;
30652 #if SQLITE_MAX_MMAP_SIZE>0
30653   pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
30654 #endif
30655   if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
30656                            "psow", SQLITE_POWERSAFE_OVERWRITE) ){
30657     pNew->ctrlFlags |= UNIXFILE_PSOW;
30658   }
30659   if( strcmp(pVfs->zName,"unix-excl")==0 ){
30660     pNew->ctrlFlags |= UNIXFILE_EXCL;
30661   }
30662
30663 #if OS_VXWORKS
30664   pNew->pId = vxworksFindFileId(zFilename);
30665   if( pNew->pId==0 ){
30666     ctrlFlags |= UNIXFILE_NOLOCK;
30667     rc = SQLITE_NOMEM;
30668   }
30669 #endif
30670
30671   if( ctrlFlags & UNIXFILE_NOLOCK ){
30672     pLockingStyle = &nolockIoMethods;
30673   }else{
30674     pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
30675 #if SQLITE_ENABLE_LOCKING_STYLE
30676     /* Cache zFilename in the locking context (AFP and dotlock override) for
30677     ** proxyLock activation is possible (remote proxy is based on db name)
30678     ** zFilename remains valid until file is closed, to support */
30679     pNew->lockingContext = (void*)zFilename;
30680 #endif
30681   }
30682
30683   if( pLockingStyle == &posixIoMethods
30684 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
30685     || pLockingStyle == &nfsIoMethods
30686 #endif
30687   ){
30688     unixEnterMutex();
30689     rc = findInodeInfo(pNew, &pNew->pInode);
30690     if( rc!=SQLITE_OK ){
30691       /* If an error occurred in findInodeInfo(), close the file descriptor
30692       ** immediately, before releasing the mutex. findInodeInfo() may fail
30693       ** in two scenarios:
30694       **
30695       **   (a) A call to fstat() failed.
30696       **   (b) A malloc failed.
30697       **
30698       ** Scenario (b) may only occur if the process is holding no other
30699       ** file descriptors open on the same file. If there were other file
30700       ** descriptors on this file, then no malloc would be required by
30701       ** findInodeInfo(). If this is the case, it is quite safe to close
30702       ** handle h - as it is guaranteed that no posix locks will be released
30703       ** by doing so.
30704       **
30705       ** If scenario (a) caused the error then things are not so safe. The
30706       ** implicit assumption here is that if fstat() fails, things are in
30707       ** such bad shape that dropping a lock or two doesn't matter much.
30708       */
30709       robust_close(pNew, h, __LINE__);
30710       h = -1;
30711     }
30712     unixLeaveMutex();
30713   }
30714
30715 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30716   else if( pLockingStyle == &afpIoMethods ){
30717     /* AFP locking uses the file path so it needs to be included in
30718     ** the afpLockingContext.
30719     */
30720     afpLockingContext *pCtx;
30721     pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
30722     if( pCtx==0 ){
30723       rc = SQLITE_NOMEM;
30724     }else{
30725       /* NB: zFilename exists and remains valid until the file is closed
30726       ** according to requirement F11141.  So we do not need to make a
30727       ** copy of the filename. */
30728       pCtx->dbPath = zFilename;
30729       pCtx->reserved = 0;
30730       srandomdev();
30731       unixEnterMutex();
30732       rc = findInodeInfo(pNew, &pNew->pInode);
30733       if( rc!=SQLITE_OK ){
30734         sqlite3_free(pNew->lockingContext);
30735         robust_close(pNew, h, __LINE__);
30736         h = -1;
30737       }
30738       unixLeaveMutex();        
30739     }
30740   }
30741 #endif
30742
30743   else if( pLockingStyle == &dotlockIoMethods ){
30744     /* Dotfile locking uses the file path so it needs to be included in
30745     ** the dotlockLockingContext 
30746     */
30747     char *zLockFile;
30748     int nFilename;
30749     assert( zFilename!=0 );
30750     nFilename = (int)strlen(zFilename) + 6;
30751     zLockFile = (char *)sqlite3_malloc(nFilename);
30752     if( zLockFile==0 ){
30753       rc = SQLITE_NOMEM;
30754     }else{
30755       sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
30756     }
30757     pNew->lockingContext = zLockFile;
30758   }
30759
30760 #if OS_VXWORKS
30761   else if( pLockingStyle == &semIoMethods ){
30762     /* Named semaphore locking uses the file path so it needs to be
30763     ** included in the semLockingContext
30764     */
30765     unixEnterMutex();
30766     rc = findInodeInfo(pNew, &pNew->pInode);
30767     if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
30768       char *zSemName = pNew->pInode->aSemName;
30769       int n;
30770       sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
30771                        pNew->pId->zCanonicalName);
30772       for( n=1; zSemName[n]; n++ )
30773         if( zSemName[n]=='/' ) zSemName[n] = '_';
30774       pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
30775       if( pNew->pInode->pSem == SEM_FAILED ){
30776         rc = SQLITE_NOMEM;
30777         pNew->pInode->aSemName[0] = '\0';
30778       }
30779     }
30780     unixLeaveMutex();
30781   }
30782 #endif
30783   
30784   storeLastErrno(pNew, 0);
30785 #if OS_VXWORKS
30786   if( rc!=SQLITE_OK ){
30787     if( h>=0 ) robust_close(pNew, h, __LINE__);
30788     h = -1;
30789     osUnlink(zFilename);
30790     pNew->ctrlFlags |= UNIXFILE_DELETE;
30791   }
30792 #endif
30793   if( rc!=SQLITE_OK ){
30794     if( h>=0 ) robust_close(pNew, h, __LINE__);
30795   }else{
30796     pNew->pMethod = pLockingStyle;
30797     OpenCounter(+1);
30798     verifyDbFile(pNew);
30799   }
30800   return rc;
30801 }
30802
30803 /*
30804 ** Return the name of a directory in which to put temporary files.
30805 ** If no suitable temporary file directory can be found, return NULL.
30806 */
30807 static const char *unixTempFileDir(void){
30808   static const char *azDirs[] = {
30809      0,
30810      0,
30811      0,
30812      "/var/tmp",
30813      "/usr/tmp",
30814      "/tmp",
30815      0        /* List terminator */
30816   };
30817   unsigned int i;
30818   struct stat buf;
30819   const char *zDir = 0;
30820
30821   azDirs[0] = sqlite3_temp_directory;
30822   if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
30823   if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
30824   for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
30825     if( zDir==0 ) continue;
30826     if( osStat(zDir, &buf) ) continue;
30827     if( !S_ISDIR(buf.st_mode) ) continue;
30828     if( osAccess(zDir, 07) ) continue;
30829     break;
30830   }
30831   return zDir;
30832 }
30833
30834 /*
30835 ** Create a temporary file name in zBuf.  zBuf must be allocated
30836 ** by the calling process and must be big enough to hold at least
30837 ** pVfs->mxPathname bytes.
30838 */
30839 static int unixGetTempname(int nBuf, char *zBuf){
30840   static const unsigned char zChars[] =
30841     "abcdefghijklmnopqrstuvwxyz"
30842     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
30843     "0123456789";
30844   unsigned int i, j;
30845   const char *zDir;
30846
30847   /* It's odd to simulate an io-error here, but really this is just
30848   ** using the io-error infrastructure to test that SQLite handles this
30849   ** function failing. 
30850   */
30851   SimulateIOError( return SQLITE_IOERR );
30852
30853   zDir = unixTempFileDir();
30854   if( zDir==0 ) zDir = ".";
30855
30856   /* Check that the output buffer is large enough for the temporary file 
30857   ** name. If it is not, return SQLITE_ERROR.
30858   */
30859   if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
30860     return SQLITE_ERROR;
30861   }
30862
30863   do{
30864     sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
30865     j = (int)strlen(zBuf);
30866     sqlite3_randomness(15, &zBuf[j]);
30867     for(i=0; i<15; i++, j++){
30868       zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
30869     }
30870     zBuf[j] = 0;
30871     zBuf[j+1] = 0;
30872   }while( osAccess(zBuf,0)==0 );
30873   return SQLITE_OK;
30874 }
30875
30876 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
30877 /*
30878 ** Routine to transform a unixFile into a proxy-locking unixFile.
30879 ** Implementation in the proxy-lock division, but used by unixOpen()
30880 ** if SQLITE_PREFER_PROXY_LOCKING is defined.
30881 */
30882 static int proxyTransformUnixFile(unixFile*, const char*);
30883 #endif
30884
30885 /*
30886 ** Search for an unused file descriptor that was opened on the database 
30887 ** file (not a journal or master-journal file) identified by pathname
30888 ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
30889 ** argument to this function.
30890 **
30891 ** Such a file descriptor may exist if a database connection was closed
30892 ** but the associated file descriptor could not be closed because some
30893 ** other file descriptor open on the same file is holding a file-lock.
30894 ** Refer to comments in the unixClose() function and the lengthy comment
30895 ** describing "Posix Advisory Locking" at the start of this file for 
30896 ** further details. Also, ticket #4018.
30897 **
30898 ** If a suitable file descriptor is found, then it is returned. If no
30899 ** such file descriptor is located, -1 is returned.
30900 */
30901 static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
30902   UnixUnusedFd *pUnused = 0;
30903
30904   /* Do not search for an unused file descriptor on vxworks. Not because
30905   ** vxworks would not benefit from the change (it might, we're not sure),
30906   ** but because no way to test it is currently available. It is better 
30907   ** not to risk breaking vxworks support for the sake of such an obscure 
30908   ** feature.  */
30909 #if !OS_VXWORKS
30910   struct stat sStat;                   /* Results of stat() call */
30911
30912   /* A stat() call may fail for various reasons. If this happens, it is
30913   ** almost certain that an open() call on the same path will also fail.
30914   ** For this reason, if an error occurs in the stat() call here, it is
30915   ** ignored and -1 is returned. The caller will try to open a new file
30916   ** descriptor on the same path, fail, and return an error to SQLite.
30917   **
30918   ** Even if a subsequent open() call does succeed, the consequences of
30919   ** not searching for a reusable file descriptor are not dire.  */
30920   if( 0==osStat(zPath, &sStat) ){
30921     unixInodeInfo *pInode;
30922
30923     unixEnterMutex();
30924     pInode = inodeList;
30925     while( pInode && (pInode->fileId.dev!=sStat.st_dev
30926                      || pInode->fileId.ino!=sStat.st_ino) ){
30927        pInode = pInode->pNext;
30928     }
30929     if( pInode ){
30930       UnixUnusedFd **pp;
30931       for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
30932       pUnused = *pp;
30933       if( pUnused ){
30934         *pp = pUnused->pNext;
30935       }
30936     }
30937     unixLeaveMutex();
30938   }
30939 #endif    /* if !OS_VXWORKS */
30940   return pUnused;
30941 }
30942
30943 /*
30944 ** This function is called by unixOpen() to determine the unix permissions
30945 ** to create new files with. If no error occurs, then SQLITE_OK is returned
30946 ** and a value suitable for passing as the third argument to open(2) is
30947 ** written to *pMode. If an IO error occurs, an SQLite error code is 
30948 ** returned and the value of *pMode is not modified.
30949 **
30950 ** In most cases, this routine sets *pMode to 0, which will become
30951 ** an indication to robust_open() to create the file using
30952 ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
30953 ** But if the file being opened is a WAL or regular journal file, then 
30954 ** this function queries the file-system for the permissions on the 
30955 ** corresponding database file and sets *pMode to this value. Whenever 
30956 ** possible, WAL and journal files are created using the same permissions 
30957 ** as the associated database file.
30958 **
30959 ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
30960 ** original filename is unavailable.  But 8_3_NAMES is only used for
30961 ** FAT filesystems and permissions do not matter there, so just use
30962 ** the default permissions.
30963 */
30964 static int findCreateFileMode(
30965   const char *zPath,              /* Path of file (possibly) being created */
30966   int flags,                      /* Flags passed as 4th argument to xOpen() */
30967   mode_t *pMode,                  /* OUT: Permissions to open file with */
30968   uid_t *pUid,                    /* OUT: uid to set on the file */
30969   gid_t *pGid                     /* OUT: gid to set on the file */
30970 ){
30971   int rc = SQLITE_OK;             /* Return Code */
30972   *pMode = 0;
30973   *pUid = 0;
30974   *pGid = 0;
30975   if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
30976     char zDb[MAX_PATHNAME+1];     /* Database file path */
30977     int nDb;                      /* Number of valid bytes in zDb */
30978     struct stat sStat;            /* Output of stat() on database file */
30979
30980     /* zPath is a path to a WAL or journal file. The following block derives
30981     ** the path to the associated database file from zPath. This block handles
30982     ** the following naming conventions:
30983     **
30984     **   "<path to db>-journal"
30985     **   "<path to db>-wal"
30986     **   "<path to db>-journalNN"
30987     **   "<path to db>-walNN"
30988     **
30989     ** where NN is a decimal number. The NN naming schemes are 
30990     ** used by the test_multiplex.c module.
30991     */
30992     nDb = sqlite3Strlen30(zPath) - 1; 
30993 #ifdef SQLITE_ENABLE_8_3_NAMES
30994     while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
30995     if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
30996 #else
30997     while( zPath[nDb]!='-' ){
30998       assert( nDb>0 );
30999       assert( zPath[nDb]!='\n' );
31000       nDb--;
31001     }
31002 #endif
31003     memcpy(zDb, zPath, nDb);
31004     zDb[nDb] = '\0';
31005
31006     if( 0==osStat(zDb, &sStat) ){
31007       *pMode = sStat.st_mode & 0777;
31008       *pUid = sStat.st_uid;
31009       *pGid = sStat.st_gid;
31010     }else{
31011       rc = SQLITE_IOERR_FSTAT;
31012     }
31013   }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
31014     *pMode = 0600;
31015   }
31016   return rc;
31017 }
31018
31019 /*
31020 ** Open the file zPath.
31021 ** 
31022 ** Previously, the SQLite OS layer used three functions in place of this
31023 ** one:
31024 **
31025 **     sqlite3OsOpenReadWrite();
31026 **     sqlite3OsOpenReadOnly();
31027 **     sqlite3OsOpenExclusive();
31028 **
31029 ** These calls correspond to the following combinations of flags:
31030 **
31031 **     ReadWrite() ->     (READWRITE | CREATE)
31032 **     ReadOnly()  ->     (READONLY) 
31033 **     OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
31034 **
31035 ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
31036 ** true, the file was configured to be automatically deleted when the
31037 ** file handle closed. To achieve the same effect using this new 
31038 ** interface, add the DELETEONCLOSE flag to those specified above for 
31039 ** OpenExclusive().
31040 */
31041 static int unixOpen(
31042   sqlite3_vfs *pVfs,           /* The VFS for which this is the xOpen method */
31043   const char *zPath,           /* Pathname of file to be opened */
31044   sqlite3_file *pFile,         /* The file descriptor to be filled in */
31045   int flags,                   /* Input flags to control the opening */
31046   int *pOutFlags               /* Output flags returned to SQLite core */
31047 ){
31048   unixFile *p = (unixFile *)pFile;
31049   int fd = -1;                   /* File descriptor returned by open() */
31050   int openFlags = 0;             /* Flags to pass to open() */
31051   int eType = flags&0xFFFFFF00;  /* Type of file to open */
31052   int noLock;                    /* True to omit locking primitives */
31053   int rc = SQLITE_OK;            /* Function Return Code */
31054   int ctrlFlags = 0;             /* UNIXFILE_* flags */
31055
31056   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
31057   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
31058   int isCreate     = (flags & SQLITE_OPEN_CREATE);
31059   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
31060   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
31061 #if SQLITE_ENABLE_LOCKING_STYLE
31062   int isAutoProxy  = (flags & SQLITE_OPEN_AUTOPROXY);
31063 #endif
31064 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
31065   struct statfs fsInfo;
31066 #endif
31067
31068   /* If creating a master or main-file journal, this function will open
31069   ** a file-descriptor on the directory too. The first time unixSync()
31070   ** is called the directory file descriptor will be fsync()ed and close()d.
31071   */
31072   int syncDir = (isCreate && (
31073         eType==SQLITE_OPEN_MASTER_JOURNAL 
31074      || eType==SQLITE_OPEN_MAIN_JOURNAL 
31075      || eType==SQLITE_OPEN_WAL
31076   ));
31077
31078   /* If argument zPath is a NULL pointer, this function is required to open
31079   ** a temporary file. Use this buffer to store the file name in.
31080   */
31081   char zTmpname[MAX_PATHNAME+2];
31082   const char *zName = zPath;
31083
31084   /* Check the following statements are true: 
31085   **
31086   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and 
31087   **   (b) if CREATE is set, then READWRITE must also be set, and
31088   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
31089   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
31090   */
31091   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
31092   assert(isCreate==0 || isReadWrite);
31093   assert(isExclusive==0 || isCreate);
31094   assert(isDelete==0 || isCreate);
31095
31096   /* The main DB, main journal, WAL file and master journal are never 
31097   ** automatically deleted. Nor are they ever temporary files.  */
31098   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
31099   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
31100   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
31101   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
31102
31103   /* Assert that the upper layer has set one of the "file-type" flags. */
31104   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB 
31105        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL 
31106        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL 
31107        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
31108   );
31109
31110   /* Detect a pid change and reset the PRNG.  There is a race condition
31111   ** here such that two or more threads all trying to open databases at
31112   ** the same instant might all reset the PRNG.  But multiple resets
31113   ** are harmless.
31114   */
31115   if( randomnessPid!=osGetpid(0) ){
31116     randomnessPid = osGetpid(0);
31117     sqlite3_randomness(0,0);
31118   }
31119
31120   memset(p, 0, sizeof(unixFile));
31121
31122   if( eType==SQLITE_OPEN_MAIN_DB ){
31123     UnixUnusedFd *pUnused;
31124     pUnused = findReusableFd(zName, flags);
31125     if( pUnused ){
31126       fd = pUnused->fd;
31127     }else{
31128       pUnused = sqlite3_malloc(sizeof(*pUnused));
31129       if( !pUnused ){
31130         return SQLITE_NOMEM;
31131       }
31132     }
31133     p->pUnused = pUnused;
31134
31135     /* Database filenames are double-zero terminated if they are not
31136     ** URIs with parameters.  Hence, they can always be passed into
31137     ** sqlite3_uri_parameter(). */
31138     assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
31139
31140   }else if( !zName ){
31141     /* If zName is NULL, the upper layer is requesting a temp file. */
31142     assert(isDelete && !syncDir);
31143     rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
31144     if( rc!=SQLITE_OK ){
31145       return rc;
31146     }
31147     zName = zTmpname;
31148
31149     /* Generated temporary filenames are always double-zero terminated
31150     ** for use by sqlite3_uri_parameter(). */
31151     assert( zName[strlen(zName)+1]==0 );
31152   }
31153
31154   /* Determine the value of the flags parameter passed to POSIX function
31155   ** open(). These must be calculated even if open() is not called, as
31156   ** they may be stored as part of the file handle and used by the 
31157   ** 'conch file' locking functions later on.  */
31158   if( isReadonly )  openFlags |= O_RDONLY;
31159   if( isReadWrite ) openFlags |= O_RDWR;
31160   if( isCreate )    openFlags |= O_CREAT;
31161   if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
31162   openFlags |= (O_LARGEFILE|O_BINARY);
31163
31164   if( fd<0 ){
31165     mode_t openMode;              /* Permissions to create file with */
31166     uid_t uid;                    /* Userid for the file */
31167     gid_t gid;                    /* Groupid for the file */
31168     rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
31169     if( rc!=SQLITE_OK ){
31170       assert( !p->pUnused );
31171       assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
31172       return rc;
31173     }
31174     fd = robust_open(zName, openFlags, openMode);
31175     OSTRACE(("OPENX   %-3d %s 0%o\n", fd, zName, openFlags));
31176     if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
31177       /* Failed to open the file for read/write access. Try read-only. */
31178       flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
31179       openFlags &= ~(O_RDWR|O_CREAT);
31180       flags |= SQLITE_OPEN_READONLY;
31181       openFlags |= O_RDONLY;
31182       isReadonly = 1;
31183       fd = robust_open(zName, openFlags, openMode);
31184     }
31185     if( fd<0 ){
31186       rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
31187       goto open_finished;
31188     }
31189
31190     /* If this process is running as root and if creating a new rollback
31191     ** journal or WAL file, set the ownership of the journal or WAL to be
31192     ** the same as the original database.
31193     */
31194     if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
31195       osFchown(fd, uid, gid);
31196     }
31197   }
31198   assert( fd>=0 );
31199   if( pOutFlags ){
31200     *pOutFlags = flags;
31201   }
31202
31203   if( p->pUnused ){
31204     p->pUnused->fd = fd;
31205     p->pUnused->flags = flags;
31206   }
31207
31208   if( isDelete ){
31209 #if OS_VXWORKS
31210     zPath = zName;
31211 #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
31212     zPath = sqlite3_mprintf("%s", zName);
31213     if( zPath==0 ){
31214       robust_close(p, fd, __LINE__);
31215       return SQLITE_NOMEM;
31216     }
31217 #else
31218     osUnlink(zName);
31219 #endif
31220   }
31221 #if SQLITE_ENABLE_LOCKING_STYLE
31222   else{
31223     p->openFlags = openFlags;
31224   }
31225 #endif
31226
31227   noLock = eType!=SQLITE_OPEN_MAIN_DB;
31228
31229   
31230 #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
31231   if( fstatfs(fd, &fsInfo) == -1 ){
31232     storeLastErrno(p, errno);
31233     robust_close(p, fd, __LINE__);
31234     return SQLITE_IOERR_ACCESS;
31235   }
31236   if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
31237     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
31238   }
31239   if (0 == strncmp("exfat", fsInfo.f_fstypename, 5)) {
31240     ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
31241   }
31242 #endif
31243
31244   /* Set up appropriate ctrlFlags */
31245   if( isDelete )                ctrlFlags |= UNIXFILE_DELETE;
31246   if( isReadonly )              ctrlFlags |= UNIXFILE_RDONLY;
31247   if( noLock )                  ctrlFlags |= UNIXFILE_NOLOCK;
31248   if( syncDir )                 ctrlFlags |= UNIXFILE_DIRSYNC;
31249   if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
31250
31251 #if SQLITE_ENABLE_LOCKING_STYLE
31252 #if SQLITE_PREFER_PROXY_LOCKING
31253   isAutoProxy = 1;
31254 #endif
31255   if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
31256     char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
31257     int useProxy = 0;
31258
31259     /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means 
31260     ** never use proxy, NULL means use proxy for non-local files only.  */
31261     if( envforce!=NULL ){
31262       useProxy = atoi(envforce)>0;
31263     }else{
31264       useProxy = !(fsInfo.f_flags&MNT_LOCAL);
31265     }
31266     if( useProxy ){
31267       rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
31268       if( rc==SQLITE_OK ){
31269         rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
31270         if( rc!=SQLITE_OK ){
31271           /* Use unixClose to clean up the resources added in fillInUnixFile 
31272           ** and clear all the structure's references.  Specifically, 
31273           ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op 
31274           */
31275           unixClose(pFile);
31276           return rc;
31277         }
31278       }
31279       goto open_finished;
31280     }
31281   }
31282 #endif
31283   
31284   rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
31285
31286 open_finished:
31287   if( rc!=SQLITE_OK ){
31288     sqlite3_free(p->pUnused);
31289   }
31290   return rc;
31291 }
31292
31293
31294 /*
31295 ** Delete the file at zPath. If the dirSync argument is true, fsync()
31296 ** the directory after deleting the file.
31297 */
31298 static int unixDelete(
31299   sqlite3_vfs *NotUsed,     /* VFS containing this as the xDelete method */
31300   const char *zPath,        /* Name of file to be deleted */
31301   int dirSync               /* If true, fsync() directory after deleting file */
31302 ){
31303   int rc = SQLITE_OK;
31304   UNUSED_PARAMETER(NotUsed);
31305   SimulateIOError(return SQLITE_IOERR_DELETE);
31306   if( osUnlink(zPath)==(-1) ){
31307     if( errno==ENOENT
31308 #if OS_VXWORKS
31309         || osAccess(zPath,0)!=0
31310 #endif
31311     ){
31312       rc = SQLITE_IOERR_DELETE_NOENT;
31313     }else{
31314       rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
31315     }
31316     return rc;
31317   }
31318 #ifndef SQLITE_DISABLE_DIRSYNC
31319   if( (dirSync & 1)!=0 ){
31320     int fd;
31321     rc = osOpenDirectory(zPath, &fd);
31322     if( rc==SQLITE_OK ){
31323 #if OS_VXWORKS
31324       if( fsync(fd)==-1 )
31325 #else
31326       if( fsync(fd) )
31327 #endif
31328       {
31329         rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
31330       }
31331       robust_close(0, fd, __LINE__);
31332     }else if( rc==SQLITE_CANTOPEN ){
31333       rc = SQLITE_OK;
31334     }
31335   }
31336 #endif
31337   return rc;
31338 }
31339
31340 /*
31341 ** Test the existence of or access permissions of file zPath. The
31342 ** test performed depends on the value of flags:
31343 **
31344 **     SQLITE_ACCESS_EXISTS: Return 1 if the file exists
31345 **     SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
31346 **     SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
31347 **
31348 ** Otherwise return 0.
31349 */
31350 static int unixAccess(
31351   sqlite3_vfs *NotUsed,   /* The VFS containing this xAccess method */
31352   const char *zPath,      /* Path of the file to examine */
31353   int flags,              /* What do we want to learn about the zPath file? */
31354   int *pResOut            /* Write result boolean here */
31355 ){
31356   int amode = 0;
31357   UNUSED_PARAMETER(NotUsed);
31358   SimulateIOError( return SQLITE_IOERR_ACCESS; );
31359   switch( flags ){
31360     case SQLITE_ACCESS_EXISTS:
31361       amode = F_OK;
31362       break;
31363     case SQLITE_ACCESS_READWRITE:
31364       amode = W_OK|R_OK;
31365       break;
31366     case SQLITE_ACCESS_READ:
31367       amode = R_OK;
31368       break;
31369
31370     default:
31371       assert(!"Invalid flags argument");
31372   }
31373   *pResOut = (osAccess(zPath, amode)==0);
31374   if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
31375     struct stat buf;
31376     if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
31377       *pResOut = 0;
31378     }
31379   }
31380   return SQLITE_OK;
31381 }
31382
31383
31384 /*
31385 ** Turn a relative pathname into a full pathname. The relative path
31386 ** is stored as a nul-terminated string in the buffer pointed to by
31387 ** zPath. 
31388 **
31389 ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes 
31390 ** (in this case, MAX_PATHNAME bytes). The full-path is written to
31391 ** this buffer before returning.
31392 */
31393 static int unixFullPathname(
31394   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
31395   const char *zPath,            /* Possibly relative input path */
31396   int nOut,                     /* Size of output buffer in bytes */
31397   char *zOut                    /* Output buffer */
31398 ){
31399
31400   /* It's odd to simulate an io-error here, but really this is just
31401   ** using the io-error infrastructure to test that SQLite handles this
31402   ** function failing. This function could fail if, for example, the
31403   ** current working directory has been unlinked.
31404   */
31405   SimulateIOError( return SQLITE_ERROR );
31406
31407   assert( pVfs->mxPathname==MAX_PATHNAME );
31408   UNUSED_PARAMETER(pVfs);
31409
31410   zOut[nOut-1] = '\0';
31411   if( zPath[0]=='/' ){
31412     sqlite3_snprintf(nOut, zOut, "%s", zPath);
31413   }else{
31414     int nCwd;
31415     if( osGetcwd(zOut, nOut-1)==0 ){
31416       return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
31417     }
31418     nCwd = (int)strlen(zOut);
31419     sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
31420   }
31421   return SQLITE_OK;
31422 }
31423
31424
31425 #ifndef SQLITE_OMIT_LOAD_EXTENSION
31426 /*
31427 ** Interfaces for opening a shared library, finding entry points
31428 ** within the shared library, and closing the shared library.
31429 */
31430 #include <dlfcn.h>
31431 static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
31432   UNUSED_PARAMETER(NotUsed);
31433   return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
31434 }
31435
31436 /*
31437 ** SQLite calls this function immediately after a call to unixDlSym() or
31438 ** unixDlOpen() fails (returns a null pointer). If a more detailed error
31439 ** message is available, it is written to zBufOut. If no error message
31440 ** is available, zBufOut is left unmodified and SQLite uses a default
31441 ** error message.
31442 */
31443 static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
31444   const char *zErr;
31445   UNUSED_PARAMETER(NotUsed);
31446   unixEnterMutex();
31447   zErr = dlerror();
31448   if( zErr ){
31449     sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
31450   }
31451   unixLeaveMutex();
31452 }
31453 static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
31454   /* 
31455   ** GCC with -pedantic-errors says that C90 does not allow a void* to be
31456   ** cast into a pointer to a function.  And yet the library dlsym() routine
31457   ** returns a void* which is really a pointer to a function.  So how do we
31458   ** use dlsym() with -pedantic-errors?
31459   **
31460   ** Variable x below is defined to be a pointer to a function taking
31461   ** parameters void* and const char* and returning a pointer to a function.
31462   ** We initialize x by assigning it a pointer to the dlsym() function.
31463   ** (That assignment requires a cast.)  Then we call the function that
31464   ** x points to.  
31465   **
31466   ** This work-around is unlikely to work correctly on any system where
31467   ** you really cannot cast a function pointer into void*.  But then, on the
31468   ** other hand, dlsym() will not work on such a system either, so we have
31469   ** not really lost anything.
31470   */
31471   void (*(*x)(void*,const char*))(void);
31472   UNUSED_PARAMETER(NotUsed);
31473   x = (void(*(*)(void*,const char*))(void))dlsym;
31474   return (*x)(p, zSym);
31475 }
31476 static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
31477   UNUSED_PARAMETER(NotUsed);
31478   dlclose(pHandle);
31479 }
31480 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
31481   #define unixDlOpen  0
31482   #define unixDlError 0
31483   #define unixDlSym   0
31484   #define unixDlClose 0
31485 #endif
31486
31487 /*
31488 ** Write nBuf bytes of random data to the supplied buffer zBuf.
31489 */
31490 static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
31491   UNUSED_PARAMETER(NotUsed);
31492   assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
31493
31494   /* We have to initialize zBuf to prevent valgrind from reporting
31495   ** errors.  The reports issued by valgrind are incorrect - we would
31496   ** prefer that the randomness be increased by making use of the
31497   ** uninitialized space in zBuf - but valgrind errors tend to worry
31498   ** some users.  Rather than argue, it seems easier just to initialize
31499   ** the whole array and silence valgrind, even if that means less randomness
31500   ** in the random seed.
31501   **
31502   ** When testing, initializing zBuf[] to zero is all we do.  That means
31503   ** that we always use the same random number sequence.  This makes the
31504   ** tests repeatable.
31505   */
31506   memset(zBuf, 0, nBuf);
31507   randomnessPid = osGetpid(0);  
31508 #if !defined(SQLITE_TEST)
31509   {
31510     int fd, got;
31511     fd = robust_open("/dev/urandom", O_RDONLY, 0);
31512     if( fd<0 ){
31513       time_t t;
31514       time(&t);
31515       memcpy(zBuf, &t, sizeof(t));
31516       memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
31517       assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
31518       nBuf = sizeof(t) + sizeof(randomnessPid);
31519     }else{
31520       do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
31521       robust_close(0, fd, __LINE__);
31522     }
31523   }
31524 #endif
31525   return nBuf;
31526 }
31527
31528
31529 /*
31530 ** Sleep for a little while.  Return the amount of time slept.
31531 ** The argument is the number of microseconds we want to sleep.
31532 ** The return value is the number of microseconds of sleep actually
31533 ** requested from the underlying operating system, a number which
31534 ** might be greater than or equal to the argument, but not less
31535 ** than the argument.
31536 */
31537 static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
31538 #if OS_VXWORKS
31539   struct timespec sp;
31540
31541   sp.tv_sec = microseconds / 1000000;
31542   sp.tv_nsec = (microseconds % 1000000) * 1000;
31543   nanosleep(&sp, NULL);
31544   UNUSED_PARAMETER(NotUsed);
31545   return microseconds;
31546 #elif defined(HAVE_USLEEP) && HAVE_USLEEP
31547   usleep(microseconds);
31548   UNUSED_PARAMETER(NotUsed);
31549   return microseconds;
31550 #else
31551   int seconds = (microseconds+999999)/1000000;
31552   sleep(seconds);
31553   UNUSED_PARAMETER(NotUsed);
31554   return seconds*1000000;
31555 #endif
31556 }
31557
31558 /*
31559 ** The following variable, if set to a non-zero value, is interpreted as
31560 ** the number of seconds since 1970 and is used to set the result of
31561 ** sqlite3OsCurrentTime() during testing.
31562 */
31563 #ifdef SQLITE_TEST
31564 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
31565 #endif
31566
31567 /*
31568 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
31569 ** the current time and date as a Julian Day number times 86_400_000.  In
31570 ** other words, write into *piNow the number of milliseconds since the Julian
31571 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
31572 ** proleptic Gregorian calendar.
31573 **
31574 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date 
31575 ** cannot be found.
31576 */
31577 static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
31578   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
31579   int rc = SQLITE_OK;
31580 #if defined(NO_GETTOD)
31581   time_t t;
31582   time(&t);
31583   *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
31584 #elif OS_VXWORKS
31585   struct timespec sNow;
31586   clock_gettime(CLOCK_REALTIME, &sNow);
31587   *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
31588 #else
31589   struct timeval sNow;
31590   if( gettimeofday(&sNow, 0)==0 ){
31591     *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
31592   }else{
31593     rc = SQLITE_ERROR;
31594   }
31595 #endif
31596
31597 #ifdef SQLITE_TEST
31598   if( sqlite3_current_time ){
31599     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
31600   }
31601 #endif
31602   UNUSED_PARAMETER(NotUsed);
31603   return rc;
31604 }
31605
31606 /*
31607 ** Find the current time (in Universal Coordinated Time).  Write the
31608 ** current time and date as a Julian Day number into *prNow and
31609 ** return 0.  Return 1 if the time and date cannot be found.
31610 */
31611 static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
31612   sqlite3_int64 i = 0;
31613   int rc;
31614   UNUSED_PARAMETER(NotUsed);
31615   rc = unixCurrentTimeInt64(0, &i);
31616   *prNow = i/86400000.0;
31617   return rc;
31618 }
31619
31620 /*
31621 ** We added the xGetLastError() method with the intention of providing
31622 ** better low-level error messages when operating-system problems come up
31623 ** during SQLite operation.  But so far, none of that has been implemented
31624 ** in the core.  So this routine is never called.  For now, it is merely
31625 ** a place-holder.
31626 */
31627 static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
31628   UNUSED_PARAMETER(NotUsed);
31629   UNUSED_PARAMETER(NotUsed2);
31630   UNUSED_PARAMETER(NotUsed3);
31631   return 0;
31632 }
31633
31634
31635 /*
31636 ************************ End of sqlite3_vfs methods ***************************
31637 ******************************************************************************/
31638
31639 /******************************************************************************
31640 ************************** Begin Proxy Locking ********************************
31641 **
31642 ** Proxy locking is a "uber-locking-method" in this sense:  It uses the
31643 ** other locking methods on secondary lock files.  Proxy locking is a
31644 ** meta-layer over top of the primitive locking implemented above.  For
31645 ** this reason, the division that implements of proxy locking is deferred
31646 ** until late in the file (here) after all of the other I/O methods have
31647 ** been defined - so that the primitive locking methods are available
31648 ** as services to help with the implementation of proxy locking.
31649 **
31650 ****
31651 **
31652 ** The default locking schemes in SQLite use byte-range locks on the
31653 ** database file to coordinate safe, concurrent access by multiple readers
31654 ** and writers [http://sqlite.org/lockingv3.html].  The five file locking
31655 ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
31656 ** as POSIX read & write locks over fixed set of locations (via fsctl),
31657 ** on AFP and SMB only exclusive byte-range locks are available via fsctl
31658 ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
31659 ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
31660 ** address in the shared range is taken for a SHARED lock, the entire
31661 ** shared range is taken for an EXCLUSIVE lock):
31662 **
31663 **      PENDING_BYTE        0x40000000
31664 **      RESERVED_BYTE       0x40000001
31665 **      SHARED_RANGE        0x40000002 -> 0x40000200
31666 **
31667 ** This works well on the local file system, but shows a nearly 100x
31668 ** slowdown in read performance on AFP because the AFP client disables
31669 ** the read cache when byte-range locks are present.  Enabling the read
31670 ** cache exposes a cache coherency problem that is present on all OS X
31671 ** supported network file systems.  NFS and AFP both observe the
31672 ** close-to-open semantics for ensuring cache coherency
31673 ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
31674 ** address the requirements for concurrent database access by multiple
31675 ** readers and writers
31676 ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
31677 **
31678 ** To address the performance and cache coherency issues, proxy file locking
31679 ** changes the way database access is controlled by limiting access to a
31680 ** single host at a time and moving file locks off of the database file
31681 ** and onto a proxy file on the local file system.  
31682 **
31683 **
31684 ** Using proxy locks
31685 ** -----------------
31686 **
31687 ** C APIs
31688 **
31689 **  sqlite3_file_control(db, dbname, SQLITE_FCNTL_SET_LOCKPROXYFILE,
31690 **                       <proxy_path> | ":auto:");
31691 **  sqlite3_file_control(db, dbname, SQLITE_FCNTL_GET_LOCKPROXYFILE,
31692 **                       &<proxy_path>);
31693 **
31694 **
31695 ** SQL pragmas
31696 **
31697 **  PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
31698 **  PRAGMA [database.]lock_proxy_file
31699 **
31700 ** Specifying ":auto:" means that if there is a conch file with a matching
31701 ** host ID in it, the proxy path in the conch file will be used, otherwise
31702 ** a proxy path based on the user's temp dir
31703 ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
31704 ** actual proxy file name is generated from the name and path of the
31705 ** database file.  For example:
31706 **
31707 **       For database path "/Users/me/foo.db" 
31708 **       The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
31709 **
31710 ** Once a lock proxy is configured for a database connection, it can not
31711 ** be removed, however it may be switched to a different proxy path via
31712 ** the above APIs (assuming the conch file is not being held by another
31713 ** connection or process). 
31714 **
31715 **
31716 ** How proxy locking works
31717 ** -----------------------
31718 **
31719 ** Proxy file locking relies primarily on two new supporting files: 
31720 **
31721 **   *  conch file to limit access to the database file to a single host
31722 **      at a time
31723 **
31724 **   *  proxy file to act as a proxy for the advisory locks normally
31725 **      taken on the database
31726 **
31727 ** The conch file - to use a proxy file, sqlite must first "hold the conch"
31728 ** by taking an sqlite-style shared lock on the conch file, reading the
31729 ** contents and comparing the host's unique host ID (see below) and lock
31730 ** proxy path against the values stored in the conch.  The conch file is
31731 ** stored in the same directory as the database file and the file name
31732 ** is patterned after the database file name as ".<databasename>-conch".
31733 ** If the conch file does not exist, or its contents do not match the
31734 ** host ID and/or proxy path, then the lock is escalated to an exclusive
31735 ** lock and the conch file contents is updated with the host ID and proxy
31736 ** path and the lock is downgraded to a shared lock again.  If the conch
31737 ** is held by another process (with a shared lock), the exclusive lock
31738 ** will fail and SQLITE_BUSY is returned.
31739 **
31740 ** The proxy file - a single-byte file used for all advisory file locks
31741 ** normally taken on the database file.   This allows for safe sharing
31742 ** of the database file for multiple readers and writers on the same
31743 ** host (the conch ensures that they all use the same local lock file).
31744 **
31745 ** Requesting the lock proxy does not immediately take the conch, it is
31746 ** only taken when the first request to lock database file is made.  
31747 ** This matches the semantics of the traditional locking behavior, where
31748 ** opening a connection to a database file does not take a lock on it.
31749 ** The shared lock and an open file descriptor are maintained until 
31750 ** the connection to the database is closed. 
31751 **
31752 ** The proxy file and the lock file are never deleted so they only need
31753 ** to be created the first time they are used.
31754 **
31755 ** Configuration options
31756 ** ---------------------
31757 **
31758 **  SQLITE_PREFER_PROXY_LOCKING
31759 **
31760 **       Database files accessed on non-local file systems are
31761 **       automatically configured for proxy locking, lock files are
31762 **       named automatically using the same logic as
31763 **       PRAGMA lock_proxy_file=":auto:"
31764 **    
31765 **  SQLITE_PROXY_DEBUG
31766 **
31767 **       Enables the logging of error messages during host id file
31768 **       retrieval and creation
31769 **
31770 **  LOCKPROXYDIR
31771 **
31772 **       Overrides the default directory used for lock proxy files that
31773 **       are named automatically via the ":auto:" setting
31774 **
31775 **  SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
31776 **
31777 **       Permissions to use when creating a directory for storing the
31778 **       lock proxy files, only used when LOCKPROXYDIR is not set.
31779 **    
31780 **    
31781 ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
31782 ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
31783 ** force proxy locking to be used for every database file opened, and 0
31784 ** will force automatic proxy locking to be disabled for all database
31785 ** files (explicitly calling the SQLITE_FCNTL_SET_LOCKPROXYFILE pragma or
31786 ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
31787 */
31788
31789 /*
31790 ** Proxy locking is only available on MacOSX 
31791 */
31792 #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
31793
31794 /*
31795 ** The proxyLockingContext has the path and file structures for the remote 
31796 ** and local proxy files in it
31797 */
31798 typedef struct proxyLockingContext proxyLockingContext;
31799 struct proxyLockingContext {
31800   unixFile *conchFile;         /* Open conch file */
31801   char *conchFilePath;         /* Name of the conch file */
31802   unixFile *lockProxy;         /* Open proxy lock file */
31803   char *lockProxyPath;         /* Name of the proxy lock file */
31804   char *dbPath;                /* Name of the open file */
31805   int conchHeld;               /* 1 if the conch is held, -1 if lockless */
31806   int nFails;                  /* Number of conch taking failures */
31807   void *oldLockingContext;     /* Original lockingcontext to restore on close */
31808   sqlite3_io_methods const *pOldMethod;     /* Original I/O methods for close */
31809 };
31810
31811 /* 
31812 ** The proxy lock file path for the database at dbPath is written into lPath, 
31813 ** which must point to valid, writable memory large enough for a maxLen length
31814 ** file path. 
31815 */
31816 static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
31817   int len;
31818   int dbLen;
31819   int i;
31820
31821 #ifdef LOCKPROXYDIR
31822   len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
31823 #else
31824 # ifdef _CS_DARWIN_USER_TEMP_DIR
31825   {
31826     if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
31827       OSTRACE(("GETLOCKPATH  failed %s errno=%d pid=%d\n",
31828                lPath, errno, osGetpid(0)));
31829       return SQLITE_IOERR_LOCK;
31830     }
31831     len = strlcat(lPath, "sqliteplocks", maxLen);    
31832   }
31833 # else
31834   len = strlcpy(lPath, "/tmp/", maxLen);
31835 # endif
31836 #endif
31837
31838   if( lPath[len-1]!='/' ){
31839     len = strlcat(lPath, "/", maxLen);
31840   }
31841   
31842   /* transform the db path to a unique cache name */
31843   dbLen = (int)strlen(dbPath);
31844   for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
31845     char c = dbPath[i];
31846     lPath[i+len] = (c=='/')?'_':c;
31847   }
31848   lPath[i+len]='\0';
31849   strlcat(lPath, ":auto:", maxLen);
31850   OSTRACE(("GETLOCKPATH  proxy lock path=%s pid=%d\n", lPath, osGetpid(0)));
31851   return SQLITE_OK;
31852 }
31853
31854 /* 
31855  ** Creates the lock file and any missing directories in lockPath
31856  */
31857 static int proxyCreateLockPath(const char *lockPath){
31858   int i, len;
31859   char buf[MAXPATHLEN];
31860   int start = 0;
31861   
31862   assert(lockPath!=NULL);
31863   /* try to create all the intermediate directories */
31864   len = (int)strlen(lockPath);
31865   buf[0] = lockPath[0];
31866   for( i=1; i<len; i++ ){
31867     if( lockPath[i] == '/' && (i - start > 0) ){
31868       /* only mkdir if leaf dir != "." or "/" or ".." */
31869       if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/') 
31870          || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
31871         buf[i]='\0';
31872         if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
31873           int err=errno;
31874           if( err!=EEXIST ) {
31875             OSTRACE(("CREATELOCKPATH  FAILED creating %s, "
31876                      "'%s' proxy lock path=%s pid=%d\n",
31877                      buf, strerror(err), lockPath, osGetpid(0)));
31878             return err;
31879           }
31880         }
31881       }
31882       start=i+1;
31883     }
31884     buf[i] = lockPath[i];
31885   }
31886   OSTRACE(("CREATELOCKPATH  proxy lock path=%s pid=%d\n", lockPath, osGetpid(0)));
31887   return 0;
31888 }
31889
31890 /*
31891 ** Create a new VFS file descriptor (stored in memory obtained from
31892 ** sqlite3_malloc) and open the file named "path" in the file descriptor.
31893 **
31894 ** The caller is responsible not only for closing the file descriptor
31895 ** but also for freeing the memory associated with the file descriptor.
31896 */
31897 static int proxyCreateUnixFile(
31898     const char *path,        /* path for the new unixFile */
31899     unixFile **ppFile,       /* unixFile created and returned by ref */
31900     int islockfile           /* if non zero missing dirs will be created */
31901 ) {
31902   int fd = -1;
31903   unixFile *pNew;
31904   int rc = SQLITE_OK;
31905   int openFlags = O_RDWR | O_CREAT;
31906   sqlite3_vfs dummyVfs;
31907   int terrno = 0;
31908   UnixUnusedFd *pUnused = NULL;
31909
31910   /* 1. first try to open/create the file
31911   ** 2. if that fails, and this is a lock file (not-conch), try creating
31912   ** the parent directories and then try again.
31913   ** 3. if that fails, try to open the file read-only
31914   ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
31915   */
31916   pUnused = findReusableFd(path, openFlags);
31917   if( pUnused ){
31918     fd = pUnused->fd;
31919   }else{
31920     pUnused = sqlite3_malloc(sizeof(*pUnused));
31921     if( !pUnused ){
31922       return SQLITE_NOMEM;
31923     }
31924   }
31925   if( fd<0 ){
31926     fd = robust_open(path, openFlags, 0);
31927     terrno = errno;
31928     if( fd<0 && errno==ENOENT && islockfile ){
31929       if( proxyCreateLockPath(path) == SQLITE_OK ){
31930         fd = robust_open(path, openFlags, 0);
31931       }
31932     }
31933   }
31934   if( fd<0 ){
31935     openFlags = O_RDONLY;
31936     fd = robust_open(path, openFlags, 0);
31937     terrno = errno;
31938   }
31939   if( fd<0 ){
31940     if( islockfile ){
31941       return SQLITE_BUSY;
31942     }
31943     switch (terrno) {
31944       case EACCES:
31945         return SQLITE_PERM;
31946       case EIO: 
31947         return SQLITE_IOERR_LOCK; /* even though it is the conch */
31948       default:
31949         return SQLITE_CANTOPEN_BKPT;
31950     }
31951   }
31952   
31953   pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
31954   if( pNew==NULL ){
31955     rc = SQLITE_NOMEM;
31956     goto end_create_proxy;
31957   }
31958   memset(pNew, 0, sizeof(unixFile));
31959   pNew->openFlags = openFlags;
31960   memset(&dummyVfs, 0, sizeof(dummyVfs));
31961   dummyVfs.pAppData = (void*)&autolockIoFinder;
31962   dummyVfs.zName = "dummy";
31963   pUnused->fd = fd;
31964   pUnused->flags = openFlags;
31965   pNew->pUnused = pUnused;
31966   
31967   rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
31968   if( rc==SQLITE_OK ){
31969     *ppFile = pNew;
31970     return SQLITE_OK;
31971   }
31972 end_create_proxy:    
31973   robust_close(pNew, fd, __LINE__);
31974   sqlite3_free(pNew);
31975   sqlite3_free(pUnused);
31976   return rc;
31977 }
31978
31979 #ifdef SQLITE_TEST
31980 /* simulate multiple hosts by creating unique hostid file paths */
31981 SQLITE_API int sqlite3_hostid_num = 0;
31982 #endif
31983
31984 #define PROXY_HOSTIDLEN    16  /* conch file host id length */
31985
31986 /* Not always defined in the headers as it ought to be */
31987 extern int gethostuuid(uuid_t id, const struct timespec *wait);
31988
31989 /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN 
31990 ** bytes of writable memory.
31991 */
31992 static int proxyGetHostID(unsigned char *pHostID, int *pError){
31993   assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
31994   memset(pHostID, 0, PROXY_HOSTIDLEN);
31995 # if defined(__APPLE__) && ((__MAC_OS_X_VERSION_MIN_REQUIRED > 1050) || \
31996                             (__IPHONE_OS_VERSION_MIN_REQUIRED > 2000))
31997   {
31998     struct timespec timeout = {1, 0}; /* 1 sec timeout */
31999     if( gethostuuid(pHostID, &timeout) ){
32000       int err = errno;
32001       if( pError ){
32002         *pError = err;
32003       }
32004       return SQLITE_IOERR;
32005     }
32006   }
32007 #else
32008   UNUSED_PARAMETER(pError);
32009 #endif
32010 #ifdef SQLITE_TEST
32011   /* simulate multiple hosts by creating unique hostid file paths */
32012   if( sqlite3_hostid_num != 0){
32013     pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
32014   }
32015 #endif
32016   
32017   return SQLITE_OK;
32018 }
32019
32020 /* The conch file contains the header, host id and lock file path
32021  */
32022 #define PROXY_CONCHVERSION 2   /* 1-byte header, 16-byte host id, path */
32023 #define PROXY_HEADERLEN    1   /* conch file header length */
32024 #define PROXY_PATHINDEX    (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
32025 #define PROXY_MAXCONCHLEN  (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
32026
32027 /* 
32028 ** Takes an open conch file, copies the contents to a new path and then moves 
32029 ** it back.  The newly created file's file descriptor is assigned to the
32030 ** conch file structure and finally the original conch file descriptor is 
32031 ** closed.  Returns zero if successful.
32032 */
32033 static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
32034   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
32035   unixFile *conchFile = pCtx->conchFile;
32036   char tPath[MAXPATHLEN];
32037   char buf[PROXY_MAXCONCHLEN];
32038   char *cPath = pCtx->conchFilePath;
32039   size_t readLen = 0;
32040   size_t pathLen = 0;
32041   char errmsg[64] = "";
32042   int fd = -1;
32043   int rc = -1;
32044   UNUSED_PARAMETER(myHostID);
32045
32046   /* create a new path by replace the trailing '-conch' with '-break' */
32047   pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
32048   if( pathLen>MAXPATHLEN || pathLen<6 || 
32049      (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
32050     sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
32051     goto end_breaklock;
32052   }
32053   /* read the conch content */
32054   readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
32055   if( readLen<PROXY_PATHINDEX ){
32056     sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
32057     goto end_breaklock;
32058   }
32059   /* write it out to the temporary break file */
32060   fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
32061   if( fd<0 ){
32062     sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
32063     goto end_breaklock;
32064   }
32065   if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
32066     sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
32067     goto end_breaklock;
32068   }
32069   if( rename(tPath, cPath) ){
32070     sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
32071     goto end_breaklock;
32072   }
32073   rc = 0;
32074   fprintf(stderr, "broke stale lock on %s\n", cPath);
32075   robust_close(pFile, conchFile->h, __LINE__);
32076   conchFile->h = fd;
32077   conchFile->openFlags = O_RDWR | O_CREAT;
32078
32079 end_breaklock:
32080   if( rc ){
32081     if( fd>=0 ){
32082       osUnlink(tPath);
32083       robust_close(pFile, fd, __LINE__);
32084     }
32085     fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
32086   }
32087   return rc;
32088 }
32089
32090 /* Take the requested lock on the conch file and break a stale lock if the 
32091 ** host id matches.
32092 */
32093 static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
32094   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
32095   unixFile *conchFile = pCtx->conchFile;
32096   int rc = SQLITE_OK;
32097   int nTries = 0;
32098   struct timespec conchModTime;
32099   
32100   memset(&conchModTime, 0, sizeof(conchModTime));
32101   do {
32102     rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
32103     nTries ++;
32104     if( rc==SQLITE_BUSY ){
32105       /* If the lock failed (busy):
32106        * 1st try: get the mod time of the conch, wait 0.5s and try again. 
32107        * 2nd try: fail if the mod time changed or host id is different, wait 
32108        *           10 sec and try again
32109        * 3rd try: break the lock unless the mod time has changed.
32110        */
32111       struct stat buf;
32112       if( osFstat(conchFile->h, &buf) ){
32113         storeLastErrno(pFile, errno);
32114         return SQLITE_IOERR_LOCK;
32115       }
32116       
32117       if( nTries==1 ){
32118         conchModTime = buf.st_mtimespec;
32119         usleep(500000); /* wait 0.5 sec and try the lock again*/
32120         continue;  
32121       }
32122
32123       assert( nTries>1 );
32124       if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec || 
32125          conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
32126         return SQLITE_BUSY;
32127       }
32128       
32129       if( nTries==2 ){  
32130         char tBuf[PROXY_MAXCONCHLEN];
32131         int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
32132         if( len<0 ){
32133           storeLastErrno(pFile, errno);
32134           return SQLITE_IOERR_LOCK;
32135         }
32136         if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
32137           /* don't break the lock if the host id doesn't match */
32138           if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
32139             return SQLITE_BUSY;
32140           }
32141         }else{
32142           /* don't break the lock on short read or a version mismatch */
32143           return SQLITE_BUSY;
32144         }
32145         usleep(10000000); /* wait 10 sec and try the lock again */
32146         continue; 
32147       }
32148       
32149       assert( nTries==3 );
32150       if( 0==proxyBreakConchLock(pFile, myHostID) ){
32151         rc = SQLITE_OK;
32152         if( lockType==EXCLUSIVE_LOCK ){
32153           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
32154         }
32155         if( !rc ){
32156           rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
32157         }
32158       }
32159     }
32160   } while( rc==SQLITE_BUSY && nTries<3 );
32161   
32162   return rc;
32163 }
32164
32165 /* Takes the conch by taking a shared lock and read the contents conch, if 
32166 ** lockPath is non-NULL, the host ID and lock file path must match.  A NULL 
32167 ** lockPath means that the lockPath in the conch file will be used if the 
32168 ** host IDs match, or a new lock path will be generated automatically 
32169 ** and written to the conch file.
32170 */
32171 static int proxyTakeConch(unixFile *pFile){
32172   proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext; 
32173   
32174   if( pCtx->conchHeld!=0 ){
32175     return SQLITE_OK;
32176   }else{
32177     unixFile *conchFile = pCtx->conchFile;
32178     uuid_t myHostID;
32179     int pError = 0;
32180     char readBuf[PROXY_MAXCONCHLEN];
32181     char lockPath[MAXPATHLEN];
32182     char *tempLockPath = NULL;
32183     int rc = SQLITE_OK;
32184     int createConch = 0;
32185     int hostIdMatch = 0;
32186     int readLen = 0;
32187     int tryOldLockPath = 0;
32188     int forceNewLockPath = 0;
32189     
32190     OSTRACE(("TAKECONCH  %d for %s pid=%d\n", conchFile->h,
32191              (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
32192              osGetpid(0)));
32193
32194     rc = proxyGetHostID(myHostID, &pError);
32195     if( (rc&0xff)==SQLITE_IOERR ){
32196       storeLastErrno(pFile, pError);
32197       goto end_takeconch;
32198     }
32199     rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
32200     if( rc!=SQLITE_OK ){
32201       goto end_takeconch;
32202     }
32203     /* read the existing conch file */
32204     readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
32205     if( readLen<0 ){
32206       /* I/O error: lastErrno set by seekAndRead */
32207       storeLastErrno(pFile, conchFile->lastErrno);
32208       rc = SQLITE_IOERR_READ;
32209       goto end_takeconch;
32210     }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) || 
32211              readBuf[0]!=(char)PROXY_CONCHVERSION ){
32212       /* a short read or version format mismatch means we need to create a new 
32213       ** conch file. 
32214       */
32215       createConch = 1;
32216     }
32217     /* if the host id matches and the lock path already exists in the conch
32218     ** we'll try to use the path there, if we can't open that path, we'll 
32219     ** retry with a new auto-generated path 
32220     */
32221     do { /* in case we need to try again for an :auto: named lock file */
32222
32223       if( !createConch && !forceNewLockPath ){
32224         hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID, 
32225                                   PROXY_HOSTIDLEN);
32226         /* if the conch has data compare the contents */
32227         if( !pCtx->lockProxyPath ){
32228           /* for auto-named local lock file, just check the host ID and we'll
32229            ** use the local lock file path that's already in there
32230            */
32231           if( hostIdMatch ){
32232             size_t pathLen = (readLen - PROXY_PATHINDEX);
32233             
32234             if( pathLen>=MAXPATHLEN ){
32235               pathLen=MAXPATHLEN-1;
32236             }
32237             memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
32238             lockPath[pathLen] = 0;
32239             tempLockPath = lockPath;
32240             tryOldLockPath = 1;
32241             /* create a copy of the lock path if the conch is taken */
32242             goto end_takeconch;
32243           }
32244         }else if( hostIdMatch
32245                && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
32246                            readLen-PROXY_PATHINDEX)
32247         ){
32248           /* conch host and lock path match */
32249           goto end_takeconch; 
32250         }
32251       }
32252       
32253       /* if the conch isn't writable and doesn't match, we can't take it */
32254       if( (conchFile->openFlags&O_RDWR) == 0 ){
32255         rc = SQLITE_BUSY;
32256         goto end_takeconch;
32257       }
32258       
32259       /* either the conch didn't match or we need to create a new one */
32260       if( !pCtx->lockProxyPath ){
32261         proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
32262         tempLockPath = lockPath;
32263         /* create a copy of the lock path _only_ if the conch is taken */
32264       }
32265       
32266       /* update conch with host and path (this will fail if other process
32267       ** has a shared lock already), if the host id matches, use the big
32268       ** stick.
32269       */
32270       futimes(conchFile->h, NULL);
32271       if( hostIdMatch && !createConch ){
32272         if( conchFile->pInode && conchFile->pInode->nShared>1 ){
32273           /* We are trying for an exclusive lock but another thread in this
32274            ** same process is still holding a shared lock. */
32275           rc = SQLITE_BUSY;
32276         } else {          
32277           rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
32278         }
32279       }else{
32280         rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
32281       }
32282       if( rc==SQLITE_OK ){
32283         char writeBuffer[PROXY_MAXCONCHLEN];
32284         int writeSize = 0;
32285         
32286         writeBuffer[0] = (char)PROXY_CONCHVERSION;
32287         memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
32288         if( pCtx->lockProxyPath!=NULL ){
32289           strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath,
32290                   MAXPATHLEN);
32291         }else{
32292           strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
32293         }
32294         writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
32295         robust_ftruncate(conchFile->h, writeSize);
32296         rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
32297         fsync(conchFile->h);
32298         /* If we created a new conch file (not just updated the contents of a 
32299          ** valid conch file), try to match the permissions of the database 
32300          */
32301         if( rc==SQLITE_OK && createConch ){
32302           struct stat buf;
32303           int err = osFstat(pFile->h, &buf);
32304           if( err==0 ){
32305             mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
32306                                         S_IROTH|S_IWOTH);
32307             /* try to match the database file R/W permissions, ignore failure */
32308 #ifndef SQLITE_PROXY_DEBUG
32309             osFchmod(conchFile->h, cmode);
32310 #else
32311             do{
32312               rc = osFchmod(conchFile->h, cmode);
32313             }while( rc==(-1) && errno==EINTR );
32314             if( rc!=0 ){
32315               int code = errno;
32316               fprintf(stderr, "fchmod %o FAILED with %d %s\n",
32317                       cmode, code, strerror(code));
32318             } else {
32319               fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
32320             }
32321           }else{
32322             int code = errno;
32323             fprintf(stderr, "STAT FAILED[%d] with %d %s\n", 
32324                     err, code, strerror(code));
32325 #endif
32326           }
32327         }
32328       }
32329       conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
32330       
32331     end_takeconch:
32332       OSTRACE(("TRANSPROXY: CLOSE  %d\n", pFile->h));
32333       if( rc==SQLITE_OK && pFile->openFlags ){
32334         int fd;
32335         if( pFile->h>=0 ){
32336           robust_close(pFile, pFile->h, __LINE__);
32337         }
32338         pFile->h = -1;
32339         fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
32340         OSTRACE(("TRANSPROXY: OPEN  %d\n", fd));
32341         if( fd>=0 ){
32342           pFile->h = fd;
32343         }else{
32344           rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
32345            during locking */
32346         }
32347       }
32348       if( rc==SQLITE_OK && !pCtx->lockProxy ){
32349         char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
32350         rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
32351         if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
32352           /* we couldn't create the proxy lock file with the old lock file path
32353            ** so try again via auto-naming 
32354            */
32355           forceNewLockPath = 1;
32356           tryOldLockPath = 0;
32357           continue; /* go back to the do {} while start point, try again */
32358         }
32359       }
32360       if( rc==SQLITE_OK ){
32361         /* Need to make a copy of path if we extracted the value
32362          ** from the conch file or the path was allocated on the stack
32363          */
32364         if( tempLockPath ){
32365           pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
32366           if( !pCtx->lockProxyPath ){
32367             rc = SQLITE_NOMEM;
32368           }
32369         }
32370       }
32371       if( rc==SQLITE_OK ){
32372         pCtx->conchHeld = 1;
32373         
32374         if( pCtx->lockProxy->pMethod == &afpIoMethods ){
32375           afpLockingContext *afpCtx;
32376           afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
32377           afpCtx->dbPath = pCtx->lockProxyPath;
32378         }
32379       } else {
32380         conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
32381       }
32382       OSTRACE(("TAKECONCH  %d %s\n", conchFile->h,
32383                rc==SQLITE_OK?"ok":"failed"));
32384       return rc;
32385     } while (1); /* in case we need to retry the :auto: lock file - 
32386                  ** we should never get here except via the 'continue' call. */
32387   }
32388 }
32389
32390 /*
32391 ** If pFile holds a lock on a conch file, then release that lock.
32392 */
32393 static int proxyReleaseConch(unixFile *pFile){
32394   int rc = SQLITE_OK;         /* Subroutine return code */
32395   proxyLockingContext *pCtx;  /* The locking context for the proxy lock */
32396   unixFile *conchFile;        /* Name of the conch file */
32397
32398   pCtx = (proxyLockingContext *)pFile->lockingContext;
32399   conchFile = pCtx->conchFile;
32400   OSTRACE(("RELEASECONCH  %d for %s pid=%d\n", conchFile->h,
32401            (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), 
32402            osGetpid(0)));
32403   if( pCtx->conchHeld>0 ){
32404     rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
32405   }
32406   pCtx->conchHeld = 0;
32407   OSTRACE(("RELEASECONCH  %d %s\n", conchFile->h,
32408            (rc==SQLITE_OK ? "ok" : "failed")));
32409   return rc;
32410 }
32411
32412 /*
32413 ** Given the name of a database file, compute the name of its conch file.
32414 ** Store the conch filename in memory obtained from sqlite3_malloc().
32415 ** Make *pConchPath point to the new name.  Return SQLITE_OK on success
32416 ** or SQLITE_NOMEM if unable to obtain memory.
32417 **
32418 ** The caller is responsible for ensuring that the allocated memory
32419 ** space is eventually freed.
32420 **
32421 ** *pConchPath is set to NULL if a memory allocation error occurs.
32422 */
32423 static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
32424   int i;                        /* Loop counter */
32425   int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
32426   char *conchPath;              /* buffer in which to construct conch name */
32427
32428   /* Allocate space for the conch filename and initialize the name to
32429   ** the name of the original database file. */  
32430   *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
32431   if( conchPath==0 ){
32432     return SQLITE_NOMEM;
32433   }
32434   memcpy(conchPath, dbPath, len+1);
32435   
32436   /* now insert a "." before the last / character */
32437   for( i=(len-1); i>=0; i-- ){
32438     if( conchPath[i]=='/' ){
32439       i++;
32440       break;
32441     }
32442   }
32443   conchPath[i]='.';
32444   while ( i<len ){
32445     conchPath[i+1]=dbPath[i];
32446     i++;
32447   }
32448
32449   /* append the "-conch" suffix to the file */
32450   memcpy(&conchPath[i+1], "-conch", 7);
32451   assert( (int)strlen(conchPath) == len+7 );
32452
32453   return SQLITE_OK;
32454 }
32455
32456
32457 /* Takes a fully configured proxy locking-style unix file and switches
32458 ** the local lock file path 
32459 */
32460 static int switchLockProxyPath(unixFile *pFile, const char *path) {
32461   proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
32462   char *oldPath = pCtx->lockProxyPath;
32463   int rc = SQLITE_OK;
32464
32465   if( pFile->eFileLock!=NO_LOCK ){
32466     return SQLITE_BUSY;
32467   }  
32468
32469   /* nothing to do if the path is NULL, :auto: or matches the existing path */
32470   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
32471     (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
32472     return SQLITE_OK;
32473   }else{
32474     unixFile *lockProxy = pCtx->lockProxy;
32475     pCtx->lockProxy=NULL;
32476     pCtx->conchHeld = 0;
32477     if( lockProxy!=NULL ){
32478       rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
32479       if( rc ) return rc;
32480       sqlite3_free(lockProxy);
32481     }
32482     sqlite3_free(oldPath);
32483     pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
32484   }
32485   
32486   return rc;
32487 }
32488
32489 /*
32490 ** pFile is a file that has been opened by a prior xOpen call.  dbPath
32491 ** is a string buffer at least MAXPATHLEN+1 characters in size.
32492 **
32493 ** This routine find the filename associated with pFile and writes it
32494 ** int dbPath.
32495 */
32496 static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
32497 #if defined(__APPLE__)
32498   if( pFile->pMethod == &afpIoMethods ){
32499     /* afp style keeps a reference to the db path in the filePath field 
32500     ** of the struct */
32501     assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
32502     strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath,
32503             MAXPATHLEN);
32504   } else
32505 #endif
32506   if( pFile->pMethod == &dotlockIoMethods ){
32507     /* dot lock style uses the locking context to store the dot lock
32508     ** file path */
32509     int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
32510     memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
32511   }else{
32512     /* all other styles use the locking context to store the db file path */
32513     assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
32514     strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
32515   }
32516   return SQLITE_OK;
32517 }
32518
32519 /*
32520 ** Takes an already filled in unix file and alters it so all file locking 
32521 ** will be performed on the local proxy lock file.  The following fields
32522 ** are preserved in the locking context so that they can be restored and 
32523 ** the unix structure properly cleaned up at close time:
32524 **  ->lockingContext
32525 **  ->pMethod
32526 */
32527 static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
32528   proxyLockingContext *pCtx;
32529   char dbPath[MAXPATHLEN+1];       /* Name of the database file */
32530   char *lockPath=NULL;
32531   int rc = SQLITE_OK;
32532   
32533   if( pFile->eFileLock!=NO_LOCK ){
32534     return SQLITE_BUSY;
32535   }
32536   proxyGetDbPathForUnixFile(pFile, dbPath);
32537   if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
32538     lockPath=NULL;
32539   }else{
32540     lockPath=(char *)path;
32541   }
32542   
32543   OSTRACE(("TRANSPROXY  %d for %s pid=%d\n", pFile->h,
32544            (lockPath ? lockPath : ":auto:"), osGetpid(0)));
32545
32546   pCtx = sqlite3_malloc( sizeof(*pCtx) );
32547   if( pCtx==0 ){
32548     return SQLITE_NOMEM;
32549   }
32550   memset(pCtx, 0, sizeof(*pCtx));
32551
32552   rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
32553   if( rc==SQLITE_OK ){
32554     rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
32555     if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
32556       /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
32557       ** (c) the file system is read-only, then enable no-locking access.
32558       ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
32559       ** that openFlags will have only one of O_RDONLY or O_RDWR.
32560       */
32561       struct statfs fsInfo;
32562       struct stat conchInfo;
32563       int goLockless = 0;
32564
32565       if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
32566         int err = errno;
32567         if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
32568           goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
32569         }
32570       }
32571       if( goLockless ){
32572         pCtx->conchHeld = -1; /* read only FS/ lockless */
32573         rc = SQLITE_OK;
32574       }
32575     }
32576   }  
32577   if( rc==SQLITE_OK && lockPath ){
32578     pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
32579   }
32580
32581   if( rc==SQLITE_OK ){
32582     pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
32583     if( pCtx->dbPath==NULL ){
32584       rc = SQLITE_NOMEM;
32585     }
32586   }
32587   if( rc==SQLITE_OK ){
32588     /* all memory is allocated, proxys are created and assigned, 
32589     ** switch the locking context and pMethod then return.
32590     */
32591     pCtx->oldLockingContext = pFile->lockingContext;
32592     pFile->lockingContext = pCtx;
32593     pCtx->pOldMethod = pFile->pMethod;
32594     pFile->pMethod = &proxyIoMethods;
32595   }else{
32596     if( pCtx->conchFile ){ 
32597       pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
32598       sqlite3_free(pCtx->conchFile);
32599     }
32600     sqlite3DbFree(0, pCtx->lockProxyPath);
32601     sqlite3_free(pCtx->conchFilePath); 
32602     sqlite3_free(pCtx);
32603   }
32604   OSTRACE(("TRANSPROXY  %d %s\n", pFile->h,
32605            (rc==SQLITE_OK ? "ok" : "failed")));
32606   return rc;
32607 }
32608
32609
32610 /*
32611 ** This routine handles sqlite3_file_control() calls that are specific
32612 ** to proxy locking.
32613 */
32614 static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
32615   switch( op ){
32616     case SQLITE_FCNTL_GET_LOCKPROXYFILE: {
32617       unixFile *pFile = (unixFile*)id;
32618       if( pFile->pMethod == &proxyIoMethods ){
32619         proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
32620         proxyTakeConch(pFile);
32621         if( pCtx->lockProxyPath ){
32622           *(const char **)pArg = pCtx->lockProxyPath;
32623         }else{
32624           *(const char **)pArg = ":auto: (not held)";
32625         }
32626       } else {
32627         *(const char **)pArg = NULL;
32628       }
32629       return SQLITE_OK;
32630     }
32631     case SQLITE_FCNTL_SET_LOCKPROXYFILE: {
32632       unixFile *pFile = (unixFile*)id;
32633       int rc = SQLITE_OK;
32634       int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
32635       if( pArg==NULL || (const char *)pArg==0 ){
32636         if( isProxyStyle ){
32637           /* turn off proxy locking - not supported.  If support is added for
32638           ** switching proxy locking mode off then it will need to fail if
32639           ** the journal mode is WAL mode. 
32640           */
32641           rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
32642         }else{
32643           /* turn off proxy locking - already off - NOOP */
32644           rc = SQLITE_OK;
32645         }
32646       }else{
32647         const char *proxyPath = (const char *)pArg;
32648         if( isProxyStyle ){
32649           proxyLockingContext *pCtx = 
32650             (proxyLockingContext*)pFile->lockingContext;
32651           if( !strcmp(pArg, ":auto:") 
32652            || (pCtx->lockProxyPath &&
32653                !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
32654           ){
32655             rc = SQLITE_OK;
32656           }else{
32657             rc = switchLockProxyPath(pFile, proxyPath);
32658           }
32659         }else{
32660           /* turn on proxy file locking */
32661           rc = proxyTransformUnixFile(pFile, proxyPath);
32662         }
32663       }
32664       return rc;
32665     }
32666     default: {
32667       assert( 0 );  /* The call assures that only valid opcodes are sent */
32668     }
32669   }
32670   /*NOTREACHED*/
32671   return SQLITE_ERROR;
32672 }
32673
32674 /*
32675 ** Within this division (the proxying locking implementation) the procedures
32676 ** above this point are all utilities.  The lock-related methods of the
32677 ** proxy-locking sqlite3_io_method object follow.
32678 */
32679
32680
32681 /*
32682 ** This routine checks if there is a RESERVED lock held on the specified
32683 ** file by this or any other process. If such a lock is held, set *pResOut
32684 ** to a non-zero value otherwise *pResOut is set to zero.  The return value
32685 ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
32686 */
32687 static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
32688   unixFile *pFile = (unixFile*)id;
32689   int rc = proxyTakeConch(pFile);
32690   if( rc==SQLITE_OK ){
32691     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32692     if( pCtx->conchHeld>0 ){
32693       unixFile *proxy = pCtx->lockProxy;
32694       return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
32695     }else{ /* conchHeld < 0 is lockless */
32696       pResOut=0;
32697     }
32698   }
32699   return rc;
32700 }
32701
32702 /*
32703 ** Lock the file with the lock specified by parameter eFileLock - one
32704 ** of the following:
32705 **
32706 **     (1) SHARED_LOCK
32707 **     (2) RESERVED_LOCK
32708 **     (3) PENDING_LOCK
32709 **     (4) EXCLUSIVE_LOCK
32710 **
32711 ** Sometimes when requesting one lock state, additional lock states
32712 ** are inserted in between.  The locking might fail on one of the later
32713 ** transitions leaving the lock state different from what it started but
32714 ** still short of its goal.  The following chart shows the allowed
32715 ** transitions and the inserted intermediate states:
32716 **
32717 **    UNLOCKED -> SHARED
32718 **    SHARED -> RESERVED
32719 **    SHARED -> (PENDING) -> EXCLUSIVE
32720 **    RESERVED -> (PENDING) -> EXCLUSIVE
32721 **    PENDING -> EXCLUSIVE
32722 **
32723 ** This routine will only increase a lock.  Use the sqlite3OsUnlock()
32724 ** routine to lower a locking level.
32725 */
32726 static int proxyLock(sqlite3_file *id, int eFileLock) {
32727   unixFile *pFile = (unixFile*)id;
32728   int rc = proxyTakeConch(pFile);
32729   if( rc==SQLITE_OK ){
32730     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32731     if( pCtx->conchHeld>0 ){
32732       unixFile *proxy = pCtx->lockProxy;
32733       rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
32734       pFile->eFileLock = proxy->eFileLock;
32735     }else{
32736       /* conchHeld < 0 is lockless */
32737     }
32738   }
32739   return rc;
32740 }
32741
32742
32743 /*
32744 ** Lower the locking level on file descriptor pFile to eFileLock.  eFileLock
32745 ** must be either NO_LOCK or SHARED_LOCK.
32746 **
32747 ** If the locking level of the file descriptor is already at or below
32748 ** the requested locking level, this routine is a no-op.
32749 */
32750 static int proxyUnlock(sqlite3_file *id, int eFileLock) {
32751   unixFile *pFile = (unixFile*)id;
32752   int rc = proxyTakeConch(pFile);
32753   if( rc==SQLITE_OK ){
32754     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32755     if( pCtx->conchHeld>0 ){
32756       unixFile *proxy = pCtx->lockProxy;
32757       rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
32758       pFile->eFileLock = proxy->eFileLock;
32759     }else{
32760       /* conchHeld < 0 is lockless */
32761     }
32762   }
32763   return rc;
32764 }
32765
32766 /*
32767 ** Close a file that uses proxy locks.
32768 */
32769 static int proxyClose(sqlite3_file *id) {
32770   if( id ){
32771     unixFile *pFile = (unixFile*)id;
32772     proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
32773     unixFile *lockProxy = pCtx->lockProxy;
32774     unixFile *conchFile = pCtx->conchFile;
32775     int rc = SQLITE_OK;
32776     
32777     if( lockProxy ){
32778       rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
32779       if( rc ) return rc;
32780       rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
32781       if( rc ) return rc;
32782       sqlite3_free(lockProxy);
32783       pCtx->lockProxy = 0;
32784     }
32785     if( conchFile ){
32786       if( pCtx->conchHeld ){
32787         rc = proxyReleaseConch(pFile);
32788         if( rc ) return rc;
32789       }
32790       rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
32791       if( rc ) return rc;
32792       sqlite3_free(conchFile);
32793     }
32794     sqlite3DbFree(0, pCtx->lockProxyPath);
32795     sqlite3_free(pCtx->conchFilePath);
32796     sqlite3DbFree(0, pCtx->dbPath);
32797     /* restore the original locking context and pMethod then close it */
32798     pFile->lockingContext = pCtx->oldLockingContext;
32799     pFile->pMethod = pCtx->pOldMethod;
32800     sqlite3_free(pCtx);
32801     return pFile->pMethod->xClose(id);
32802   }
32803   return SQLITE_OK;
32804 }
32805
32806
32807
32808 #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
32809 /*
32810 ** The proxy locking style is intended for use with AFP filesystems.
32811 ** And since AFP is only supported on MacOSX, the proxy locking is also
32812 ** restricted to MacOSX.
32813 ** 
32814 **
32815 ******************* End of the proxy lock implementation **********************
32816 ******************************************************************************/
32817
32818 /*
32819 ** Initialize the operating system interface.
32820 **
32821 ** This routine registers all VFS implementations for unix-like operating
32822 ** systems.  This routine, and the sqlite3_os_end() routine that follows,
32823 ** should be the only routines in this file that are visible from other
32824 ** files.
32825 **
32826 ** This routine is called once during SQLite initialization and by a
32827 ** single thread.  The memory allocation and mutex subsystems have not
32828 ** necessarily been initialized when this routine is called, and so they
32829 ** should not be used.
32830 */
32831 SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void){ 
32832   /* 
32833   ** The following macro defines an initializer for an sqlite3_vfs object.
32834   ** The name of the VFS is NAME.  The pAppData is a pointer to a pointer
32835   ** to the "finder" function.  (pAppData is a pointer to a pointer because
32836   ** silly C90 rules prohibit a void* from being cast to a function pointer
32837   ** and so we have to go through the intermediate pointer to avoid problems
32838   ** when compiling with -pedantic-errors on GCC.)
32839   **
32840   ** The FINDER parameter to this macro is the name of the pointer to the
32841   ** finder-function.  The finder-function returns a pointer to the
32842   ** sqlite_io_methods object that implements the desired locking
32843   ** behaviors.  See the division above that contains the IOMETHODS
32844   ** macro for addition information on finder-functions.
32845   **
32846   ** Most finders simply return a pointer to a fixed sqlite3_io_methods
32847   ** object.  But the "autolockIoFinder" available on MacOSX does a little
32848   ** more than that; it looks at the filesystem type that hosts the 
32849   ** database file and tries to choose an locking method appropriate for
32850   ** that filesystem time.
32851   */
32852   #define UNIXVFS(VFSNAME, FINDER) {                        \
32853     3,                    /* iVersion */                    \
32854     sizeof(unixFile),     /* szOsFile */                    \
32855     MAX_PATHNAME,         /* mxPathname */                  \
32856     0,                    /* pNext */                       \
32857     VFSNAME,              /* zName */                       \
32858     (void*)&FINDER,       /* pAppData */                    \
32859     unixOpen,             /* xOpen */                       \
32860     unixDelete,           /* xDelete */                     \
32861     unixAccess,           /* xAccess */                     \
32862     unixFullPathname,     /* xFullPathname */               \
32863     unixDlOpen,           /* xDlOpen */                     \
32864     unixDlError,          /* xDlError */                    \
32865     unixDlSym,            /* xDlSym */                      \
32866     unixDlClose,          /* xDlClose */                    \
32867     unixRandomness,       /* xRandomness */                 \
32868     unixSleep,            /* xSleep */                      \
32869     unixCurrentTime,      /* xCurrentTime */                \
32870     unixGetLastError,     /* xGetLastError */               \
32871     unixCurrentTimeInt64, /* xCurrentTimeInt64 */           \
32872     unixSetSystemCall,    /* xSetSystemCall */              \
32873     unixGetSystemCall,    /* xGetSystemCall */              \
32874     unixNextSystemCall,   /* xNextSystemCall */             \
32875   }
32876
32877   /*
32878   ** All default VFSes for unix are contained in the following array.
32879   **
32880   ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
32881   ** by the SQLite core when the VFS is registered.  So the following
32882   ** array cannot be const.
32883   */
32884   static sqlite3_vfs aVfs[] = {
32885 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
32886     UNIXVFS("unix",          autolockIoFinder ),
32887 #elif OS_VXWORKS
32888     UNIXVFS("unix",          vxworksIoFinder ),
32889 #else
32890     UNIXVFS("unix",          posixIoFinder ),
32891 #endif
32892     UNIXVFS("unix-none",     nolockIoFinder ),
32893     UNIXVFS("unix-dotfile",  dotlockIoFinder ),
32894     UNIXVFS("unix-excl",     posixIoFinder ),
32895 #if OS_VXWORKS
32896     UNIXVFS("unix-namedsem", semIoFinder ),
32897 #endif
32898 #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
32899     UNIXVFS("unix-posix",    posixIoFinder ),
32900 #endif
32901 #if SQLITE_ENABLE_LOCKING_STYLE
32902     UNIXVFS("unix-flock",    flockIoFinder ),
32903 #endif
32904 #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
32905     UNIXVFS("unix-afp",      afpIoFinder ),
32906     UNIXVFS("unix-nfs",      nfsIoFinder ),
32907     UNIXVFS("unix-proxy",    proxyIoFinder ),
32908 #endif
32909   };
32910   unsigned int i;          /* Loop counter */
32911
32912   /* Double-check that the aSyscall[] array has been constructed
32913   ** correctly.  See ticket [bb3a86e890c8e96ab] */
32914   assert( ArraySize(aSyscall)==25 );
32915
32916   /* Register all VFSes defined in the aVfs[] array */
32917   for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
32918     sqlite3_vfs_register(&aVfs[i], i==0);
32919   }
32920   return SQLITE_OK; 
32921 }
32922
32923 /*
32924 ** Shutdown the operating system interface.
32925 **
32926 ** Some operating systems might need to do some cleanup in this routine,
32927 ** to release dynamically allocated objects.  But not on unix.
32928 ** This routine is a no-op for unix.
32929 */
32930 SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void){ 
32931   return SQLITE_OK; 
32932 }
32933  
32934 #endif /* SQLITE_OS_UNIX */
32935
32936 /************** End of os_unix.c *********************************************/
32937 /************** Begin file os_win.c ******************************************/
32938 /*
32939 ** 2004 May 22
32940 **
32941 ** The author disclaims copyright to this source code.  In place of
32942 ** a legal notice, here is a blessing:
32943 **
32944 **    May you do good and not evil.
32945 **    May you find forgiveness for yourself and forgive others.
32946 **    May you share freely, never taking more than you give.
32947 **
32948 ******************************************************************************
32949 **
32950 ** This file contains code that is specific to Windows.
32951 */
32952 #if SQLITE_OS_WIN               /* This file is used for Windows only */
32953
32954 /*
32955 ** Include code that is common to all os_*.c files
32956 */
32957 /************** Include os_common.h in the middle of os_win.c ****************/
32958 /************** Begin file os_common.h ***************************************/
32959 /*
32960 ** 2004 May 22
32961 **
32962 ** The author disclaims copyright to this source code.  In place of
32963 ** a legal notice, here is a blessing:
32964 **
32965 **    May you do good and not evil.
32966 **    May you find forgiveness for yourself and forgive others.
32967 **    May you share freely, never taking more than you give.
32968 **
32969 ******************************************************************************
32970 **
32971 ** This file contains macros and a little bit of code that is common to
32972 ** all of the platform-specific files (os_*.c) and is #included into those
32973 ** files.
32974 **
32975 ** This file should be #included by the os_*.c files only.  It is not a
32976 ** general purpose header file.
32977 */
32978 #ifndef _OS_COMMON_H_
32979 #define _OS_COMMON_H_
32980
32981 /*
32982 ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
32983 ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
32984 ** switch.  The following code should catch this problem at compile-time.
32985 */
32986 #ifdef MEMORY_DEBUG
32987 # error "The MEMORY_DEBUG macro is obsolete.  Use SQLITE_DEBUG instead."
32988 #endif
32989
32990 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
32991 # ifndef SQLITE_DEBUG_OS_TRACE
32992 #   define SQLITE_DEBUG_OS_TRACE 0
32993 # endif
32994   int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
32995 # define OSTRACE(X)          if( sqlite3OSTrace ) sqlite3DebugPrintf X
32996 #else
32997 # define OSTRACE(X)
32998 #endif
32999
33000 /*
33001 ** Macros for performance tracing.  Normally turned off.  Only works
33002 ** on i486 hardware.
33003 */
33004 #ifdef SQLITE_PERFORMANCE_TRACE
33005
33006 /* 
33007 ** hwtime.h contains inline assembler code for implementing 
33008 ** high-performance timing routines.
33009 */
33010 /************** Include hwtime.h in the middle of os_common.h ****************/
33011 /************** Begin file hwtime.h ******************************************/
33012 /*
33013 ** 2008 May 27
33014 **
33015 ** The author disclaims copyright to this source code.  In place of
33016 ** a legal notice, here is a blessing:
33017 **
33018 **    May you do good and not evil.
33019 **    May you find forgiveness for yourself and forgive others.
33020 **    May you share freely, never taking more than you give.
33021 **
33022 ******************************************************************************
33023 **
33024 ** This file contains inline asm code for retrieving "high-performance"
33025 ** counters for x86 class CPUs.
33026 */
33027 #ifndef _HWTIME_H_
33028 #define _HWTIME_H_
33029
33030 /*
33031 ** The following routine only works on pentium-class (or newer) processors.
33032 ** It uses the RDTSC opcode to read the cycle count value out of the
33033 ** processor and returns that value.  This can be used for high-res
33034 ** profiling.
33035 */
33036 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
33037       (defined(i386) || defined(__i386__) || defined(_M_IX86))
33038
33039   #if defined(__GNUC__)
33040
33041   __inline__ sqlite_uint64 sqlite3Hwtime(void){
33042      unsigned int lo, hi;
33043      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
33044      return (sqlite_uint64)hi << 32 | lo;
33045   }
33046
33047   #elif defined(_MSC_VER)
33048
33049   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
33050      __asm {
33051         rdtsc
33052         ret       ; return value at EDX:EAX
33053      }
33054   }
33055
33056   #endif
33057
33058 #elif (defined(__GNUC__) && defined(__x86_64__))
33059
33060   __inline__ sqlite_uint64 sqlite3Hwtime(void){
33061       unsigned long val;
33062       __asm__ __volatile__ ("rdtsc" : "=A" (val));
33063       return val;
33064   }
33065  
33066 #elif (defined(__GNUC__) && defined(__ppc__))
33067
33068   __inline__ sqlite_uint64 sqlite3Hwtime(void){
33069       unsigned long long retval;
33070       unsigned long junk;
33071       __asm__ __volatile__ ("\n\
33072           1:      mftbu   %1\n\
33073                   mftb    %L0\n\
33074                   mftbu   %0\n\
33075                   cmpw    %0,%1\n\
33076                   bne     1b"
33077                   : "=r" (retval), "=r" (junk));
33078       return retval;
33079   }
33080
33081 #else
33082
33083   #error Need implementation of sqlite3Hwtime() for your platform.
33084
33085   /*
33086   ** To compile without implementing sqlite3Hwtime() for your platform,
33087   ** you can remove the above #error and use the following
33088   ** stub function.  You will lose timing support for many
33089   ** of the debugging and testing utilities, but it should at
33090   ** least compile and run.
33091   */
33092 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
33093
33094 #endif
33095
33096 #endif /* !defined(_HWTIME_H_) */
33097
33098 /************** End of hwtime.h **********************************************/
33099 /************** Continuing where we left off in os_common.h ******************/
33100
33101 static sqlite_uint64 g_start;
33102 static sqlite_uint64 g_elapsed;
33103 #define TIMER_START       g_start=sqlite3Hwtime()
33104 #define TIMER_END         g_elapsed=sqlite3Hwtime()-g_start
33105 #define TIMER_ELAPSED     g_elapsed
33106 #else
33107 #define TIMER_START
33108 #define TIMER_END
33109 #define TIMER_ELAPSED     ((sqlite_uint64)0)
33110 #endif
33111
33112 /*
33113 ** If we compile with the SQLITE_TEST macro set, then the following block
33114 ** of code will give us the ability to simulate a disk I/O error.  This
33115 ** is used for testing the I/O recovery logic.
33116 */
33117 #ifdef SQLITE_TEST
33118 SQLITE_API int sqlite3_io_error_hit = 0;            /* Total number of I/O Errors */
33119 SQLITE_API int sqlite3_io_error_hardhit = 0;        /* Number of non-benign errors */
33120 SQLITE_API int sqlite3_io_error_pending = 0;        /* Count down to first I/O error */
33121 SQLITE_API int sqlite3_io_error_persist = 0;        /* True if I/O errors persist */
33122 SQLITE_API int sqlite3_io_error_benign = 0;         /* True if errors are benign */
33123 SQLITE_API int sqlite3_diskfull_pending = 0;
33124 SQLITE_API int sqlite3_diskfull = 0;
33125 #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
33126 #define SimulateIOError(CODE)  \
33127   if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
33128        || sqlite3_io_error_pending-- == 1 )  \
33129               { local_ioerr(); CODE; }
33130 static void local_ioerr(){
33131   IOTRACE(("IOERR\n"));
33132   sqlite3_io_error_hit++;
33133   if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
33134 }
33135 #define SimulateDiskfullError(CODE) \
33136    if( sqlite3_diskfull_pending ){ \
33137      if( sqlite3_diskfull_pending == 1 ){ \
33138        local_ioerr(); \
33139        sqlite3_diskfull = 1; \
33140        sqlite3_io_error_hit = 1; \
33141        CODE; \
33142      }else{ \
33143        sqlite3_diskfull_pending--; \
33144      } \
33145    }
33146 #else
33147 #define SimulateIOErrorBenign(X)
33148 #define SimulateIOError(A)
33149 #define SimulateDiskfullError(A)
33150 #endif
33151
33152 /*
33153 ** When testing, keep a count of the number of open files.
33154 */
33155 #ifdef SQLITE_TEST
33156 SQLITE_API int sqlite3_open_file_count = 0;
33157 #define OpenCounter(X)  sqlite3_open_file_count+=(X)
33158 #else
33159 #define OpenCounter(X)
33160 #endif
33161
33162 #endif /* !defined(_OS_COMMON_H_) */
33163
33164 /************** End of os_common.h *******************************************/
33165 /************** Continuing where we left off in os_win.c *********************/
33166
33167 /*
33168 ** Include the header file for the Windows VFS.
33169 */
33170
33171 /*
33172 ** Compiling and using WAL mode requires several APIs that are only
33173 ** available in Windows platforms based on the NT kernel.
33174 */
33175 #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
33176 #  error "WAL mode requires support from the Windows NT kernel, compile\
33177  with SQLITE_OMIT_WAL."
33178 #endif
33179
33180 #if !SQLITE_OS_WINNT && SQLITE_MAX_MMAP_SIZE>0
33181 #  error "Memory mapped files require support from the Windows NT kernel,\
33182  compile with SQLITE_MAX_MMAP_SIZE=0."
33183 #endif
33184
33185 /*
33186 ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
33187 ** based on the sub-platform)?
33188 */
33189 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
33190 #  define SQLITE_WIN32_HAS_ANSI
33191 #endif
33192
33193 /*
33194 ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
33195 ** based on the sub-platform)?
33196 */
33197 #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
33198     !defined(SQLITE_WIN32_NO_WIDE)
33199 #  define SQLITE_WIN32_HAS_WIDE
33200 #endif
33201
33202 /*
33203 ** Make sure at least one set of Win32 APIs is available.
33204 */
33205 #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
33206 #  error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
33207  must be defined."
33208 #endif
33209
33210 /*
33211 ** Define the required Windows SDK version constants if they are not
33212 ** already available.
33213 */
33214 #ifndef NTDDI_WIN8
33215 #  define NTDDI_WIN8                        0x06020000
33216 #endif
33217
33218 #ifndef NTDDI_WINBLUE
33219 #  define NTDDI_WINBLUE                     0x06030000
33220 #endif
33221
33222 /*
33223 ** Check to see if the GetVersionEx[AW] functions are deprecated on the
33224 ** target system.  GetVersionEx was first deprecated in Win8.1.
33225 */
33226 #ifndef SQLITE_WIN32_GETVERSIONEX
33227 #  if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
33228 #    define SQLITE_WIN32_GETVERSIONEX   0   /* GetVersionEx() is deprecated */
33229 #  else
33230 #    define SQLITE_WIN32_GETVERSIONEX   1   /* GetVersionEx() is current */
33231 #  endif
33232 #endif
33233
33234 /*
33235 ** This constant should already be defined (in the "WinDef.h" SDK file).
33236 */
33237 #ifndef MAX_PATH
33238 #  define MAX_PATH                      (260)
33239 #endif
33240
33241 /*
33242 ** Maximum pathname length (in chars) for Win32.  This should normally be
33243 ** MAX_PATH.
33244 */
33245 #ifndef SQLITE_WIN32_MAX_PATH_CHARS
33246 #  define SQLITE_WIN32_MAX_PATH_CHARS   (MAX_PATH)
33247 #endif
33248
33249 /*
33250 ** This constant should already be defined (in the "WinNT.h" SDK file).
33251 */
33252 #ifndef UNICODE_STRING_MAX_CHARS
33253 #  define UNICODE_STRING_MAX_CHARS      (32767)
33254 #endif
33255
33256 /*
33257 ** Maximum pathname length (in chars) for WinNT.  This should normally be
33258 ** UNICODE_STRING_MAX_CHARS.
33259 */
33260 #ifndef SQLITE_WINNT_MAX_PATH_CHARS
33261 #  define SQLITE_WINNT_MAX_PATH_CHARS   (UNICODE_STRING_MAX_CHARS)
33262 #endif
33263
33264 /*
33265 ** Maximum pathname length (in bytes) for Win32.  The MAX_PATH macro is in
33266 ** characters, so we allocate 4 bytes per character assuming worst-case of
33267 ** 4-bytes-per-character for UTF8.
33268 */
33269 #ifndef SQLITE_WIN32_MAX_PATH_BYTES
33270 #  define SQLITE_WIN32_MAX_PATH_BYTES   (SQLITE_WIN32_MAX_PATH_CHARS*4)
33271 #endif
33272
33273 /*
33274 ** Maximum pathname length (in bytes) for WinNT.  This should normally be
33275 ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
33276 */
33277 #ifndef SQLITE_WINNT_MAX_PATH_BYTES
33278 #  define SQLITE_WINNT_MAX_PATH_BYTES   \
33279                             (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
33280 #endif
33281
33282 /*
33283 ** Maximum error message length (in chars) for WinRT.
33284 */
33285 #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
33286 #  define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
33287 #endif
33288
33289 /*
33290 ** Returns non-zero if the character should be treated as a directory
33291 ** separator.
33292 */
33293 #ifndef winIsDirSep
33294 #  define winIsDirSep(a)                (((a) == '/') || ((a) == '\\'))
33295 #endif
33296
33297 /*
33298 ** This macro is used when a local variable is set to a value that is
33299 ** [sometimes] not used by the code (e.g. via conditional compilation).
33300 */
33301 #ifndef UNUSED_VARIABLE_VALUE
33302 #  define UNUSED_VARIABLE_VALUE(x)      (void)(x)
33303 #endif
33304
33305 /*
33306 ** Returns the character that should be used as the directory separator.
33307 */
33308 #ifndef winGetDirSep
33309 #  define winGetDirSep()                '\\'
33310 #endif
33311
33312 /*
33313 ** Do we need to manually define the Win32 file mapping APIs for use with WAL
33314 ** mode or memory mapped files (e.g. these APIs are available in the Windows
33315 ** CE SDK; however, they are not present in the header file)?
33316 */
33317 #if SQLITE_WIN32_FILEMAPPING_API && \
33318         (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
33319 /*
33320 ** Two of the file mapping APIs are different under WinRT.  Figure out which
33321 ** set we need.
33322 */
33323 #if SQLITE_OS_WINRT
33324 WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
33325         LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
33326
33327 WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
33328 #else
33329 #if defined(SQLITE_WIN32_HAS_ANSI)
33330 WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
33331         DWORD, DWORD, DWORD, LPCSTR);
33332 #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
33333
33334 #if defined(SQLITE_WIN32_HAS_WIDE)
33335 WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
33336         DWORD, DWORD, DWORD, LPCWSTR);
33337 #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
33338
33339 WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
33340 #endif /* SQLITE_OS_WINRT */
33341
33342 /*
33343 ** These file mapping APIs are common to both Win32 and WinRT.
33344 */
33345
33346 WINBASEAPI BOOL WINAPI FlushViewOfFile(LPCVOID, SIZE_T);
33347 WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
33348 #endif /* SQLITE_WIN32_FILEMAPPING_API */
33349
33350 /*
33351 ** Some Microsoft compilers lack this definition.
33352 */
33353 #ifndef INVALID_FILE_ATTRIBUTES
33354 # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
33355 #endif
33356
33357 #ifndef FILE_FLAG_MASK
33358 # define FILE_FLAG_MASK          (0xFF3C0000)
33359 #endif
33360
33361 #ifndef FILE_ATTRIBUTE_MASK
33362 # define FILE_ATTRIBUTE_MASK     (0x0003FFF7)
33363 #endif
33364
33365 #ifndef SQLITE_OMIT_WAL
33366 /* Forward references to structures used for WAL */
33367 typedef struct winShm winShm;           /* A connection to shared-memory */
33368 typedef struct winShmNode winShmNode;   /* A region of shared-memory */
33369 #endif
33370
33371 /*
33372 ** WinCE lacks native support for file locking so we have to fake it
33373 ** with some code of our own.
33374 */
33375 #if SQLITE_OS_WINCE
33376 typedef struct winceLock {
33377   int nReaders;       /* Number of reader locks obtained */
33378   BOOL bPending;      /* Indicates a pending lock has been obtained */
33379   BOOL bReserved;     /* Indicates a reserved lock has been obtained */
33380   BOOL bExclusive;    /* Indicates an exclusive lock has been obtained */
33381 } winceLock;
33382 #endif
33383
33384 /*
33385 ** The winFile structure is a subclass of sqlite3_file* specific to the win32
33386 ** portability layer.
33387 */
33388 typedef struct winFile winFile;
33389 struct winFile {
33390   const sqlite3_io_methods *pMethod; /*** Must be first ***/
33391   sqlite3_vfs *pVfs;      /* The VFS used to open this file */
33392   HANDLE h;               /* Handle for accessing the file */
33393   u8 locktype;            /* Type of lock currently held on this file */
33394   short sharedLockByte;   /* Randomly chosen byte used as a shared lock */
33395   u8 ctrlFlags;           /* Flags.  See WINFILE_* below */
33396   DWORD lastErrno;        /* The Windows errno from the last I/O error */
33397 #ifndef SQLITE_OMIT_WAL
33398   winShm *pShm;           /* Instance of shared memory on this file */
33399 #endif
33400   const char *zPath;      /* Full pathname of this file */
33401   int szChunk;            /* Chunk size configured by FCNTL_CHUNK_SIZE */
33402 #if SQLITE_OS_WINCE
33403   LPWSTR zDeleteOnClose;  /* Name of file to delete when closing */
33404   HANDLE hMutex;          /* Mutex used to control access to shared lock */
33405   HANDLE hShared;         /* Shared memory segment used for locking */
33406   winceLock local;        /* Locks obtained by this instance of winFile */
33407   winceLock *shared;      /* Global shared lock memory for the file  */
33408 #endif
33409 #if SQLITE_MAX_MMAP_SIZE>0
33410   int nFetchOut;                /* Number of outstanding xFetch references */
33411   HANDLE hMap;                  /* Handle for accessing memory mapping */
33412   void *pMapRegion;             /* Area memory mapped */
33413   sqlite3_int64 mmapSize;       /* Usable size of mapped region */
33414   sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
33415   sqlite3_int64 mmapSizeMax;    /* Configured FCNTL_MMAP_SIZE value */
33416 #endif
33417 };
33418
33419 /*
33420 ** Allowed values for winFile.ctrlFlags
33421 */
33422 #define WINFILE_RDONLY          0x02   /* Connection is read only */
33423 #define WINFILE_PERSIST_WAL     0x04   /* Persistent WAL mode */
33424 #define WINFILE_PSOW            0x10   /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
33425
33426 /*
33427  * The size of the buffer used by sqlite3_win32_write_debug().
33428  */
33429 #ifndef SQLITE_WIN32_DBG_BUF_SIZE
33430 #  define SQLITE_WIN32_DBG_BUF_SIZE   ((int)(4096-sizeof(DWORD)))
33431 #endif
33432
33433 /*
33434  * The value used with sqlite3_win32_set_directory() to specify that
33435  * the data directory should be changed.
33436  */
33437 #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
33438 #  define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
33439 #endif
33440
33441 /*
33442  * The value used with sqlite3_win32_set_directory() to specify that
33443  * the temporary directory should be changed.
33444  */
33445 #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
33446 #  define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
33447 #endif
33448
33449 /*
33450  * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
33451  * various Win32 API heap functions instead of our own.
33452  */
33453 #ifdef SQLITE_WIN32_MALLOC
33454
33455 /*
33456  * If this is non-zero, an isolated heap will be created by the native Win32
33457  * allocator subsystem; otherwise, the default process heap will be used.  This
33458  * setting has no effect when compiling for WinRT.  By default, this is enabled
33459  * and an isolated heap will be created to store all allocated data.
33460  *
33461  ******************************************************************************
33462  * WARNING: It is important to note that when this setting is non-zero and the
33463  *          winMemShutdown function is called (e.g. by the sqlite3_shutdown
33464  *          function), all data that was allocated using the isolated heap will
33465  *          be freed immediately and any attempt to access any of that freed
33466  *          data will almost certainly result in an immediate access violation.
33467  ******************************************************************************
33468  */
33469 #ifndef SQLITE_WIN32_HEAP_CREATE
33470 #  define SQLITE_WIN32_HEAP_CREATE    (TRUE)
33471 #endif
33472
33473 /*
33474  * The initial size of the Win32-specific heap.  This value may be zero.
33475  */
33476 #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
33477 #  define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
33478                                        (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
33479 #endif
33480
33481 /*
33482  * The maximum size of the Win32-specific heap.  This value may be zero.
33483  */
33484 #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
33485 #  define SQLITE_WIN32_HEAP_MAX_SIZE  (0)
33486 #endif
33487
33488 /*
33489  * The extra flags to use in calls to the Win32 heap APIs.  This value may be
33490  * zero for the default behavior.
33491  */
33492 #ifndef SQLITE_WIN32_HEAP_FLAGS
33493 #  define SQLITE_WIN32_HEAP_FLAGS     (0)
33494 #endif
33495
33496
33497 /*
33498 ** The winMemData structure stores information required by the Win32-specific
33499 ** sqlite3_mem_methods implementation.
33500 */
33501 typedef struct winMemData winMemData;
33502 struct winMemData {
33503 #ifndef NDEBUG
33504   u32 magic1;   /* Magic number to detect structure corruption. */
33505 #endif
33506   HANDLE hHeap; /* The handle to our heap. */
33507   BOOL bOwned;  /* Do we own the heap (i.e. destroy it on shutdown)? */
33508 #ifndef NDEBUG
33509   u32 magic2;   /* Magic number to detect structure corruption. */
33510 #endif
33511 };
33512
33513 #ifndef NDEBUG
33514 #define WINMEM_MAGIC1     0x42b2830b
33515 #define WINMEM_MAGIC2     0xbd4d7cf4
33516 #endif
33517
33518 static struct winMemData win_mem_data = {
33519 #ifndef NDEBUG
33520   WINMEM_MAGIC1,
33521 #endif
33522   NULL, FALSE
33523 #ifndef NDEBUG
33524   ,WINMEM_MAGIC2
33525 #endif
33526 };
33527
33528 #ifndef NDEBUG
33529 #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
33530 #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
33531 #define winMemAssertMagic()  winMemAssertMagic1(); winMemAssertMagic2();
33532 #else
33533 #define winMemAssertMagic()
33534 #endif
33535
33536 #define winMemGetDataPtr()  &win_mem_data
33537 #define winMemGetHeap()     win_mem_data.hHeap
33538 #define winMemGetOwned()    win_mem_data.bOwned
33539
33540 static void *winMemMalloc(int nBytes);
33541 static void winMemFree(void *pPrior);
33542 static void *winMemRealloc(void *pPrior, int nBytes);
33543 static int winMemSize(void *p);
33544 static int winMemRoundup(int n);
33545 static int winMemInit(void *pAppData);
33546 static void winMemShutdown(void *pAppData);
33547
33548 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
33549 #endif /* SQLITE_WIN32_MALLOC */
33550
33551 /*
33552 ** The following variable is (normally) set once and never changes
33553 ** thereafter.  It records whether the operating system is Win9x
33554 ** or WinNT.
33555 **
33556 ** 0:   Operating system unknown.
33557 ** 1:   Operating system is Win9x.
33558 ** 2:   Operating system is WinNT.
33559 **
33560 ** In order to facilitate testing on a WinNT system, the test fixture
33561 ** can manually set this value to 1 to emulate Win98 behavior.
33562 */
33563 #ifdef SQLITE_TEST
33564 SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
33565 #else
33566 static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
33567 #endif
33568
33569 #ifndef SYSCALL
33570 #  define SYSCALL sqlite3_syscall_ptr
33571 #endif
33572
33573 /*
33574 ** This function is not available on Windows CE or WinRT.
33575  */
33576
33577 #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
33578 #  define osAreFileApisANSI()       1
33579 #endif
33580
33581 /*
33582 ** Many system calls are accessed through pointer-to-functions so that
33583 ** they may be overridden at runtime to facilitate fault injection during
33584 ** testing and sandboxing.  The following array holds the names and pointers
33585 ** to all overrideable system calls.
33586 */
33587 static struct win_syscall {
33588   const char *zName;            /* Name of the system call */
33589   sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
33590   sqlite3_syscall_ptr pDefault; /* Default value */
33591 } aSyscall[] = {
33592 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
33593   { "AreFileApisANSI",         (SYSCALL)AreFileApisANSI,         0 },
33594 #else
33595   { "AreFileApisANSI",         (SYSCALL)0,                       0 },
33596 #endif
33597
33598 #ifndef osAreFileApisANSI
33599 #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
33600 #endif
33601
33602 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
33603   { "CharLowerW",              (SYSCALL)CharLowerW,              0 },
33604 #else
33605   { "CharLowerW",              (SYSCALL)0,                       0 },
33606 #endif
33607
33608 #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
33609
33610 #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
33611   { "CharUpperW",              (SYSCALL)CharUpperW,              0 },
33612 #else
33613   { "CharUpperW",              (SYSCALL)0,                       0 },
33614 #endif
33615
33616 #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
33617
33618   { "CloseHandle",             (SYSCALL)CloseHandle,             0 },
33619
33620 #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
33621
33622 #if defined(SQLITE_WIN32_HAS_ANSI)
33623   { "CreateFileA",             (SYSCALL)CreateFileA,             0 },
33624 #else
33625   { "CreateFileA",             (SYSCALL)0,                       0 },
33626 #endif
33627
33628 #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
33629         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
33630
33631 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33632   { "CreateFileW",             (SYSCALL)CreateFileW,             0 },
33633 #else
33634   { "CreateFileW",             (SYSCALL)0,                       0 },
33635 #endif
33636
33637 #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
33638         LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
33639
33640 #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
33641         (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
33642   { "CreateFileMappingA",      (SYSCALL)CreateFileMappingA,      0 },
33643 #else
33644   { "CreateFileMappingA",      (SYSCALL)0,                       0 },
33645 #endif
33646
33647 #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
33648         DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
33649
33650 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
33651         (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
33652   { "CreateFileMappingW",      (SYSCALL)CreateFileMappingW,      0 },
33653 #else
33654   { "CreateFileMappingW",      (SYSCALL)0,                       0 },
33655 #endif
33656
33657 #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
33658         DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
33659
33660 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33661   { "CreateMutexW",            (SYSCALL)CreateMutexW,            0 },
33662 #else
33663   { "CreateMutexW",            (SYSCALL)0,                       0 },
33664 #endif
33665
33666 #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
33667         LPCWSTR))aSyscall[8].pCurrent)
33668
33669 #if defined(SQLITE_WIN32_HAS_ANSI)
33670   { "DeleteFileA",             (SYSCALL)DeleteFileA,             0 },
33671 #else
33672   { "DeleteFileA",             (SYSCALL)0,                       0 },
33673 #endif
33674
33675 #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
33676
33677 #if defined(SQLITE_WIN32_HAS_WIDE)
33678   { "DeleteFileW",             (SYSCALL)DeleteFileW,             0 },
33679 #else
33680   { "DeleteFileW",             (SYSCALL)0,                       0 },
33681 #endif
33682
33683 #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
33684
33685 #if SQLITE_OS_WINCE
33686   { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
33687 #else
33688   { "FileTimeToLocalFileTime", (SYSCALL)0,                       0 },
33689 #endif
33690
33691 #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
33692         LPFILETIME))aSyscall[11].pCurrent)
33693
33694 #if SQLITE_OS_WINCE
33695   { "FileTimeToSystemTime",    (SYSCALL)FileTimeToSystemTime,    0 },
33696 #else
33697   { "FileTimeToSystemTime",    (SYSCALL)0,                       0 },
33698 #endif
33699
33700 #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
33701         LPSYSTEMTIME))aSyscall[12].pCurrent)
33702
33703   { "FlushFileBuffers",        (SYSCALL)FlushFileBuffers,        0 },
33704
33705 #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
33706
33707 #if defined(SQLITE_WIN32_HAS_ANSI)
33708   { "FormatMessageA",          (SYSCALL)FormatMessageA,          0 },
33709 #else
33710   { "FormatMessageA",          (SYSCALL)0,                       0 },
33711 #endif
33712
33713 #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
33714         DWORD,va_list*))aSyscall[14].pCurrent)
33715
33716 #if defined(SQLITE_WIN32_HAS_WIDE)
33717   { "FormatMessageW",          (SYSCALL)FormatMessageW,          0 },
33718 #else
33719   { "FormatMessageW",          (SYSCALL)0,                       0 },
33720 #endif
33721
33722 #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
33723         DWORD,va_list*))aSyscall[15].pCurrent)
33724
33725 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
33726   { "FreeLibrary",             (SYSCALL)FreeLibrary,             0 },
33727 #else
33728   { "FreeLibrary",             (SYSCALL)0,                       0 },
33729 #endif
33730
33731 #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
33732
33733   { "GetCurrentProcessId",     (SYSCALL)GetCurrentProcessId,     0 },
33734
33735 #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
33736
33737 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
33738   { "GetDiskFreeSpaceA",       (SYSCALL)GetDiskFreeSpaceA,       0 },
33739 #else
33740   { "GetDiskFreeSpaceA",       (SYSCALL)0,                       0 },
33741 #endif
33742
33743 #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
33744         LPDWORD))aSyscall[18].pCurrent)
33745
33746 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33747   { "GetDiskFreeSpaceW",       (SYSCALL)GetDiskFreeSpaceW,       0 },
33748 #else
33749   { "GetDiskFreeSpaceW",       (SYSCALL)0,                       0 },
33750 #endif
33751
33752 #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
33753         LPDWORD))aSyscall[19].pCurrent)
33754
33755 #if defined(SQLITE_WIN32_HAS_ANSI)
33756   { "GetFileAttributesA",      (SYSCALL)GetFileAttributesA,      0 },
33757 #else
33758   { "GetFileAttributesA",      (SYSCALL)0,                       0 },
33759 #endif
33760
33761 #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
33762
33763 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33764   { "GetFileAttributesW",      (SYSCALL)GetFileAttributesW,      0 },
33765 #else
33766   { "GetFileAttributesW",      (SYSCALL)0,                       0 },
33767 #endif
33768
33769 #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
33770
33771 #if defined(SQLITE_WIN32_HAS_WIDE)
33772   { "GetFileAttributesExW",    (SYSCALL)GetFileAttributesExW,    0 },
33773 #else
33774   { "GetFileAttributesExW",    (SYSCALL)0,                       0 },
33775 #endif
33776
33777 #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
33778         LPVOID))aSyscall[22].pCurrent)
33779
33780 #if !SQLITE_OS_WINRT
33781   { "GetFileSize",             (SYSCALL)GetFileSize,             0 },
33782 #else
33783   { "GetFileSize",             (SYSCALL)0,                       0 },
33784 #endif
33785
33786 #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
33787
33788 #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
33789   { "GetFullPathNameA",        (SYSCALL)GetFullPathNameA,        0 },
33790 #else
33791   { "GetFullPathNameA",        (SYSCALL)0,                       0 },
33792 #endif
33793
33794 #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
33795         LPSTR*))aSyscall[24].pCurrent)
33796
33797 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33798   { "GetFullPathNameW",        (SYSCALL)GetFullPathNameW,        0 },
33799 #else
33800   { "GetFullPathNameW",        (SYSCALL)0,                       0 },
33801 #endif
33802
33803 #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
33804         LPWSTR*))aSyscall[25].pCurrent)
33805
33806   { "GetLastError",            (SYSCALL)GetLastError,            0 },
33807
33808 #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
33809
33810 #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
33811 #if SQLITE_OS_WINCE
33812   /* The GetProcAddressA() routine is only available on Windows CE. */
33813   { "GetProcAddressA",         (SYSCALL)GetProcAddressA,         0 },
33814 #else
33815   /* All other Windows platforms expect GetProcAddress() to take
33816   ** an ANSI string regardless of the _UNICODE setting */
33817   { "GetProcAddressA",         (SYSCALL)GetProcAddress,          0 },
33818 #endif
33819 #else
33820   { "GetProcAddressA",         (SYSCALL)0,                       0 },
33821 #endif
33822
33823 #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
33824         LPCSTR))aSyscall[27].pCurrent)
33825
33826 #if !SQLITE_OS_WINRT
33827   { "GetSystemInfo",           (SYSCALL)GetSystemInfo,           0 },
33828 #else
33829   { "GetSystemInfo",           (SYSCALL)0,                       0 },
33830 #endif
33831
33832 #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
33833
33834   { "GetSystemTime",           (SYSCALL)GetSystemTime,           0 },
33835
33836 #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
33837
33838 #if !SQLITE_OS_WINCE
33839   { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
33840 #else
33841   { "GetSystemTimeAsFileTime", (SYSCALL)0,                       0 },
33842 #endif
33843
33844 #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
33845         LPFILETIME))aSyscall[30].pCurrent)
33846
33847 #if defined(SQLITE_WIN32_HAS_ANSI)
33848   { "GetTempPathA",            (SYSCALL)GetTempPathA,            0 },
33849 #else
33850   { "GetTempPathA",            (SYSCALL)0,                       0 },
33851 #endif
33852
33853 #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
33854
33855 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
33856   { "GetTempPathW",            (SYSCALL)GetTempPathW,            0 },
33857 #else
33858   { "GetTempPathW",            (SYSCALL)0,                       0 },
33859 #endif
33860
33861 #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
33862
33863 #if !SQLITE_OS_WINRT
33864   { "GetTickCount",            (SYSCALL)GetTickCount,            0 },
33865 #else
33866   { "GetTickCount",            (SYSCALL)0,                       0 },
33867 #endif
33868
33869 #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
33870
33871 #if defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_GETVERSIONEX) && \
33872         SQLITE_WIN32_GETVERSIONEX
33873   { "GetVersionExA",           (SYSCALL)GetVersionExA,           0 },
33874 #else
33875   { "GetVersionExA",           (SYSCALL)0,                       0 },
33876 #endif
33877
33878 #define osGetVersionExA ((BOOL(WINAPI*)( \
33879         LPOSVERSIONINFOA))aSyscall[34].pCurrent)
33880
33881 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
33882         defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
33883   { "GetVersionExW",           (SYSCALL)GetVersionExW,           0 },
33884 #else
33885   { "GetVersionExW",           (SYSCALL)0,                       0 },
33886 #endif
33887
33888 #define osGetVersionExW ((BOOL(WINAPI*)( \
33889         LPOSVERSIONINFOW))aSyscall[35].pCurrent)
33890
33891   { "HeapAlloc",               (SYSCALL)HeapAlloc,               0 },
33892
33893 #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
33894         SIZE_T))aSyscall[36].pCurrent)
33895
33896 #if !SQLITE_OS_WINRT
33897   { "HeapCreate",              (SYSCALL)HeapCreate,              0 },
33898 #else
33899   { "HeapCreate",              (SYSCALL)0,                       0 },
33900 #endif
33901
33902 #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
33903         SIZE_T))aSyscall[37].pCurrent)
33904
33905 #if !SQLITE_OS_WINRT
33906   { "HeapDestroy",             (SYSCALL)HeapDestroy,             0 },
33907 #else
33908   { "HeapDestroy",             (SYSCALL)0,                       0 },
33909 #endif
33910
33911 #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
33912
33913   { "HeapFree",                (SYSCALL)HeapFree,                0 },
33914
33915 #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
33916
33917   { "HeapReAlloc",             (SYSCALL)HeapReAlloc,             0 },
33918
33919 #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
33920         SIZE_T))aSyscall[40].pCurrent)
33921
33922   { "HeapSize",                (SYSCALL)HeapSize,                0 },
33923
33924 #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
33925         LPCVOID))aSyscall[41].pCurrent)
33926
33927 #if !SQLITE_OS_WINRT
33928   { "HeapValidate",            (SYSCALL)HeapValidate,            0 },
33929 #else
33930   { "HeapValidate",            (SYSCALL)0,                       0 },
33931 #endif
33932
33933 #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
33934         LPCVOID))aSyscall[42].pCurrent)
33935
33936 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
33937   { "HeapCompact",             (SYSCALL)HeapCompact,             0 },
33938 #else
33939   { "HeapCompact",             (SYSCALL)0,                       0 },
33940 #endif
33941
33942 #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
33943
33944 #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
33945   { "LoadLibraryA",            (SYSCALL)LoadLibraryA,            0 },
33946 #else
33947   { "LoadLibraryA",            (SYSCALL)0,                       0 },
33948 #endif
33949
33950 #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
33951
33952 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
33953         !defined(SQLITE_OMIT_LOAD_EXTENSION)
33954   { "LoadLibraryW",            (SYSCALL)LoadLibraryW,            0 },
33955 #else
33956   { "LoadLibraryW",            (SYSCALL)0,                       0 },
33957 #endif
33958
33959 #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
33960
33961 #if !SQLITE_OS_WINRT
33962   { "LocalFree",               (SYSCALL)LocalFree,               0 },
33963 #else
33964   { "LocalFree",               (SYSCALL)0,                       0 },
33965 #endif
33966
33967 #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
33968
33969 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
33970   { "LockFile",                (SYSCALL)LockFile,                0 },
33971 #else
33972   { "LockFile",                (SYSCALL)0,                       0 },
33973 #endif
33974
33975 #ifndef osLockFile
33976 #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
33977         DWORD))aSyscall[47].pCurrent)
33978 #endif
33979
33980 #if !SQLITE_OS_WINCE
33981   { "LockFileEx",              (SYSCALL)LockFileEx,              0 },
33982 #else
33983   { "LockFileEx",              (SYSCALL)0,                       0 },
33984 #endif
33985
33986 #ifndef osLockFileEx
33987 #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
33988         LPOVERLAPPED))aSyscall[48].pCurrent)
33989 #endif
33990
33991 #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && \
33992         (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0))
33993   { "MapViewOfFile",           (SYSCALL)MapViewOfFile,           0 },
33994 #else
33995   { "MapViewOfFile",           (SYSCALL)0,                       0 },
33996 #endif
33997
33998 #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
33999         SIZE_T))aSyscall[49].pCurrent)
34000
34001   { "MultiByteToWideChar",     (SYSCALL)MultiByteToWideChar,     0 },
34002
34003 #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
34004         int))aSyscall[50].pCurrent)
34005
34006   { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
34007
34008 #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
34009         LARGE_INTEGER*))aSyscall[51].pCurrent)
34010
34011   { "ReadFile",                (SYSCALL)ReadFile,                0 },
34012
34013 #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
34014         LPOVERLAPPED))aSyscall[52].pCurrent)
34015
34016   { "SetEndOfFile",            (SYSCALL)SetEndOfFile,            0 },
34017
34018 #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
34019
34020 #if !SQLITE_OS_WINRT
34021   { "SetFilePointer",          (SYSCALL)SetFilePointer,          0 },
34022 #else
34023   { "SetFilePointer",          (SYSCALL)0,                       0 },
34024 #endif
34025
34026 #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
34027         DWORD))aSyscall[54].pCurrent)
34028
34029 #if !SQLITE_OS_WINRT
34030   { "Sleep",                   (SYSCALL)Sleep,                   0 },
34031 #else
34032   { "Sleep",                   (SYSCALL)0,                       0 },
34033 #endif
34034
34035 #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
34036
34037   { "SystemTimeToFileTime",    (SYSCALL)SystemTimeToFileTime,    0 },
34038
34039 #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
34040         LPFILETIME))aSyscall[56].pCurrent)
34041
34042 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
34043   { "UnlockFile",              (SYSCALL)UnlockFile,              0 },
34044 #else
34045   { "UnlockFile",              (SYSCALL)0,                       0 },
34046 #endif
34047
34048 #ifndef osUnlockFile
34049 #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
34050         DWORD))aSyscall[57].pCurrent)
34051 #endif
34052
34053 #if !SQLITE_OS_WINCE
34054   { "UnlockFileEx",            (SYSCALL)UnlockFileEx,            0 },
34055 #else
34056   { "UnlockFileEx",            (SYSCALL)0,                       0 },
34057 #endif
34058
34059 #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
34060         LPOVERLAPPED))aSyscall[58].pCurrent)
34061
34062 #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
34063   { "UnmapViewOfFile",         (SYSCALL)UnmapViewOfFile,         0 },
34064 #else
34065   { "UnmapViewOfFile",         (SYSCALL)0,                       0 },
34066 #endif
34067
34068 #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
34069
34070   { "WideCharToMultiByte",     (SYSCALL)WideCharToMultiByte,     0 },
34071
34072 #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
34073         LPCSTR,LPBOOL))aSyscall[60].pCurrent)
34074
34075   { "WriteFile",               (SYSCALL)WriteFile,               0 },
34076
34077 #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
34078         LPOVERLAPPED))aSyscall[61].pCurrent)
34079
34080 #if SQLITE_OS_WINRT
34081   { "CreateEventExW",          (SYSCALL)CreateEventExW,          0 },
34082 #else
34083   { "CreateEventExW",          (SYSCALL)0,                       0 },
34084 #endif
34085
34086 #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
34087         DWORD,DWORD))aSyscall[62].pCurrent)
34088
34089 #if !SQLITE_OS_WINRT
34090   { "WaitForSingleObject",     (SYSCALL)WaitForSingleObject,     0 },
34091 #else
34092   { "WaitForSingleObject",     (SYSCALL)0,                       0 },
34093 #endif
34094
34095 #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
34096         DWORD))aSyscall[63].pCurrent)
34097
34098 #if !SQLITE_OS_WINCE
34099   { "WaitForSingleObjectEx",   (SYSCALL)WaitForSingleObjectEx,   0 },
34100 #else
34101   { "WaitForSingleObjectEx",   (SYSCALL)0,                       0 },
34102 #endif
34103
34104 #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
34105         BOOL))aSyscall[64].pCurrent)
34106
34107 #if SQLITE_OS_WINRT
34108   { "SetFilePointerEx",        (SYSCALL)SetFilePointerEx,        0 },
34109 #else
34110   { "SetFilePointerEx",        (SYSCALL)0,                       0 },
34111 #endif
34112
34113 #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
34114         PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
34115
34116 #if SQLITE_OS_WINRT
34117   { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
34118 #else
34119   { "GetFileInformationByHandleEx", (SYSCALL)0,                  0 },
34120 #endif
34121
34122 #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
34123         FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
34124
34125 #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
34126   { "MapViewOfFileFromApp",    (SYSCALL)MapViewOfFileFromApp,    0 },
34127 #else
34128   { "MapViewOfFileFromApp",    (SYSCALL)0,                       0 },
34129 #endif
34130
34131 #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
34132         SIZE_T))aSyscall[67].pCurrent)
34133
34134 #if SQLITE_OS_WINRT
34135   { "CreateFile2",             (SYSCALL)CreateFile2,             0 },
34136 #else
34137   { "CreateFile2",             (SYSCALL)0,                       0 },
34138 #endif
34139
34140 #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
34141         LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
34142
34143 #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
34144   { "LoadPackagedLibrary",     (SYSCALL)LoadPackagedLibrary,     0 },
34145 #else
34146   { "LoadPackagedLibrary",     (SYSCALL)0,                       0 },
34147 #endif
34148
34149 #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
34150         DWORD))aSyscall[69].pCurrent)
34151
34152 #if SQLITE_OS_WINRT
34153   { "GetTickCount64",          (SYSCALL)GetTickCount64,          0 },
34154 #else
34155   { "GetTickCount64",          (SYSCALL)0,                       0 },
34156 #endif
34157
34158 #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
34159
34160 #if SQLITE_OS_WINRT
34161   { "GetNativeSystemInfo",     (SYSCALL)GetNativeSystemInfo,     0 },
34162 #else
34163   { "GetNativeSystemInfo",     (SYSCALL)0,                       0 },
34164 #endif
34165
34166 #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
34167         LPSYSTEM_INFO))aSyscall[71].pCurrent)
34168
34169 #if defined(SQLITE_WIN32_HAS_ANSI)
34170   { "OutputDebugStringA",      (SYSCALL)OutputDebugStringA,      0 },
34171 #else
34172   { "OutputDebugStringA",      (SYSCALL)0,                       0 },
34173 #endif
34174
34175 #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
34176
34177 #if defined(SQLITE_WIN32_HAS_WIDE)
34178   { "OutputDebugStringW",      (SYSCALL)OutputDebugStringW,      0 },
34179 #else
34180   { "OutputDebugStringW",      (SYSCALL)0,                       0 },
34181 #endif
34182
34183 #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
34184
34185   { "GetProcessHeap",          (SYSCALL)GetProcessHeap,          0 },
34186
34187 #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
34188
34189 #if SQLITE_OS_WINRT && (!defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0)
34190   { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
34191 #else
34192   { "CreateFileMappingFromApp", (SYSCALL)0,                      0 },
34193 #endif
34194
34195 #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
34196         LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
34197
34198 /*
34199 ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
34200 **       is really just a macro that uses a compiler intrinsic (e.g. x64).
34201 **       So do not try to make this is into a redefinable interface.
34202 */
34203 #if defined(InterlockedCompareExchange)
34204   { "InterlockedCompareExchange", (SYSCALL)0,                    0 },
34205
34206 #define osInterlockedCompareExchange InterlockedCompareExchange
34207 #else
34208   { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
34209
34210 #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
34211         SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
34212 #endif /* defined(InterlockedCompareExchange) */
34213
34214 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
34215   { "UuidCreate",               (SYSCALL)UuidCreate,             0 },
34216 #else
34217   { "UuidCreate",               (SYSCALL)0,                      0 },
34218 #endif
34219
34220 #define osUuidCreate ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[77].pCurrent)
34221
34222 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
34223   { "UuidCreateSequential",     (SYSCALL)UuidCreateSequential,   0 },
34224 #else
34225   { "UuidCreateSequential",     (SYSCALL)0,                      0 },
34226 #endif
34227
34228 #define osUuidCreateSequential \
34229         ((RPC_STATUS(RPC_ENTRY*)(UUID*))aSyscall[78].pCurrent)
34230
34231 #if !defined(SQLITE_NO_SYNC) && SQLITE_MAX_MMAP_SIZE>0
34232   { "FlushViewOfFile",          (SYSCALL)FlushViewOfFile,        0 },
34233 #else
34234   { "FlushViewOfFile",          (SYSCALL)0,                      0 },
34235 #endif
34236
34237 #define osFlushViewOfFile \
34238         ((BOOL(WINAPI*)(LPCVOID,SIZE_T))aSyscall[79].pCurrent)
34239
34240 }; /* End of the overrideable system calls */
34241
34242 /*
34243 ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
34244 ** "win32" VFSes.  Return SQLITE_OK opon successfully updating the
34245 ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
34246 ** system call named zName.
34247 */
34248 static int winSetSystemCall(
34249   sqlite3_vfs *pNotUsed,        /* The VFS pointer.  Not used */
34250   const char *zName,            /* Name of system call to override */
34251   sqlite3_syscall_ptr pNewFunc  /* Pointer to new system call value */
34252 ){
34253   unsigned int i;
34254   int rc = SQLITE_NOTFOUND;
34255
34256   UNUSED_PARAMETER(pNotUsed);
34257   if( zName==0 ){
34258     /* If no zName is given, restore all system calls to their default
34259     ** settings and return NULL
34260     */
34261     rc = SQLITE_OK;
34262     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
34263       if( aSyscall[i].pDefault ){
34264         aSyscall[i].pCurrent = aSyscall[i].pDefault;
34265       }
34266     }
34267   }else{
34268     /* If zName is specified, operate on only the one system call
34269     ** specified.
34270     */
34271     for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
34272       if( strcmp(zName, aSyscall[i].zName)==0 ){
34273         if( aSyscall[i].pDefault==0 ){
34274           aSyscall[i].pDefault = aSyscall[i].pCurrent;
34275         }
34276         rc = SQLITE_OK;
34277         if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
34278         aSyscall[i].pCurrent = pNewFunc;
34279         break;
34280       }
34281     }
34282   }
34283   return rc;
34284 }
34285
34286 /*
34287 ** Return the value of a system call.  Return NULL if zName is not a
34288 ** recognized system call name.  NULL is also returned if the system call
34289 ** is currently undefined.
34290 */
34291 static sqlite3_syscall_ptr winGetSystemCall(
34292   sqlite3_vfs *pNotUsed,
34293   const char *zName
34294 ){
34295   unsigned int i;
34296
34297   UNUSED_PARAMETER(pNotUsed);
34298   for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
34299     if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
34300   }
34301   return 0;
34302 }
34303
34304 /*
34305 ** Return the name of the first system call after zName.  If zName==NULL
34306 ** then return the name of the first system call.  Return NULL if zName
34307 ** is the last system call or if zName is not the name of a valid
34308 ** system call.
34309 */
34310 static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
34311   int i = -1;
34312
34313   UNUSED_PARAMETER(p);
34314   if( zName ){
34315     for(i=0; i<ArraySize(aSyscall)-1; i++){
34316       if( strcmp(zName, aSyscall[i].zName)==0 ) break;
34317     }
34318   }
34319   for(i++; i<ArraySize(aSyscall); i++){
34320     if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
34321   }
34322   return 0;
34323 }
34324
34325 #ifdef SQLITE_WIN32_MALLOC
34326 /*
34327 ** If a Win32 native heap has been configured, this function will attempt to
34328 ** compact it.  Upon success, SQLITE_OK will be returned.  Upon failure, one
34329 ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned.  The
34330 ** "pnLargest" argument, if non-zero, will be used to return the size of the
34331 ** largest committed free block in the heap, in bytes.
34332 */
34333 SQLITE_API int SQLITE_STDCALL sqlite3_win32_compact_heap(LPUINT pnLargest){
34334   int rc = SQLITE_OK;
34335   UINT nLargest = 0;
34336   HANDLE hHeap;
34337
34338   winMemAssertMagic();
34339   hHeap = winMemGetHeap();
34340   assert( hHeap!=0 );
34341   assert( hHeap!=INVALID_HANDLE_VALUE );
34342 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34343   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
34344 #endif
34345 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
34346   if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
34347     DWORD lastErrno = osGetLastError();
34348     if( lastErrno==NO_ERROR ){
34349       sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
34350                   (void*)hHeap);
34351       rc = SQLITE_NOMEM;
34352     }else{
34353       sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
34354                   osGetLastError(), (void*)hHeap);
34355       rc = SQLITE_ERROR;
34356     }
34357   }
34358 #else
34359   sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
34360               (void*)hHeap);
34361   rc = SQLITE_NOTFOUND;
34362 #endif
34363   if( pnLargest ) *pnLargest = nLargest;
34364   return rc;
34365 }
34366
34367 /*
34368 ** If a Win32 native heap has been configured, this function will attempt to
34369 ** destroy and recreate it.  If the Win32 native heap is not isolated and/or
34370 ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
34371 ** be returned and no changes will be made to the Win32 native heap.
34372 */
34373 SQLITE_API int SQLITE_STDCALL sqlite3_win32_reset_heap(){
34374   int rc;
34375   MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
34376   MUTEX_LOGIC( sqlite3_mutex *pMem; )    /* The memsys static mutex */
34377   MUTEX_LOGIC( pMaster = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MASTER); )
34378   MUTEX_LOGIC( pMem = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_MEM); )
34379   sqlite3_mutex_enter(pMaster);
34380   sqlite3_mutex_enter(pMem);
34381   winMemAssertMagic();
34382   if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
34383     /*
34384     ** At this point, there should be no outstanding memory allocations on
34385     ** the heap.  Also, since both the master and memsys locks are currently
34386     ** being held by us, no other function (i.e. from another thread) should
34387     ** be able to even access the heap.  Attempt to destroy and recreate our
34388     ** isolated Win32 native heap now.
34389     */
34390     assert( winMemGetHeap()!=NULL );
34391     assert( winMemGetOwned() );
34392     assert( sqlite3_memory_used()==0 );
34393     winMemShutdown(winMemGetDataPtr());
34394     assert( winMemGetHeap()==NULL );
34395     assert( !winMemGetOwned() );
34396     assert( sqlite3_memory_used()==0 );
34397     rc = winMemInit(winMemGetDataPtr());
34398     assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
34399     assert( rc!=SQLITE_OK || winMemGetOwned() );
34400     assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
34401   }else{
34402     /*
34403     ** The Win32 native heap cannot be modified because it may be in use.
34404     */
34405     rc = SQLITE_BUSY;
34406   }
34407   sqlite3_mutex_leave(pMem);
34408   sqlite3_mutex_leave(pMaster);
34409   return rc;
34410 }
34411 #endif /* SQLITE_WIN32_MALLOC */
34412
34413 /*
34414 ** This function outputs the specified (ANSI) string to the Win32 debugger
34415 ** (if available).
34416 */
34417
34418 SQLITE_API void SQLITE_STDCALL sqlite3_win32_write_debug(const char *zBuf, int nBuf){
34419   char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
34420   int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
34421   if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
34422   assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
34423 #if defined(SQLITE_WIN32_HAS_ANSI)
34424   if( nMin>0 ){
34425     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
34426     memcpy(zDbgBuf, zBuf, nMin);
34427     osOutputDebugStringA(zDbgBuf);
34428   }else{
34429     osOutputDebugStringA(zBuf);
34430   }
34431 #elif defined(SQLITE_WIN32_HAS_WIDE)
34432   memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
34433   if ( osMultiByteToWideChar(
34434           osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
34435           nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
34436     return;
34437   }
34438   osOutputDebugStringW((LPCWSTR)zDbgBuf);
34439 #else
34440   if( nMin>0 ){
34441     memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
34442     memcpy(zDbgBuf, zBuf, nMin);
34443     fprintf(stderr, "%s", zDbgBuf);
34444   }else{
34445     fprintf(stderr, "%s", zBuf);
34446   }
34447 #endif
34448 }
34449
34450 /*
34451 ** The following routine suspends the current thread for at least ms
34452 ** milliseconds.  This is equivalent to the Win32 Sleep() interface.
34453 */
34454 #if SQLITE_OS_WINRT
34455 static HANDLE sleepObj = NULL;
34456 #endif
34457
34458 SQLITE_API void SQLITE_STDCALL sqlite3_win32_sleep(DWORD milliseconds){
34459 #if SQLITE_OS_WINRT
34460   if ( sleepObj==NULL ){
34461     sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
34462                                 SYNCHRONIZE);
34463   }
34464   assert( sleepObj!=NULL );
34465   osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
34466 #else
34467   osSleep(milliseconds);
34468 #endif
34469 }
34470
34471 #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
34472         SQLITE_THREADSAFE>0
34473 SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
34474   DWORD rc;
34475   while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
34476                                        TRUE))==WAIT_IO_COMPLETION ){}
34477   return rc;
34478 }
34479 #endif
34480
34481 /*
34482 ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
34483 ** or WinCE.  Return false (zero) for Win95, Win98, or WinME.
34484 **
34485 ** Here is an interesting observation:  Win95, Win98, and WinME lack
34486 ** the LockFileEx() API.  But we can still statically link against that
34487 ** API as long as we don't call it when running Win95/98/ME.  A call to
34488 ** this routine is used to determine if the host is Win95/98/ME or
34489 ** WinNT/2K/XP so that we will know whether or not we can safely call
34490 ** the LockFileEx() API.
34491 */
34492
34493 #if !defined(SQLITE_WIN32_GETVERSIONEX) || !SQLITE_WIN32_GETVERSIONEX
34494 # define osIsNT()  (1)
34495 #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
34496 # define osIsNT()  (1)
34497 #elif !defined(SQLITE_WIN32_HAS_WIDE)
34498 # define osIsNT()  (0)
34499 #else
34500 # define osIsNT()  ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
34501 #endif
34502
34503 /*
34504 ** This function determines if the machine is running a version of Windows
34505 ** based on the NT kernel.
34506 */
34507 SQLITE_API int SQLITE_STDCALL sqlite3_win32_is_nt(void){
34508 #if SQLITE_OS_WINRT
34509   /*
34510   ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
34511   **       kernel.
34512   */
34513   return 1;
34514 #elif defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
34515   if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
34516 #if defined(SQLITE_WIN32_HAS_ANSI)
34517     OSVERSIONINFOA sInfo;
34518     sInfo.dwOSVersionInfoSize = sizeof(sInfo);
34519     osGetVersionExA(&sInfo);
34520     osInterlockedCompareExchange(&sqlite3_os_type,
34521         (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
34522 #elif defined(SQLITE_WIN32_HAS_WIDE)
34523     OSVERSIONINFOW sInfo;
34524     sInfo.dwOSVersionInfoSize = sizeof(sInfo);
34525     osGetVersionExW(&sInfo);
34526     osInterlockedCompareExchange(&sqlite3_os_type,
34527         (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
34528 #endif
34529   }
34530   return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
34531 #elif SQLITE_TEST
34532   return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
34533 #else
34534   /*
34535   ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
34536   **       deprecated are always assumed to be based on the NT kernel.
34537   */
34538   return 1;
34539 #endif
34540 }
34541
34542 #ifdef SQLITE_WIN32_MALLOC
34543 /*
34544 ** Allocate nBytes of memory.
34545 */
34546 static void *winMemMalloc(int nBytes){
34547   HANDLE hHeap;
34548   void *p;
34549
34550   winMemAssertMagic();
34551   hHeap = winMemGetHeap();
34552   assert( hHeap!=0 );
34553   assert( hHeap!=INVALID_HANDLE_VALUE );
34554 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34555   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
34556 #endif
34557   assert( nBytes>=0 );
34558   p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
34559   if( !p ){
34560     sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
34561                 nBytes, osGetLastError(), (void*)hHeap);
34562   }
34563   return p;
34564 }
34565
34566 /*
34567 ** Free memory.
34568 */
34569 static void winMemFree(void *pPrior){
34570   HANDLE hHeap;
34571
34572   winMemAssertMagic();
34573   hHeap = winMemGetHeap();
34574   assert( hHeap!=0 );
34575   assert( hHeap!=INVALID_HANDLE_VALUE );
34576 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34577   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
34578 #endif
34579   if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
34580   if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
34581     sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
34582                 pPrior, osGetLastError(), (void*)hHeap);
34583   }
34584 }
34585
34586 /*
34587 ** Change the size of an existing memory allocation
34588 */
34589 static void *winMemRealloc(void *pPrior, int nBytes){
34590   HANDLE hHeap;
34591   void *p;
34592
34593   winMemAssertMagic();
34594   hHeap = winMemGetHeap();
34595   assert( hHeap!=0 );
34596   assert( hHeap!=INVALID_HANDLE_VALUE );
34597 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34598   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
34599 #endif
34600   assert( nBytes>=0 );
34601   if( !pPrior ){
34602     p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
34603   }else{
34604     p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
34605   }
34606   if( !p ){
34607     sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
34608                 pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
34609                 (void*)hHeap);
34610   }
34611   return p;
34612 }
34613
34614 /*
34615 ** Return the size of an outstanding allocation, in bytes.
34616 */
34617 static int winMemSize(void *p){
34618   HANDLE hHeap;
34619   SIZE_T n;
34620
34621   winMemAssertMagic();
34622   hHeap = winMemGetHeap();
34623   assert( hHeap!=0 );
34624   assert( hHeap!=INVALID_HANDLE_VALUE );
34625 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34626   assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
34627 #endif
34628   if( !p ) return 0;
34629   n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
34630   if( n==(SIZE_T)-1 ){
34631     sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
34632                 p, osGetLastError(), (void*)hHeap);
34633     return 0;
34634   }
34635   return (int)n;
34636 }
34637
34638 /*
34639 ** Round up a request size to the next valid allocation size.
34640 */
34641 static int winMemRoundup(int n){
34642   return n;
34643 }
34644
34645 /*
34646 ** Initialize this module.
34647 */
34648 static int winMemInit(void *pAppData){
34649   winMemData *pWinMemData = (winMemData *)pAppData;
34650
34651   if( !pWinMemData ) return SQLITE_ERROR;
34652   assert( pWinMemData->magic1==WINMEM_MAGIC1 );
34653   assert( pWinMemData->magic2==WINMEM_MAGIC2 );
34654
34655 #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
34656   if( !pWinMemData->hHeap ){
34657     DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
34658     DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
34659     if( dwMaximumSize==0 ){
34660       dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
34661     }else if( dwInitialSize>dwMaximumSize ){
34662       dwInitialSize = dwMaximumSize;
34663     }
34664     pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
34665                                       dwInitialSize, dwMaximumSize);
34666     if( !pWinMemData->hHeap ){
34667       sqlite3_log(SQLITE_NOMEM,
34668           "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
34669           osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
34670           dwMaximumSize);
34671       return SQLITE_NOMEM;
34672     }
34673     pWinMemData->bOwned = TRUE;
34674     assert( pWinMemData->bOwned );
34675   }
34676 #else
34677   pWinMemData->hHeap = osGetProcessHeap();
34678   if( !pWinMemData->hHeap ){
34679     sqlite3_log(SQLITE_NOMEM,
34680         "failed to GetProcessHeap (%lu)", osGetLastError());
34681     return SQLITE_NOMEM;
34682   }
34683   pWinMemData->bOwned = FALSE;
34684   assert( !pWinMemData->bOwned );
34685 #endif
34686   assert( pWinMemData->hHeap!=0 );
34687   assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
34688 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34689   assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
34690 #endif
34691   return SQLITE_OK;
34692 }
34693
34694 /*
34695 ** Deinitialize this module.
34696 */
34697 static void winMemShutdown(void *pAppData){
34698   winMemData *pWinMemData = (winMemData *)pAppData;
34699
34700   if( !pWinMemData ) return;
34701   assert( pWinMemData->magic1==WINMEM_MAGIC1 );
34702   assert( pWinMemData->magic2==WINMEM_MAGIC2 );
34703
34704   if( pWinMemData->hHeap ){
34705     assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
34706 #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
34707     assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
34708 #endif
34709     if( pWinMemData->bOwned ){
34710       if( !osHeapDestroy(pWinMemData->hHeap) ){
34711         sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
34712                     osGetLastError(), (void*)pWinMemData->hHeap);
34713       }
34714       pWinMemData->bOwned = FALSE;
34715     }
34716     pWinMemData->hHeap = NULL;
34717   }
34718 }
34719
34720 /*
34721 ** Populate the low-level memory allocation function pointers in
34722 ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
34723 ** arguments specify the block of memory to manage.
34724 **
34725 ** This routine is only called by sqlite3_config(), and therefore
34726 ** is not required to be threadsafe (it is not).
34727 */
34728 SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
34729   static const sqlite3_mem_methods winMemMethods = {
34730     winMemMalloc,
34731     winMemFree,
34732     winMemRealloc,
34733     winMemSize,
34734     winMemRoundup,
34735     winMemInit,
34736     winMemShutdown,
34737     &win_mem_data
34738   };
34739   return &winMemMethods;
34740 }
34741
34742 SQLITE_PRIVATE void sqlite3MemSetDefault(void){
34743   sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
34744 }
34745 #endif /* SQLITE_WIN32_MALLOC */
34746
34747 /*
34748 ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
34749 **
34750 ** Space to hold the returned string is obtained from malloc.
34751 */
34752 static LPWSTR winUtf8ToUnicode(const char *zFilename){
34753   int nChar;
34754   LPWSTR zWideFilename;
34755
34756   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
34757   if( nChar==0 ){
34758     return 0;
34759   }
34760   zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
34761   if( zWideFilename==0 ){
34762     return 0;
34763   }
34764   nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
34765                                 nChar);
34766   if( nChar==0 ){
34767     sqlite3_free(zWideFilename);
34768     zWideFilename = 0;
34769   }
34770   return zWideFilename;
34771 }
34772
34773 /*
34774 ** Convert Microsoft Unicode to UTF-8.  Space to hold the returned string is
34775 ** obtained from sqlite3_malloc().
34776 */
34777 static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
34778   int nByte;
34779   char *zFilename;
34780
34781   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
34782   if( nByte == 0 ){
34783     return 0;
34784   }
34785   zFilename = sqlite3MallocZero( nByte );
34786   if( zFilename==0 ){
34787     return 0;
34788   }
34789   nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
34790                                 0, 0);
34791   if( nByte == 0 ){
34792     sqlite3_free(zFilename);
34793     zFilename = 0;
34794   }
34795   return zFilename;
34796 }
34797
34798 /*
34799 ** Convert an ANSI string to Microsoft Unicode, based on the
34800 ** current codepage settings for file apis.
34801 **
34802 ** Space to hold the returned string is obtained
34803 ** from sqlite3_malloc.
34804 */
34805 static LPWSTR winMbcsToUnicode(const char *zFilename){
34806   int nByte;
34807   LPWSTR zMbcsFilename;
34808   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
34809
34810   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
34811                                 0)*sizeof(WCHAR);
34812   if( nByte==0 ){
34813     return 0;
34814   }
34815   zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
34816   if( zMbcsFilename==0 ){
34817     return 0;
34818   }
34819   nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
34820                                 nByte);
34821   if( nByte==0 ){
34822     sqlite3_free(zMbcsFilename);
34823     zMbcsFilename = 0;
34824   }
34825   return zMbcsFilename;
34826 }
34827
34828 /*
34829 ** Convert Microsoft Unicode to multi-byte character string, based on the
34830 ** user's ANSI codepage.
34831 **
34832 ** Space to hold the returned string is obtained from
34833 ** sqlite3_malloc().
34834 */
34835 static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
34836   int nByte;
34837   char *zFilename;
34838   int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
34839
34840   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
34841   if( nByte == 0 ){
34842     return 0;
34843   }
34844   zFilename = sqlite3MallocZero( nByte );
34845   if( zFilename==0 ){
34846     return 0;
34847   }
34848   nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
34849                                 nByte, 0, 0);
34850   if( nByte == 0 ){
34851     sqlite3_free(zFilename);
34852     zFilename = 0;
34853   }
34854   return zFilename;
34855 }
34856
34857 /*
34858 ** Convert multibyte character string to UTF-8.  Space to hold the
34859 ** returned string is obtained from sqlite3_malloc().
34860 */
34861 SQLITE_API char *SQLITE_STDCALL sqlite3_win32_mbcs_to_utf8(const char *zFilename){
34862   char *zFilenameUtf8;
34863   LPWSTR zTmpWide;
34864
34865   zTmpWide = winMbcsToUnicode(zFilename);
34866   if( zTmpWide==0 ){
34867     return 0;
34868   }
34869   zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
34870   sqlite3_free(zTmpWide);
34871   return zFilenameUtf8;
34872 }
34873
34874 /*
34875 ** Convert UTF-8 to multibyte character string.  Space to hold the
34876 ** returned string is obtained from sqlite3_malloc().
34877 */
34878 SQLITE_API char *SQLITE_STDCALL sqlite3_win32_utf8_to_mbcs(const char *zFilename){
34879   char *zFilenameMbcs;
34880   LPWSTR zTmpWide;
34881
34882   zTmpWide = winUtf8ToUnicode(zFilename);
34883   if( zTmpWide==0 ){
34884     return 0;
34885   }
34886   zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
34887   sqlite3_free(zTmpWide);
34888   return zFilenameMbcs;
34889 }
34890
34891 /*
34892 ** This function sets the data directory or the temporary directory based on
34893 ** the provided arguments.  The type argument must be 1 in order to set the
34894 ** data directory or 2 in order to set the temporary directory.  The zValue
34895 ** argument is the name of the directory to use.  The return value will be
34896 ** SQLITE_OK if successful.
34897 */
34898 SQLITE_API int SQLITE_STDCALL sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
34899   char **ppDirectory = 0;
34900 #ifndef SQLITE_OMIT_AUTOINIT
34901   int rc = sqlite3_initialize();
34902   if( rc ) return rc;
34903 #endif
34904   if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
34905     ppDirectory = &sqlite3_data_directory;
34906   }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
34907     ppDirectory = &sqlite3_temp_directory;
34908   }
34909   assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
34910           || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
34911   );
34912   assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
34913   if( ppDirectory ){
34914     char *zValueUtf8 = 0;
34915     if( zValue && zValue[0] ){
34916       zValueUtf8 = winUnicodeToUtf8(zValue);
34917       if ( zValueUtf8==0 ){
34918         return SQLITE_NOMEM;
34919       }
34920     }
34921     sqlite3_free(*ppDirectory);
34922     *ppDirectory = zValueUtf8;
34923     return SQLITE_OK;
34924   }
34925   return SQLITE_ERROR;
34926 }
34927
34928 /*
34929 ** The return value of winGetLastErrorMsg
34930 ** is zero if the error message fits in the buffer, or non-zero
34931 ** otherwise (if the message was truncated).
34932 */
34933 static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
34934   /* FormatMessage returns 0 on failure.  Otherwise it
34935   ** returns the number of TCHARs written to the output
34936   ** buffer, excluding the terminating null char.
34937   */
34938   DWORD dwLen = 0;
34939   char *zOut = 0;
34940
34941   if( osIsNT() ){
34942 #if SQLITE_OS_WINRT
34943     WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
34944     dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
34945                              FORMAT_MESSAGE_IGNORE_INSERTS,
34946                              NULL,
34947                              lastErrno,
34948                              0,
34949                              zTempWide,
34950                              SQLITE_WIN32_MAX_ERRMSG_CHARS,
34951                              0);
34952 #else
34953     LPWSTR zTempWide = NULL;
34954     dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
34955                              FORMAT_MESSAGE_FROM_SYSTEM |
34956                              FORMAT_MESSAGE_IGNORE_INSERTS,
34957                              NULL,
34958                              lastErrno,
34959                              0,
34960                              (LPWSTR) &zTempWide,
34961                              0,
34962                              0);
34963 #endif
34964     if( dwLen > 0 ){
34965       /* allocate a buffer and convert to UTF8 */
34966       sqlite3BeginBenignMalloc();
34967       zOut = winUnicodeToUtf8(zTempWide);
34968       sqlite3EndBenignMalloc();
34969 #if !SQLITE_OS_WINRT
34970       /* free the system buffer allocated by FormatMessage */
34971       osLocalFree(zTempWide);
34972 #endif
34973     }
34974   }
34975 #ifdef SQLITE_WIN32_HAS_ANSI
34976   else{
34977     char *zTemp = NULL;
34978     dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
34979                              FORMAT_MESSAGE_FROM_SYSTEM |
34980                              FORMAT_MESSAGE_IGNORE_INSERTS,
34981                              NULL,
34982                              lastErrno,
34983                              0,
34984                              (LPSTR) &zTemp,
34985                              0,
34986                              0);
34987     if( dwLen > 0 ){
34988       /* allocate a buffer and convert to UTF8 */
34989       sqlite3BeginBenignMalloc();
34990       zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
34991       sqlite3EndBenignMalloc();
34992       /* free the system buffer allocated by FormatMessage */
34993       osLocalFree(zTemp);
34994     }
34995   }
34996 #endif
34997   if( 0 == dwLen ){
34998     sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
34999   }else{
35000     /* copy a maximum of nBuf chars to output buffer */
35001     sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
35002     /* free the UTF8 buffer */
35003     sqlite3_free(zOut);
35004   }
35005   return 0;
35006 }
35007
35008 /*
35009 **
35010 ** This function - winLogErrorAtLine() - is only ever called via the macro
35011 ** winLogError().
35012 **
35013 ** This routine is invoked after an error occurs in an OS function.
35014 ** It logs a message using sqlite3_log() containing the current value of
35015 ** error code and, if possible, the human-readable equivalent from
35016 ** FormatMessage.
35017 **
35018 ** The first argument passed to the macro should be the error code that
35019 ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
35020 ** The two subsequent arguments should be the name of the OS function that
35021 ** failed and the associated file-system path, if any.
35022 */
35023 #define winLogError(a,b,c,d)   winLogErrorAtLine(a,b,c,d,__LINE__)
35024 static int winLogErrorAtLine(
35025   int errcode,                    /* SQLite error code */
35026   DWORD lastErrno,                /* Win32 last error */
35027   const char *zFunc,              /* Name of OS function that failed */
35028   const char *zPath,              /* File path associated with error */
35029   int iLine                       /* Source line number where error occurred */
35030 ){
35031   char zMsg[500];                 /* Human readable error text */
35032   int i;                          /* Loop counter */
35033
35034   zMsg[0] = 0;
35035   winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
35036   assert( errcode!=SQLITE_OK );
35037   if( zPath==0 ) zPath = "";
35038   for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
35039   zMsg[i] = 0;
35040   sqlite3_log(errcode,
35041       "os_win.c:%d: (%lu) %s(%s) - %s",
35042       iLine, lastErrno, zFunc, zPath, zMsg
35043   );
35044
35045   return errcode;
35046 }
35047
35048 /*
35049 ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
35050 ** will be retried following a locking error - probably caused by
35051 ** antivirus software.  Also the initial delay before the first retry.
35052 ** The delay increases linearly with each retry.
35053 */
35054 #ifndef SQLITE_WIN32_IOERR_RETRY
35055 # define SQLITE_WIN32_IOERR_RETRY 10
35056 #endif
35057 #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
35058 # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
35059 #endif
35060 static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
35061 static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
35062
35063 /*
35064 ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
35065 ** error code obtained via GetLastError() is eligible to be retried.  It
35066 ** must accept the error code DWORD as its only argument and should return
35067 ** non-zero if the error code is transient in nature and the operation
35068 ** responsible for generating the original error might succeed upon being
35069 ** retried.  The argument to this macro should be a variable.
35070 **
35071 ** Additionally, a macro named "winIoerrCanRetry2" may be defined.  If it
35072 ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
35073 ** returns zero.  The "winIoerrCanRetry2" macro is completely optional and
35074 ** may be used to include additional error codes in the set that should
35075 ** result in the failing I/O operation being retried by the caller.  If
35076 ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
35077 ** identical to those of the "winIoerrCanRetry1" macro.
35078 */
35079 #if !defined(winIoerrCanRetry1)
35080 #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED)        || \
35081                               ((a)==ERROR_SHARING_VIOLATION)    || \
35082                               ((a)==ERROR_LOCK_VIOLATION)       || \
35083                               ((a)==ERROR_DEV_NOT_EXIST)        || \
35084                               ((a)==ERROR_NETNAME_DELETED)      || \
35085                               ((a)==ERROR_SEM_TIMEOUT)          || \
35086                               ((a)==ERROR_NETWORK_UNREACHABLE))
35087 #endif
35088
35089 /*
35090 ** If a ReadFile() or WriteFile() error occurs, invoke this routine
35091 ** to see if it should be retried.  Return TRUE to retry.  Return FALSE
35092 ** to give up with an error.
35093 */
35094 static int winRetryIoerr(int *pnRetry, DWORD *pError){
35095   DWORD e = osGetLastError();
35096   if( *pnRetry>=winIoerrRetry ){
35097     if( pError ){
35098       *pError = e;
35099     }
35100     return 0;
35101   }
35102   if( winIoerrCanRetry1(e) ){
35103     sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
35104     ++*pnRetry;
35105     return 1;
35106   }
35107 #if defined(winIoerrCanRetry2)
35108   else if( winIoerrCanRetry2(e) ){
35109     sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
35110     ++*pnRetry;
35111     return 1;
35112   }
35113 #endif
35114   if( pError ){
35115     *pError = e;
35116   }
35117   return 0;
35118 }
35119
35120 /*
35121 ** Log a I/O error retry episode.
35122 */
35123 static void winLogIoerr(int nRetry, int lineno){
35124   if( nRetry ){
35125     sqlite3_log(SQLITE_NOTICE,
35126       "delayed %dms for lock/sharing conflict at line %d",
35127       winIoerrRetryDelay*nRetry*(nRetry+1)/2, lineno
35128     );
35129   }
35130 }
35131
35132 #if SQLITE_OS_WINCE
35133 /*************************************************************************
35134 ** This section contains code for WinCE only.
35135 */
35136 #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
35137 /*
35138 ** The MSVC CRT on Windows CE may not have a localtime() function.  So
35139 ** create a substitute.
35140 */
35141 /* #include <time.h> */
35142 struct tm *__cdecl localtime(const time_t *t)
35143 {
35144   static struct tm y;
35145   FILETIME uTm, lTm;
35146   SYSTEMTIME pTm;
35147   sqlite3_int64 t64;
35148   t64 = *t;
35149   t64 = (t64 + 11644473600)*10000000;
35150   uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
35151   uTm.dwHighDateTime= (DWORD)(t64 >> 32);
35152   osFileTimeToLocalFileTime(&uTm,&lTm);
35153   osFileTimeToSystemTime(&lTm,&pTm);
35154   y.tm_year = pTm.wYear - 1900;
35155   y.tm_mon = pTm.wMonth - 1;
35156   y.tm_wday = pTm.wDayOfWeek;
35157   y.tm_mday = pTm.wDay;
35158   y.tm_hour = pTm.wHour;
35159   y.tm_min = pTm.wMinute;
35160   y.tm_sec = pTm.wSecond;
35161   return &y;
35162 }
35163 #endif
35164
35165 #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
35166
35167 /*
35168 ** Acquire a lock on the handle h
35169 */
35170 static void winceMutexAcquire(HANDLE h){
35171    DWORD dwErr;
35172    do {
35173      dwErr = osWaitForSingleObject(h, INFINITE);
35174    } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
35175 }
35176 /*
35177 ** Release a lock acquired by winceMutexAcquire()
35178 */
35179 #define winceMutexRelease(h) ReleaseMutex(h)
35180
35181 /*
35182 ** Create the mutex and shared memory used for locking in the file
35183 ** descriptor pFile
35184 */
35185 static int winceCreateLock(const char *zFilename, winFile *pFile){
35186   LPWSTR zTok;
35187   LPWSTR zName;
35188   DWORD lastErrno;
35189   BOOL bLogged = FALSE;
35190   BOOL bInit = TRUE;
35191
35192   zName = winUtf8ToUnicode(zFilename);
35193   if( zName==0 ){
35194     /* out of memory */
35195     return SQLITE_IOERR_NOMEM;
35196   }
35197
35198   /* Initialize the local lockdata */
35199   memset(&pFile->local, 0, sizeof(pFile->local));
35200
35201   /* Replace the backslashes from the filename and lowercase it
35202   ** to derive a mutex name. */
35203   zTok = osCharLowerW(zName);
35204   for (;*zTok;zTok++){
35205     if (*zTok == '\\') *zTok = '_';
35206   }
35207
35208   /* Create/open the named mutex */
35209   pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
35210   if (!pFile->hMutex){
35211     pFile->lastErrno = osGetLastError();
35212     sqlite3_free(zName);
35213     return winLogError(SQLITE_IOERR, pFile->lastErrno,
35214                        "winceCreateLock1", zFilename);
35215   }
35216
35217   /* Acquire the mutex before continuing */
35218   winceMutexAcquire(pFile->hMutex);
35219
35220   /* Since the names of named mutexes, semaphores, file mappings etc are
35221   ** case-sensitive, take advantage of that by uppercasing the mutex name
35222   ** and using that as the shared filemapping name.
35223   */
35224   osCharUpperW(zName);
35225   pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
35226                                         PAGE_READWRITE, 0, sizeof(winceLock),
35227                                         zName);
35228
35229   /* Set a flag that indicates we're the first to create the memory so it
35230   ** must be zero-initialized */
35231   lastErrno = osGetLastError();
35232   if (lastErrno == ERROR_ALREADY_EXISTS){
35233     bInit = FALSE;
35234   }
35235
35236   sqlite3_free(zName);
35237
35238   /* If we succeeded in making the shared memory handle, map it. */
35239   if( pFile->hShared ){
35240     pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
35241              FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
35242     /* If mapping failed, close the shared memory handle and erase it */
35243     if( !pFile->shared ){
35244       pFile->lastErrno = osGetLastError();
35245       winLogError(SQLITE_IOERR, pFile->lastErrno,
35246                   "winceCreateLock2", zFilename);
35247       bLogged = TRUE;
35248       osCloseHandle(pFile->hShared);
35249       pFile->hShared = NULL;
35250     }
35251   }
35252
35253   /* If shared memory could not be created, then close the mutex and fail */
35254   if( pFile->hShared==NULL ){
35255     if( !bLogged ){
35256       pFile->lastErrno = lastErrno;
35257       winLogError(SQLITE_IOERR, pFile->lastErrno,
35258                   "winceCreateLock3", zFilename);
35259       bLogged = TRUE;
35260     }
35261     winceMutexRelease(pFile->hMutex);
35262     osCloseHandle(pFile->hMutex);
35263     pFile->hMutex = NULL;
35264     return SQLITE_IOERR;
35265   }
35266
35267   /* Initialize the shared memory if we're supposed to */
35268   if( bInit ){
35269     memset(pFile->shared, 0, sizeof(winceLock));
35270   }
35271
35272   winceMutexRelease(pFile->hMutex);
35273   return SQLITE_OK;
35274 }
35275
35276 /*
35277 ** Destroy the part of winFile that deals with wince locks
35278 */
35279 static void winceDestroyLock(winFile *pFile){
35280   if (pFile->hMutex){
35281     /* Acquire the mutex */
35282     winceMutexAcquire(pFile->hMutex);
35283
35284     /* The following blocks should probably assert in debug mode, but they
35285        are to cleanup in case any locks remained open */
35286     if (pFile->local.nReaders){
35287       pFile->shared->nReaders --;
35288     }
35289     if (pFile->local.bReserved){
35290       pFile->shared->bReserved = FALSE;
35291     }
35292     if (pFile->local.bPending){
35293       pFile->shared->bPending = FALSE;
35294     }
35295     if (pFile->local.bExclusive){
35296       pFile->shared->bExclusive = FALSE;
35297     }
35298
35299     /* De-reference and close our copy of the shared memory handle */
35300     osUnmapViewOfFile(pFile->shared);
35301     osCloseHandle(pFile->hShared);
35302
35303     /* Done with the mutex */
35304     winceMutexRelease(pFile->hMutex);
35305     osCloseHandle(pFile->hMutex);
35306     pFile->hMutex = NULL;
35307   }
35308 }
35309
35310 /*
35311 ** An implementation of the LockFile() API of Windows for CE
35312 */
35313 static BOOL winceLockFile(
35314   LPHANDLE phFile,
35315   DWORD dwFileOffsetLow,
35316   DWORD dwFileOffsetHigh,
35317   DWORD nNumberOfBytesToLockLow,
35318   DWORD nNumberOfBytesToLockHigh
35319 ){
35320   winFile *pFile = HANDLE_TO_WINFILE(phFile);
35321   BOOL bReturn = FALSE;
35322
35323   UNUSED_PARAMETER(dwFileOffsetHigh);
35324   UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
35325
35326   if (!pFile->hMutex) return TRUE;
35327   winceMutexAcquire(pFile->hMutex);
35328
35329   /* Wanting an exclusive lock? */
35330   if (dwFileOffsetLow == (DWORD)SHARED_FIRST
35331        && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
35332     if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
35333        pFile->shared->bExclusive = TRUE;
35334        pFile->local.bExclusive = TRUE;
35335        bReturn = TRUE;
35336     }
35337   }
35338
35339   /* Want a read-only lock? */
35340   else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
35341            nNumberOfBytesToLockLow == 1){
35342     if (pFile->shared->bExclusive == 0){
35343       pFile->local.nReaders ++;
35344       if (pFile->local.nReaders == 1){
35345         pFile->shared->nReaders ++;
35346       }
35347       bReturn = TRUE;
35348     }
35349   }
35350
35351   /* Want a pending lock? */
35352   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
35353            && nNumberOfBytesToLockLow == 1){
35354     /* If no pending lock has been acquired, then acquire it */
35355     if (pFile->shared->bPending == 0) {
35356       pFile->shared->bPending = TRUE;
35357       pFile->local.bPending = TRUE;
35358       bReturn = TRUE;
35359     }
35360   }
35361
35362   /* Want a reserved lock? */
35363   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
35364            && nNumberOfBytesToLockLow == 1){
35365     if (pFile->shared->bReserved == 0) {
35366       pFile->shared->bReserved = TRUE;
35367       pFile->local.bReserved = TRUE;
35368       bReturn = TRUE;
35369     }
35370   }
35371
35372   winceMutexRelease(pFile->hMutex);
35373   return bReturn;
35374 }
35375
35376 /*
35377 ** An implementation of the UnlockFile API of Windows for CE
35378 */
35379 static BOOL winceUnlockFile(
35380   LPHANDLE phFile,
35381   DWORD dwFileOffsetLow,
35382   DWORD dwFileOffsetHigh,
35383   DWORD nNumberOfBytesToUnlockLow,
35384   DWORD nNumberOfBytesToUnlockHigh
35385 ){
35386   winFile *pFile = HANDLE_TO_WINFILE(phFile);
35387   BOOL bReturn = FALSE;
35388
35389   UNUSED_PARAMETER(dwFileOffsetHigh);
35390   UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
35391
35392   if (!pFile->hMutex) return TRUE;
35393   winceMutexAcquire(pFile->hMutex);
35394
35395   /* Releasing a reader lock or an exclusive lock */
35396   if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
35397     /* Did we have an exclusive lock? */
35398     if (pFile->local.bExclusive){
35399       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
35400       pFile->local.bExclusive = FALSE;
35401       pFile->shared->bExclusive = FALSE;
35402       bReturn = TRUE;
35403     }
35404
35405     /* Did we just have a reader lock? */
35406     else if (pFile->local.nReaders){
35407       assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
35408              || nNumberOfBytesToUnlockLow == 1);
35409       pFile->local.nReaders --;
35410       if (pFile->local.nReaders == 0)
35411       {
35412         pFile->shared->nReaders --;
35413       }
35414       bReturn = TRUE;
35415     }
35416   }
35417
35418   /* Releasing a pending lock */
35419   else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
35420            && nNumberOfBytesToUnlockLow == 1){
35421     if (pFile->local.bPending){
35422       pFile->local.bPending = FALSE;
35423       pFile->shared->bPending = FALSE;
35424       bReturn = TRUE;
35425     }
35426   }
35427   /* Releasing a reserved lock */
35428   else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
35429            && nNumberOfBytesToUnlockLow == 1){
35430     if (pFile->local.bReserved) {
35431       pFile->local.bReserved = FALSE;
35432       pFile->shared->bReserved = FALSE;
35433       bReturn = TRUE;
35434     }
35435   }
35436
35437   winceMutexRelease(pFile->hMutex);
35438   return bReturn;
35439 }
35440 /*
35441 ** End of the special code for wince
35442 *****************************************************************************/
35443 #endif /* SQLITE_OS_WINCE */
35444
35445 /*
35446 ** Lock a file region.
35447 */
35448 static BOOL winLockFile(
35449   LPHANDLE phFile,
35450   DWORD flags,
35451   DWORD offsetLow,
35452   DWORD offsetHigh,
35453   DWORD numBytesLow,
35454   DWORD numBytesHigh
35455 ){
35456 #if SQLITE_OS_WINCE
35457   /*
35458   ** NOTE: Windows CE is handled differently here due its lack of the Win32
35459   **       API LockFile.
35460   */
35461   return winceLockFile(phFile, offsetLow, offsetHigh,
35462                        numBytesLow, numBytesHigh);
35463 #else
35464   if( osIsNT() ){
35465     OVERLAPPED ovlp;
35466     memset(&ovlp, 0, sizeof(OVERLAPPED));
35467     ovlp.Offset = offsetLow;
35468     ovlp.OffsetHigh = offsetHigh;
35469     return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
35470   }else{
35471     return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
35472                       numBytesHigh);
35473   }
35474 #endif
35475 }
35476
35477 /*
35478 ** Unlock a file region.
35479  */
35480 static BOOL winUnlockFile(
35481   LPHANDLE phFile,
35482   DWORD offsetLow,
35483   DWORD offsetHigh,
35484   DWORD numBytesLow,
35485   DWORD numBytesHigh
35486 ){
35487 #if SQLITE_OS_WINCE
35488   /*
35489   ** NOTE: Windows CE is handled differently here due its lack of the Win32
35490   **       API UnlockFile.
35491   */
35492   return winceUnlockFile(phFile, offsetLow, offsetHigh,
35493                          numBytesLow, numBytesHigh);
35494 #else
35495   if( osIsNT() ){
35496     OVERLAPPED ovlp;
35497     memset(&ovlp, 0, sizeof(OVERLAPPED));
35498     ovlp.Offset = offsetLow;
35499     ovlp.OffsetHigh = offsetHigh;
35500     return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
35501   }else{
35502     return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
35503                         numBytesHigh);
35504   }
35505 #endif
35506 }
35507
35508 /*****************************************************************************
35509 ** The next group of routines implement the I/O methods specified
35510 ** by the sqlite3_io_methods object.
35511 ******************************************************************************/
35512
35513 /*
35514 ** Some Microsoft compilers lack this definition.
35515 */
35516 #ifndef INVALID_SET_FILE_POINTER
35517 # define INVALID_SET_FILE_POINTER ((DWORD)-1)
35518 #endif
35519
35520 /*
35521 ** Move the current position of the file handle passed as the first
35522 ** argument to offset iOffset within the file. If successful, return 0.
35523 ** Otherwise, set pFile->lastErrno and return non-zero.
35524 */
35525 static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
35526 #if !SQLITE_OS_WINRT
35527   LONG upperBits;                 /* Most sig. 32 bits of new offset */
35528   LONG lowerBits;                 /* Least sig. 32 bits of new offset */
35529   DWORD dwRet;                    /* Value returned by SetFilePointer() */
35530   DWORD lastErrno;                /* Value returned by GetLastError() */
35531
35532   OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
35533
35534   upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
35535   lowerBits = (LONG)(iOffset & 0xffffffff);
35536
35537   /* API oddity: If successful, SetFilePointer() returns a dword
35538   ** containing the lower 32-bits of the new file-offset. Or, if it fails,
35539   ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
35540   ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
35541   ** whether an error has actually occurred, it is also necessary to call
35542   ** GetLastError().
35543   */
35544   dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
35545
35546   if( (dwRet==INVALID_SET_FILE_POINTER
35547       && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
35548     pFile->lastErrno = lastErrno;
35549     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
35550                 "winSeekFile", pFile->zPath);
35551     OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
35552     return 1;
35553   }
35554
35555   OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
35556   return 0;
35557 #else
35558   /*
35559   ** Same as above, except that this implementation works for WinRT.
35560   */
35561
35562   LARGE_INTEGER x;                /* The new offset */
35563   BOOL bRet;                      /* Value returned by SetFilePointerEx() */
35564
35565   x.QuadPart = iOffset;
35566   bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
35567
35568   if(!bRet){
35569     pFile->lastErrno = osGetLastError();
35570     winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
35571                 "winSeekFile", pFile->zPath);
35572     OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
35573     return 1;
35574   }
35575
35576   OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
35577   return 0;
35578 #endif
35579 }
35580
35581 #if SQLITE_MAX_MMAP_SIZE>0
35582 /* Forward references to VFS helper methods used for memory mapped files */
35583 static int winMapfile(winFile*, sqlite3_int64);
35584 static int winUnmapfile(winFile*);
35585 #endif
35586
35587 /*
35588 ** Close a file.
35589 **
35590 ** It is reported that an attempt to close a handle might sometimes
35591 ** fail.  This is a very unreasonable result, but Windows is notorious
35592 ** for being unreasonable so I do not doubt that it might happen.  If
35593 ** the close fails, we pause for 100 milliseconds and try again.  As
35594 ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
35595 ** giving up and returning an error.
35596 */
35597 #define MX_CLOSE_ATTEMPT 3
35598 static int winClose(sqlite3_file *id){
35599   int rc, cnt = 0;
35600   winFile *pFile = (winFile*)id;
35601
35602   assert( id!=0 );
35603 #ifndef SQLITE_OMIT_WAL
35604   assert( pFile->pShm==0 );
35605 #endif
35606   assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
35607   OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p\n",
35608            osGetCurrentProcessId(), pFile, pFile->h));
35609
35610 #if SQLITE_MAX_MMAP_SIZE>0
35611   winUnmapfile(pFile);
35612 #endif
35613
35614   do{
35615     rc = osCloseHandle(pFile->h);
35616     /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
35617   }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
35618 #if SQLITE_OS_WINCE
35619 #define WINCE_DELETION_ATTEMPTS 3
35620   winceDestroyLock(pFile);
35621   if( pFile->zDeleteOnClose ){
35622     int cnt = 0;
35623     while(
35624            osDeleteFileW(pFile->zDeleteOnClose)==0
35625         && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
35626         && cnt++ < WINCE_DELETION_ATTEMPTS
35627     ){
35628        sqlite3_win32_sleep(100);  /* Wait a little before trying again */
35629     }
35630     sqlite3_free(pFile->zDeleteOnClose);
35631   }
35632 #endif
35633   if( rc ){
35634     pFile->h = NULL;
35635   }
35636   OpenCounter(-1);
35637   OSTRACE(("CLOSE pid=%lu, pFile=%p, file=%p, rc=%s\n",
35638            osGetCurrentProcessId(), pFile, pFile->h, rc ? "ok" : "failed"));
35639   return rc ? SQLITE_OK
35640             : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
35641                           "winClose", pFile->zPath);
35642 }
35643
35644 /*
35645 ** Read data from a file into a buffer.  Return SQLITE_OK if all
35646 ** bytes were read successfully and SQLITE_IOERR if anything goes
35647 ** wrong.
35648 */
35649 static int winRead(
35650   sqlite3_file *id,          /* File to read from */
35651   void *pBuf,                /* Write content into this buffer */
35652   int amt,                   /* Number of bytes to read */
35653   sqlite3_int64 offset       /* Begin reading at this offset */
35654 ){
35655 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
35656   OVERLAPPED overlapped;          /* The offset for ReadFile. */
35657 #endif
35658   winFile *pFile = (winFile*)id;  /* file handle */
35659   DWORD nRead;                    /* Number of bytes actually read from file */
35660   int nRetry = 0;                 /* Number of retrys */
35661
35662   assert( id!=0 );
35663   assert( amt>0 );
35664   assert( offset>=0 );
35665   SimulateIOError(return SQLITE_IOERR_READ);
35666   OSTRACE(("READ pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
35667            "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
35668            pFile->h, pBuf, amt, offset, pFile->locktype));
35669
35670 #if SQLITE_MAX_MMAP_SIZE>0
35671   /* Deal with as much of this read request as possible by transfering
35672   ** data from the memory mapping using memcpy().  */
35673   if( offset<pFile->mmapSize ){
35674     if( offset+amt <= pFile->mmapSize ){
35675       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
35676       OSTRACE(("READ-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
35677                osGetCurrentProcessId(), pFile, pFile->h));
35678       return SQLITE_OK;
35679     }else{
35680       int nCopy = (int)(pFile->mmapSize - offset);
35681       memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
35682       pBuf = &((u8 *)pBuf)[nCopy];
35683       amt -= nCopy;
35684       offset += nCopy;
35685     }
35686   }
35687 #endif
35688
35689 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
35690   if( winSeekFile(pFile, offset) ){
35691     OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
35692              osGetCurrentProcessId(), pFile, pFile->h));
35693     return SQLITE_FULL;
35694   }
35695   while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
35696 #else
35697   memset(&overlapped, 0, sizeof(OVERLAPPED));
35698   overlapped.Offset = (LONG)(offset & 0xffffffff);
35699   overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
35700   while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
35701          osGetLastError()!=ERROR_HANDLE_EOF ){
35702 #endif
35703     DWORD lastErrno;
35704     if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
35705     pFile->lastErrno = lastErrno;
35706     OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_READ\n",
35707              osGetCurrentProcessId(), pFile, pFile->h));
35708     return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
35709                        "winRead", pFile->zPath);
35710   }
35711   winLogIoerr(nRetry, __LINE__);
35712   if( nRead<(DWORD)amt ){
35713     /* Unread parts of the buffer must be zero-filled */
35714     memset(&((char*)pBuf)[nRead], 0, amt-nRead);
35715     OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_SHORT_READ\n",
35716              osGetCurrentProcessId(), pFile, pFile->h));
35717     return SQLITE_IOERR_SHORT_READ;
35718   }
35719
35720   OSTRACE(("READ pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
35721            osGetCurrentProcessId(), pFile, pFile->h));
35722   return SQLITE_OK;
35723 }
35724
35725 /*
35726 ** Write data from a buffer into a file.  Return SQLITE_OK on success
35727 ** or some other error code on failure.
35728 */
35729 static int winWrite(
35730   sqlite3_file *id,               /* File to write into */
35731   const void *pBuf,               /* The bytes to be written */
35732   int amt,                        /* Number of bytes to write */
35733   sqlite3_int64 offset            /* Offset into the file to begin writing at */
35734 ){
35735   int rc = 0;                     /* True if error has occurred, else false */
35736   winFile *pFile = (winFile*)id;  /* File handle */
35737   int nRetry = 0;                 /* Number of retries */
35738
35739   assert( amt>0 );
35740   assert( pFile );
35741   SimulateIOError(return SQLITE_IOERR_WRITE);
35742   SimulateDiskfullError(return SQLITE_FULL);
35743
35744   OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, buffer=%p, amount=%d, "
35745            "offset=%lld, lock=%d\n", osGetCurrentProcessId(), pFile,
35746            pFile->h, pBuf, amt, offset, pFile->locktype));
35747
35748 #if SQLITE_MAX_MMAP_SIZE>0
35749   /* Deal with as much of this write request as possible by transfering
35750   ** data from the memory mapping using memcpy().  */
35751   if( offset<pFile->mmapSize ){
35752     if( offset+amt <= pFile->mmapSize ){
35753       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
35754       OSTRACE(("WRITE-MMAP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
35755                osGetCurrentProcessId(), pFile, pFile->h));
35756       return SQLITE_OK;
35757     }else{
35758       int nCopy = (int)(pFile->mmapSize - offset);
35759       memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
35760       pBuf = &((u8 *)pBuf)[nCopy];
35761       amt -= nCopy;
35762       offset += nCopy;
35763     }
35764   }
35765 #endif
35766
35767 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
35768   rc = winSeekFile(pFile, offset);
35769   if( rc==0 ){
35770 #else
35771   {
35772 #endif
35773 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
35774     OVERLAPPED overlapped;        /* The offset for WriteFile. */
35775 #endif
35776     u8 *aRem = (u8 *)pBuf;        /* Data yet to be written */
35777     int nRem = amt;               /* Number of bytes yet to be written */
35778     DWORD nWrite;                 /* Bytes written by each WriteFile() call */
35779     DWORD lastErrno = NO_ERROR;   /* Value returned by GetLastError() */
35780
35781 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
35782     memset(&overlapped, 0, sizeof(OVERLAPPED));
35783     overlapped.Offset = (LONG)(offset & 0xffffffff);
35784     overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
35785 #endif
35786
35787     while( nRem>0 ){
35788 #if SQLITE_OS_WINCE || defined(SQLITE_WIN32_NO_OVERLAPPED)
35789       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
35790 #else
35791       if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
35792 #endif
35793         if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
35794         break;
35795       }
35796       assert( nWrite==0 || nWrite<=(DWORD)nRem );
35797       if( nWrite==0 || nWrite>(DWORD)nRem ){
35798         lastErrno = osGetLastError();
35799         break;
35800       }
35801 #if !SQLITE_OS_WINCE && !defined(SQLITE_WIN32_NO_OVERLAPPED)
35802       offset += nWrite;
35803       overlapped.Offset = (LONG)(offset & 0xffffffff);
35804       overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
35805 #endif
35806       aRem += nWrite;
35807       nRem -= nWrite;
35808     }
35809     if( nRem>0 ){
35810       pFile->lastErrno = lastErrno;
35811       rc = 1;
35812     }
35813   }
35814
35815   if( rc ){
35816     if(   ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
35817        || ( pFile->lastErrno==ERROR_DISK_FULL )){
35818       OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_FULL\n",
35819                osGetCurrentProcessId(), pFile, pFile->h));
35820       return winLogError(SQLITE_FULL, pFile->lastErrno,
35821                          "winWrite1", pFile->zPath);
35822     }
35823     OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_WRITE\n",
35824              osGetCurrentProcessId(), pFile, pFile->h));
35825     return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
35826                        "winWrite2", pFile->zPath);
35827   }else{
35828     winLogIoerr(nRetry, __LINE__);
35829   }
35830   OSTRACE(("WRITE pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
35831            osGetCurrentProcessId(), pFile, pFile->h));
35832   return SQLITE_OK;
35833 }
35834
35835 /*
35836 ** Truncate an open file to a specified size
35837 */
35838 static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
35839   winFile *pFile = (winFile*)id;  /* File handle object */
35840   int rc = SQLITE_OK;             /* Return code for this function */
35841   DWORD lastErrno;
35842
35843   assert( pFile );
35844   SimulateIOError(return SQLITE_IOERR_TRUNCATE);
35845   OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, size=%lld, lock=%d\n",
35846            osGetCurrentProcessId(), pFile, pFile->h, nByte, pFile->locktype));
35847
35848   /* If the user has configured a chunk-size for this file, truncate the
35849   ** file so that it consists of an integer number of chunks (i.e. the
35850   ** actual file size after the operation may be larger than the requested
35851   ** size).
35852   */
35853   if( pFile->szChunk>0 ){
35854     nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
35855   }
35856
35857   /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
35858   if( winSeekFile(pFile, nByte) ){
35859     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
35860                      "winTruncate1", pFile->zPath);
35861   }else if( 0==osSetEndOfFile(pFile->h) &&
35862             ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
35863     pFile->lastErrno = lastErrno;
35864     rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
35865                      "winTruncate2", pFile->zPath);
35866   }
35867
35868 #if SQLITE_MAX_MMAP_SIZE>0
35869   /* If the file was truncated to a size smaller than the currently
35870   ** mapped region, reduce the effective mapping size as well. SQLite will
35871   ** use read() and write() to access data beyond this point from now on.
35872   */
35873   if( pFile->pMapRegion && nByte<pFile->mmapSize ){
35874     pFile->mmapSize = nByte;
35875   }
35876 #endif
35877
35878   OSTRACE(("TRUNCATE pid=%lu, pFile=%p, file=%p, rc=%s\n",
35879            osGetCurrentProcessId(), pFile, pFile->h, sqlite3ErrName(rc)));
35880   return rc;
35881 }
35882
35883 #ifdef SQLITE_TEST
35884 /*
35885 ** Count the number of fullsyncs and normal syncs.  This is used to test
35886 ** that syncs and fullsyncs are occuring at the right times.
35887 */
35888 SQLITE_API int sqlite3_sync_count = 0;
35889 SQLITE_API int sqlite3_fullsync_count = 0;
35890 #endif
35891
35892 /*
35893 ** Make sure all writes to a particular file are committed to disk.
35894 */
35895 static int winSync(sqlite3_file *id, int flags){
35896 #ifndef SQLITE_NO_SYNC
35897   /*
35898   ** Used only when SQLITE_NO_SYNC is not defined.
35899    */
35900   BOOL rc;
35901 #endif
35902 #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
35903     (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
35904   /*
35905   ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
35906   ** OSTRACE() macros.
35907    */
35908   winFile *pFile = (winFile*)id;
35909 #else
35910   UNUSED_PARAMETER(id);
35911 #endif
35912
35913   assert( pFile );
35914   /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
35915   assert((flags&0x0F)==SQLITE_SYNC_NORMAL
35916       || (flags&0x0F)==SQLITE_SYNC_FULL
35917   );
35918
35919   /* Unix cannot, but some systems may return SQLITE_FULL from here. This
35920   ** line is to test that doing so does not cause any problems.
35921   */
35922   SimulateDiskfullError( return SQLITE_FULL );
35923
35924   OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, flags=%x, lock=%d\n",
35925            osGetCurrentProcessId(), pFile, pFile->h, flags,
35926            pFile->locktype));
35927
35928 #ifndef SQLITE_TEST
35929   UNUSED_PARAMETER(flags);
35930 #else
35931   if( (flags&0x0F)==SQLITE_SYNC_FULL ){
35932     sqlite3_fullsync_count++;
35933   }
35934   sqlite3_sync_count++;
35935 #endif
35936
35937   /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
35938   ** no-op
35939   */
35940 #ifdef SQLITE_NO_SYNC
35941   OSTRACE(("SYNC-NOP pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
35942            osGetCurrentProcessId(), pFile, pFile->h));
35943   return SQLITE_OK;
35944 #else
35945 #if SQLITE_MAX_MMAP_SIZE>0
35946   if( pFile->pMapRegion ){
35947     if( osFlushViewOfFile(pFile->pMapRegion, 0) ){
35948       OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
35949                "rc=SQLITE_OK\n", osGetCurrentProcessId(),
35950                pFile, pFile->pMapRegion));
35951     }else{
35952       pFile->lastErrno = osGetLastError();
35953       OSTRACE(("SYNC-MMAP pid=%lu, pFile=%p, pMapRegion=%p, "
35954                "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(),
35955                pFile, pFile->pMapRegion));
35956       return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
35957                          "winSync1", pFile->zPath);
35958     }
35959   }
35960 #endif
35961   rc = osFlushFileBuffers(pFile->h);
35962   SimulateIOError( rc=FALSE );
35963   if( rc ){
35964     OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_OK\n",
35965              osGetCurrentProcessId(), pFile, pFile->h));
35966     return SQLITE_OK;
35967   }else{
35968     pFile->lastErrno = osGetLastError();
35969     OSTRACE(("SYNC pid=%lu, pFile=%p, file=%p, rc=SQLITE_IOERR_FSYNC\n",
35970              osGetCurrentProcessId(), pFile, pFile->h));
35971     return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
35972                        "winSync2", pFile->zPath);
35973   }
35974 #endif
35975 }
35976
35977 /*
35978 ** Determine the current size of a file in bytes
35979 */
35980 static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
35981   winFile *pFile = (winFile*)id;
35982   int rc = SQLITE_OK;
35983
35984   assert( id!=0 );
35985   assert( pSize!=0 );
35986   SimulateIOError(return SQLITE_IOERR_FSTAT);
35987   OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
35988
35989 #if SQLITE_OS_WINRT
35990   {
35991     FILE_STANDARD_INFO info;
35992     if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
35993                                      &info, sizeof(info)) ){
35994       *pSize = info.EndOfFile.QuadPart;
35995     }else{
35996       pFile->lastErrno = osGetLastError();
35997       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
35998                        "winFileSize", pFile->zPath);
35999     }
36000   }
36001 #else
36002   {
36003     DWORD upperBits;
36004     DWORD lowerBits;
36005     DWORD lastErrno;
36006
36007     lowerBits = osGetFileSize(pFile->h, &upperBits);
36008     *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
36009     if(   (lowerBits == INVALID_FILE_SIZE)
36010        && ((lastErrno = osGetLastError())!=NO_ERROR) ){
36011       pFile->lastErrno = lastErrno;
36012       rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
36013                        "winFileSize", pFile->zPath);
36014     }
36015   }
36016 #endif
36017   OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
36018            pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
36019   return rc;
36020 }
36021
36022 /*
36023 ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
36024 */
36025 #ifndef LOCKFILE_FAIL_IMMEDIATELY
36026 # define LOCKFILE_FAIL_IMMEDIATELY 1
36027 #endif
36028
36029 #ifndef LOCKFILE_EXCLUSIVE_LOCK
36030 # define LOCKFILE_EXCLUSIVE_LOCK 2
36031 #endif
36032
36033 /*
36034 ** Historically, SQLite has used both the LockFile and LockFileEx functions.
36035 ** When the LockFile function was used, it was always expected to fail
36036 ** immediately if the lock could not be obtained.  Also, it always expected to
36037 ** obtain an exclusive lock.  These flags are used with the LockFileEx function
36038 ** and reflect those expectations; therefore, they should not be changed.
36039 */
36040 #ifndef SQLITE_LOCKFILE_FLAGS
36041 # define SQLITE_LOCKFILE_FLAGS   (LOCKFILE_FAIL_IMMEDIATELY | \
36042                                   LOCKFILE_EXCLUSIVE_LOCK)
36043 #endif
36044
36045 /*
36046 ** Currently, SQLite never calls the LockFileEx function without wanting the
36047 ** call to fail immediately if the lock cannot be obtained.
36048 */
36049 #ifndef SQLITE_LOCKFILEEX_FLAGS
36050 # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
36051 #endif
36052
36053 /*
36054 ** Acquire a reader lock.
36055 ** Different API routines are called depending on whether or not this
36056 ** is Win9x or WinNT.
36057 */
36058 static int winGetReadLock(winFile *pFile){
36059   int res;
36060   OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
36061   if( osIsNT() ){
36062 #if SQLITE_OS_WINCE
36063     /*
36064     ** NOTE: Windows CE is handled differently here due its lack of the Win32
36065     **       API LockFileEx.
36066     */
36067     res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
36068 #else
36069     res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
36070                       SHARED_SIZE, 0);
36071 #endif
36072   }
36073 #ifdef SQLITE_WIN32_HAS_ANSI
36074   else{
36075     int lk;
36076     sqlite3_randomness(sizeof(lk), &lk);
36077     pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
36078     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
36079                       SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
36080   }
36081 #endif
36082   if( res == 0 ){
36083     pFile->lastErrno = osGetLastError();
36084     /* No need to log a failure to lock */
36085   }
36086   OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
36087   return res;
36088 }
36089
36090 /*
36091 ** Undo a readlock
36092 */
36093 static int winUnlockReadLock(winFile *pFile){
36094   int res;
36095   DWORD lastErrno;
36096   OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
36097   if( osIsNT() ){
36098     res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
36099   }
36100 #ifdef SQLITE_WIN32_HAS_ANSI
36101   else{
36102     res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
36103   }
36104 #endif
36105   if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
36106     pFile->lastErrno = lastErrno;
36107     winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
36108                 "winUnlockReadLock", pFile->zPath);
36109   }
36110   OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
36111   return res;
36112 }
36113
36114 /*
36115 ** Lock the file with the lock specified by parameter locktype - one
36116 ** of the following:
36117 **
36118 **     (1) SHARED_LOCK
36119 **     (2) RESERVED_LOCK
36120 **     (3) PENDING_LOCK
36121 **     (4) EXCLUSIVE_LOCK
36122 **
36123 ** Sometimes when requesting one lock state, additional lock states
36124 ** are inserted in between.  The locking might fail on one of the later
36125 ** transitions leaving the lock state different from what it started but
36126 ** still short of its goal.  The following chart shows the allowed
36127 ** transitions and the inserted intermediate states:
36128 **
36129 **    UNLOCKED -> SHARED
36130 **    SHARED -> RESERVED
36131 **    SHARED -> (PENDING) -> EXCLUSIVE
36132 **    RESERVED -> (PENDING) -> EXCLUSIVE
36133 **    PENDING -> EXCLUSIVE
36134 **
36135 ** This routine will only increase a lock.  The winUnlock() routine
36136 ** erases all locks at once and returns us immediately to locking level 0.
36137 ** It is not possible to lower the locking level one step at a time.  You
36138 ** must go straight to locking level 0.
36139 */
36140 static int winLock(sqlite3_file *id, int locktype){
36141   int rc = SQLITE_OK;    /* Return code from subroutines */
36142   int res = 1;           /* Result of a Windows lock call */
36143   int newLocktype;       /* Set pFile->locktype to this value before exiting */
36144   int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
36145   winFile *pFile = (winFile*)id;
36146   DWORD lastErrno = NO_ERROR;
36147
36148   assert( id!=0 );
36149   OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
36150            pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
36151
36152   /* If there is already a lock of this type or more restrictive on the
36153   ** OsFile, do nothing. Don't use the end_lock: exit path, as
36154   ** sqlite3OsEnterMutex() hasn't been called yet.
36155   */
36156   if( pFile->locktype>=locktype ){
36157     OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
36158     return SQLITE_OK;
36159   }
36160
36161   /* Make sure the locking sequence is correct
36162   */
36163   assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
36164   assert( locktype!=PENDING_LOCK );
36165   assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
36166
36167   /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
36168   ** a SHARED lock.  If we are acquiring a SHARED lock, the acquisition of
36169   ** the PENDING_LOCK byte is temporary.
36170   */
36171   newLocktype = pFile->locktype;
36172   if(   (pFile->locktype==NO_LOCK)
36173      || (   (locktype==EXCLUSIVE_LOCK)
36174          && (pFile->locktype==RESERVED_LOCK))
36175   ){
36176     int cnt = 3;
36177     while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
36178                                          PENDING_BYTE, 0, 1, 0))==0 ){
36179       /* Try 3 times to get the pending lock.  This is needed to work
36180       ** around problems caused by indexing and/or anti-virus software on
36181       ** Windows systems.
36182       ** If you are using this code as a model for alternative VFSes, do not
36183       ** copy this retry logic.  It is a hack intended for Windows only.
36184       */
36185       lastErrno = osGetLastError();
36186       OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
36187                pFile->h, cnt, res));
36188       if( lastErrno==ERROR_INVALID_HANDLE ){
36189         pFile->lastErrno = lastErrno;
36190         rc = SQLITE_IOERR_LOCK;
36191         OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
36192                  pFile->h, cnt, sqlite3ErrName(rc)));
36193         return rc;
36194       }
36195       if( cnt ) sqlite3_win32_sleep(1);
36196     }
36197     gotPendingLock = res;
36198     if( !res ){
36199       lastErrno = osGetLastError();
36200     }
36201   }
36202
36203   /* Acquire a shared lock
36204   */
36205   if( locktype==SHARED_LOCK && res ){
36206     assert( pFile->locktype==NO_LOCK );
36207     res = winGetReadLock(pFile);
36208     if( res ){
36209       newLocktype = SHARED_LOCK;
36210     }else{
36211       lastErrno = osGetLastError();
36212     }
36213   }
36214
36215   /* Acquire a RESERVED lock
36216   */
36217   if( locktype==RESERVED_LOCK && res ){
36218     assert( pFile->locktype==SHARED_LOCK );
36219     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
36220     if( res ){
36221       newLocktype = RESERVED_LOCK;
36222     }else{
36223       lastErrno = osGetLastError();
36224     }
36225   }
36226
36227   /* Acquire a PENDING lock
36228   */
36229   if( locktype==EXCLUSIVE_LOCK && res ){
36230     newLocktype = PENDING_LOCK;
36231     gotPendingLock = 0;
36232   }
36233
36234   /* Acquire an EXCLUSIVE lock
36235   */
36236   if( locktype==EXCLUSIVE_LOCK && res ){
36237     assert( pFile->locktype>=SHARED_LOCK );
36238     res = winUnlockReadLock(pFile);
36239     res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
36240                       SHARED_SIZE, 0);
36241     if( res ){
36242       newLocktype = EXCLUSIVE_LOCK;
36243     }else{
36244       lastErrno = osGetLastError();
36245       winGetReadLock(pFile);
36246     }
36247   }
36248
36249   /* If we are holding a PENDING lock that ought to be released, then
36250   ** release it now.
36251   */
36252   if( gotPendingLock && locktype==SHARED_LOCK ){
36253     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
36254   }
36255
36256   /* Update the state of the lock has held in the file descriptor then
36257   ** return the appropriate result code.
36258   */
36259   if( res ){
36260     rc = SQLITE_OK;
36261   }else{
36262     pFile->lastErrno = lastErrno;
36263     rc = SQLITE_BUSY;
36264     OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
36265              pFile->h, locktype, newLocktype));
36266   }
36267   pFile->locktype = (u8)newLocktype;
36268   OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
36269            pFile->h, pFile->locktype, sqlite3ErrName(rc)));
36270   return rc;
36271 }
36272
36273 /*
36274 ** This routine checks if there is a RESERVED lock held on the specified
36275 ** file by this or any other process. If such a lock is held, return
36276 ** non-zero, otherwise zero.
36277 */
36278 static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
36279   int res;
36280   winFile *pFile = (winFile*)id;
36281
36282   SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
36283   OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
36284
36285   assert( id!=0 );
36286   if( pFile->locktype>=RESERVED_LOCK ){
36287     res = 1;
36288     OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
36289   }else{
36290     res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
36291     if( res ){
36292       winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
36293     }
36294     res = !res;
36295     OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
36296   }
36297   *pResOut = res;
36298   OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
36299            pFile->h, pResOut, *pResOut));
36300   return SQLITE_OK;
36301 }
36302
36303 /*
36304 ** Lower the locking level on file descriptor id to locktype.  locktype
36305 ** must be either NO_LOCK or SHARED_LOCK.
36306 **
36307 ** If the locking level of the file descriptor is already at or below
36308 ** the requested locking level, this routine is a no-op.
36309 **
36310 ** It is not possible for this routine to fail if the second argument
36311 ** is NO_LOCK.  If the second argument is SHARED_LOCK then this routine
36312 ** might return SQLITE_IOERR;
36313 */
36314 static int winUnlock(sqlite3_file *id, int locktype){
36315   int type;
36316   winFile *pFile = (winFile*)id;
36317   int rc = SQLITE_OK;
36318   assert( pFile!=0 );
36319   assert( locktype<=SHARED_LOCK );
36320   OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
36321            pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
36322   type = pFile->locktype;
36323   if( type>=EXCLUSIVE_LOCK ){
36324     winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
36325     if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
36326       /* This should never happen.  We should always be able to
36327       ** reacquire the read lock */
36328       rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
36329                        "winUnlock", pFile->zPath);
36330     }
36331   }
36332   if( type>=RESERVED_LOCK ){
36333     winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
36334   }
36335   if( locktype==NO_LOCK && type>=SHARED_LOCK ){
36336     winUnlockReadLock(pFile);
36337   }
36338   if( type>=PENDING_LOCK ){
36339     winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
36340   }
36341   pFile->locktype = (u8)locktype;
36342   OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
36343            pFile->h, pFile->locktype, sqlite3ErrName(rc)));
36344   return rc;
36345 }
36346
36347 /*
36348 ** If *pArg is initially negative then this is a query.  Set *pArg to
36349 ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
36350 **
36351 ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
36352 */
36353 static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
36354   if( *pArg<0 ){
36355     *pArg = (pFile->ctrlFlags & mask)!=0;
36356   }else if( (*pArg)==0 ){
36357     pFile->ctrlFlags &= ~mask;
36358   }else{
36359     pFile->ctrlFlags |= mask;
36360   }
36361 }
36362
36363 /* Forward references to VFS helper methods used for temporary files */
36364 static int winGetTempname(sqlite3_vfs *, char **);
36365 static int winIsDir(const void *);
36366 static BOOL winIsDriveLetterAndColon(const char *);
36367
36368 /*
36369 ** Control and query of the open file handle.
36370 */
36371 static int winFileControl(sqlite3_file *id, int op, void *pArg){
36372   winFile *pFile = (winFile*)id;
36373   OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
36374   switch( op ){
36375     case SQLITE_FCNTL_LOCKSTATE: {
36376       *(int*)pArg = pFile->locktype;
36377       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
36378       return SQLITE_OK;
36379     }
36380     case SQLITE_LAST_ERRNO: {
36381       *(int*)pArg = (int)pFile->lastErrno;
36382       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
36383       return SQLITE_OK;
36384     }
36385     case SQLITE_FCNTL_CHUNK_SIZE: {
36386       pFile->szChunk = *(int *)pArg;
36387       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
36388       return SQLITE_OK;
36389     }
36390     case SQLITE_FCNTL_SIZE_HINT: {
36391       if( pFile->szChunk>0 ){
36392         sqlite3_int64 oldSz;
36393         int rc = winFileSize(id, &oldSz);
36394         if( rc==SQLITE_OK ){
36395           sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
36396           if( newSz>oldSz ){
36397             SimulateIOErrorBenign(1);
36398             rc = winTruncate(id, newSz);
36399             SimulateIOErrorBenign(0);
36400           }
36401         }
36402         OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
36403         return rc;
36404       }
36405       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
36406       return SQLITE_OK;
36407     }
36408     case SQLITE_FCNTL_PERSIST_WAL: {
36409       winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
36410       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
36411       return SQLITE_OK;
36412     }
36413     case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
36414       winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
36415       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
36416       return SQLITE_OK;
36417     }
36418     case SQLITE_FCNTL_VFSNAME: {
36419       *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
36420       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
36421       return SQLITE_OK;
36422     }
36423     case SQLITE_FCNTL_WIN32_AV_RETRY: {
36424       int *a = (int*)pArg;
36425       if( a[0]>0 ){
36426         winIoerrRetry = a[0];
36427       }else{
36428         a[0] = winIoerrRetry;
36429       }
36430       if( a[1]>0 ){
36431         winIoerrRetryDelay = a[1];
36432       }else{
36433         a[1] = winIoerrRetryDelay;
36434       }
36435       OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
36436       return SQLITE_OK;
36437     }
36438 #ifdef SQLITE_TEST
36439     case SQLITE_FCNTL_WIN32_SET_HANDLE: {
36440       LPHANDLE phFile = (LPHANDLE)pArg;
36441       HANDLE hOldFile = pFile->h;
36442       pFile->h = *phFile;
36443       *phFile = hOldFile;
36444       OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
36445                hOldFile, pFile->h));
36446       return SQLITE_OK;
36447     }
36448 #endif
36449     case SQLITE_FCNTL_TEMPFILENAME: {
36450       char *zTFile = 0;
36451       int rc = winGetTempname(pFile->pVfs, &zTFile);
36452       if( rc==SQLITE_OK ){
36453         *(char**)pArg = zTFile;
36454       }
36455       OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
36456       return rc;
36457     }
36458 #if SQLITE_MAX_MMAP_SIZE>0
36459     case SQLITE_FCNTL_MMAP_SIZE: {
36460       i64 newLimit = *(i64*)pArg;
36461       int rc = SQLITE_OK;
36462       if( newLimit>sqlite3GlobalConfig.mxMmap ){
36463         newLimit = sqlite3GlobalConfig.mxMmap;
36464       }
36465       *(i64*)pArg = pFile->mmapSizeMax;
36466       if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
36467         pFile->mmapSizeMax = newLimit;
36468         if( pFile->mmapSize>0 ){
36469           winUnmapfile(pFile);
36470           rc = winMapfile(pFile, -1);
36471         }
36472       }
36473       OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
36474       return rc;
36475     }
36476 #endif
36477   }
36478   OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
36479   return SQLITE_NOTFOUND;
36480 }
36481
36482 /*
36483 ** Return the sector size in bytes of the underlying block device for
36484 ** the specified file. This is almost always 512 bytes, but may be
36485 ** larger for some devices.
36486 **
36487 ** SQLite code assumes this function cannot fail. It also assumes that
36488 ** if two files are created in the same file-system directory (i.e.
36489 ** a database and its journal file) that the sector size will be the
36490 ** same for both.
36491 */
36492 static int winSectorSize(sqlite3_file *id){
36493   (void)id;
36494   return SQLITE_DEFAULT_SECTOR_SIZE;
36495 }
36496
36497 /*
36498 ** Return a vector of device characteristics.
36499 */
36500 static int winDeviceCharacteristics(sqlite3_file *id){
36501   winFile *p = (winFile*)id;
36502   return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
36503          ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
36504 }
36505
36506 /*
36507 ** Windows will only let you create file view mappings
36508 ** on allocation size granularity boundaries.
36509 ** During sqlite3_os_init() we do a GetSystemInfo()
36510 ** to get the granularity size.
36511 */
36512 static SYSTEM_INFO winSysInfo;
36513
36514 #ifndef SQLITE_OMIT_WAL
36515
36516 /*
36517 ** Helper functions to obtain and relinquish the global mutex. The
36518 ** global mutex is used to protect the winLockInfo objects used by
36519 ** this file, all of which may be shared by multiple threads.
36520 **
36521 ** Function winShmMutexHeld() is used to assert() that the global mutex
36522 ** is held when required. This function is only used as part of assert()
36523 ** statements. e.g.
36524 **
36525 **   winShmEnterMutex()
36526 **     assert( winShmMutexHeld() );
36527 **   winShmLeaveMutex()
36528 */
36529 static void winShmEnterMutex(void){
36530   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
36531 }
36532 static void winShmLeaveMutex(void){
36533   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
36534 }
36535 #ifndef NDEBUG
36536 static int winShmMutexHeld(void) {
36537   return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
36538 }
36539 #endif
36540
36541 /*
36542 ** Object used to represent a single file opened and mmapped to provide
36543 ** shared memory.  When multiple threads all reference the same
36544 ** log-summary, each thread has its own winFile object, but they all
36545 ** point to a single instance of this object.  In other words, each
36546 ** log-summary is opened only once per process.
36547 **
36548 ** winShmMutexHeld() must be true when creating or destroying
36549 ** this object or while reading or writing the following fields:
36550 **
36551 **      nRef
36552 **      pNext
36553 **
36554 ** The following fields are read-only after the object is created:
36555 **
36556 **      fid
36557 **      zFilename
36558 **
36559 ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
36560 ** winShmMutexHeld() is true when reading or writing any other field
36561 ** in this structure.
36562 **
36563 */
36564 struct winShmNode {
36565   sqlite3_mutex *mutex;      /* Mutex to access this object */
36566   char *zFilename;           /* Name of the file */
36567   winFile hFile;             /* File handle from winOpen */
36568
36569   int szRegion;              /* Size of shared-memory regions */
36570   int nRegion;               /* Size of array apRegion */
36571   struct ShmRegion {
36572     HANDLE hMap;             /* File handle from CreateFileMapping */
36573     void *pMap;
36574   } *aRegion;
36575   DWORD lastErrno;           /* The Windows errno from the last I/O error */
36576
36577   int nRef;                  /* Number of winShm objects pointing to this */
36578   winShm *pFirst;            /* All winShm objects pointing to this */
36579   winShmNode *pNext;         /* Next in list of all winShmNode objects */
36580 #ifdef SQLITE_DEBUG
36581   u8 nextShmId;              /* Next available winShm.id value */
36582 #endif
36583 };
36584
36585 /*
36586 ** A global array of all winShmNode objects.
36587 **
36588 ** The winShmMutexHeld() must be true while reading or writing this list.
36589 */
36590 static winShmNode *winShmNodeList = 0;
36591
36592 /*
36593 ** Structure used internally by this VFS to record the state of an
36594 ** open shared memory connection.
36595 **
36596 ** The following fields are initialized when this object is created and
36597 ** are read-only thereafter:
36598 **
36599 **    winShm.pShmNode
36600 **    winShm.id
36601 **
36602 ** All other fields are read/write.  The winShm.pShmNode->mutex must be held
36603 ** while accessing any read/write fields.
36604 */
36605 struct winShm {
36606   winShmNode *pShmNode;      /* The underlying winShmNode object */
36607   winShm *pNext;             /* Next winShm with the same winShmNode */
36608   u8 hasMutex;               /* True if holding the winShmNode mutex */
36609   u16 sharedMask;            /* Mask of shared locks held */
36610   u16 exclMask;              /* Mask of exclusive locks held */
36611 #ifdef SQLITE_DEBUG
36612   u8 id;                     /* Id of this connection with its winShmNode */
36613 #endif
36614 };
36615
36616 /*
36617 ** Constants used for locking
36618 */
36619 #define WIN_SHM_BASE   ((22+SQLITE_SHM_NLOCK)*4)        /* first lock byte */
36620 #define WIN_SHM_DMS    (WIN_SHM_BASE+SQLITE_SHM_NLOCK)  /* deadman switch */
36621
36622 /*
36623 ** Apply advisory locks for all n bytes beginning at ofst.
36624 */
36625 #define _SHM_UNLCK  1
36626 #define _SHM_RDLCK  2
36627 #define _SHM_WRLCK  3
36628 static int winShmSystemLock(
36629   winShmNode *pFile,    /* Apply locks to this open shared-memory segment */
36630   int lockType,         /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
36631   int ofst,             /* Offset to first byte to be locked/unlocked */
36632   int nByte             /* Number of bytes to lock or unlock */
36633 ){
36634   int rc = 0;           /* Result code form Lock/UnlockFileEx() */
36635
36636   /* Access to the winShmNode object is serialized by the caller */
36637   assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
36638
36639   OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
36640            pFile->hFile.h, lockType, ofst, nByte));
36641
36642   /* Release/Acquire the system-level lock */
36643   if( lockType==_SHM_UNLCK ){
36644     rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
36645   }else{
36646     /* Initialize the locking parameters */
36647     DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
36648     if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
36649     rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
36650   }
36651
36652   if( rc!= 0 ){
36653     rc = SQLITE_OK;
36654   }else{
36655     pFile->lastErrno =  osGetLastError();
36656     rc = SQLITE_BUSY;
36657   }
36658
36659   OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
36660            pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
36661            "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
36662
36663   return rc;
36664 }
36665
36666 /* Forward references to VFS methods */
36667 static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
36668 static int winDelete(sqlite3_vfs *,const char*,int);
36669
36670 /*
36671 ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
36672 **
36673 ** This is not a VFS shared-memory method; it is a utility function called
36674 ** by VFS shared-memory methods.
36675 */
36676 static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
36677   winShmNode **pp;
36678   winShmNode *p;
36679   assert( winShmMutexHeld() );
36680   OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
36681            osGetCurrentProcessId(), deleteFlag));
36682   pp = &winShmNodeList;
36683   while( (p = *pp)!=0 ){
36684     if( p->nRef==0 ){
36685       int i;
36686       if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
36687       for(i=0; i<p->nRegion; i++){
36688         BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
36689         OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
36690                  osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
36691         UNUSED_VARIABLE_VALUE(bRc);
36692         bRc = osCloseHandle(p->aRegion[i].hMap);
36693         OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
36694                  osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
36695         UNUSED_VARIABLE_VALUE(bRc);
36696       }
36697       if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
36698         SimulateIOErrorBenign(1);
36699         winClose((sqlite3_file *)&p->hFile);
36700         SimulateIOErrorBenign(0);
36701       }
36702       if( deleteFlag ){
36703         SimulateIOErrorBenign(1);
36704         sqlite3BeginBenignMalloc();
36705         winDelete(pVfs, p->zFilename, 0);
36706         sqlite3EndBenignMalloc();
36707         SimulateIOErrorBenign(0);
36708       }
36709       *pp = p->pNext;
36710       sqlite3_free(p->aRegion);
36711       sqlite3_free(p);
36712     }else{
36713       pp = &p->pNext;
36714     }
36715   }
36716 }
36717
36718 /*
36719 ** Open the shared-memory area associated with database file pDbFd.
36720 **
36721 ** When opening a new shared-memory file, if no other instances of that
36722 ** file are currently open, in this process or in other processes, then
36723 ** the file must be truncated to zero length or have its header cleared.
36724 */
36725 static int winOpenSharedMemory(winFile *pDbFd){
36726   struct winShm *p;                  /* The connection to be opened */
36727   struct winShmNode *pShmNode = 0;   /* The underlying mmapped file */
36728   int rc;                            /* Result code */
36729   struct winShmNode *pNew;           /* Newly allocated winShmNode */
36730   int nName;                         /* Size of zName in bytes */
36731
36732   assert( pDbFd->pShm==0 );    /* Not previously opened */
36733
36734   /* Allocate space for the new sqlite3_shm object.  Also speculatively
36735   ** allocate space for a new winShmNode and filename.
36736   */
36737   p = sqlite3MallocZero( sizeof(*p) );
36738   if( p==0 ) return SQLITE_IOERR_NOMEM;
36739   nName = sqlite3Strlen30(pDbFd->zPath);
36740   pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
36741   if( pNew==0 ){
36742     sqlite3_free(p);
36743     return SQLITE_IOERR_NOMEM;
36744   }
36745   pNew->zFilename = (char*)&pNew[1];
36746   sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
36747   sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
36748
36749   /* Look to see if there is an existing winShmNode that can be used.
36750   ** If no matching winShmNode currently exists, create a new one.
36751   */
36752   winShmEnterMutex();
36753   for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
36754     /* TBD need to come up with better match here.  Perhaps
36755     ** use FILE_ID_BOTH_DIR_INFO Structure.
36756     */
36757     if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
36758   }
36759   if( pShmNode ){
36760     sqlite3_free(pNew);
36761   }else{
36762     pShmNode = pNew;
36763     pNew = 0;
36764     ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
36765     pShmNode->pNext = winShmNodeList;
36766     winShmNodeList = pShmNode;
36767
36768     pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
36769     if( pShmNode->mutex==0 ){
36770       rc = SQLITE_IOERR_NOMEM;
36771       goto shm_open_err;
36772     }
36773
36774     rc = winOpen(pDbFd->pVfs,
36775                  pShmNode->zFilename,             /* Name of the file (UTF-8) */
36776                  (sqlite3_file*)&pShmNode->hFile,  /* File handle here */
36777                  SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
36778                  0);
36779     if( SQLITE_OK!=rc ){
36780       goto shm_open_err;
36781     }
36782
36783     /* Check to see if another process is holding the dead-man switch.
36784     ** If not, truncate the file to zero length.
36785     */
36786     if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
36787       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
36788       if( rc!=SQLITE_OK ){
36789         rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
36790                          "winOpenShm", pDbFd->zPath);
36791       }
36792     }
36793     if( rc==SQLITE_OK ){
36794       winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
36795       rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
36796     }
36797     if( rc ) goto shm_open_err;
36798   }
36799
36800   /* Make the new connection a child of the winShmNode */
36801   p->pShmNode = pShmNode;
36802 #ifdef SQLITE_DEBUG
36803   p->id = pShmNode->nextShmId++;
36804 #endif
36805   pShmNode->nRef++;
36806   pDbFd->pShm = p;
36807   winShmLeaveMutex();
36808
36809   /* The reference count on pShmNode has already been incremented under
36810   ** the cover of the winShmEnterMutex() mutex and the pointer from the
36811   ** new (struct winShm) object to the pShmNode has been set. All that is
36812   ** left to do is to link the new object into the linked list starting
36813   ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
36814   ** mutex.
36815   */
36816   sqlite3_mutex_enter(pShmNode->mutex);
36817   p->pNext = pShmNode->pFirst;
36818   pShmNode->pFirst = p;
36819   sqlite3_mutex_leave(pShmNode->mutex);
36820   return SQLITE_OK;
36821
36822   /* Jump here on any error */
36823 shm_open_err:
36824   winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
36825   winShmPurge(pDbFd->pVfs, 0);      /* This call frees pShmNode if required */
36826   sqlite3_free(p);
36827   sqlite3_free(pNew);
36828   winShmLeaveMutex();
36829   return rc;
36830 }
36831
36832 /*
36833 ** Close a connection to shared-memory.  Delete the underlying
36834 ** storage if deleteFlag is true.
36835 */
36836 static int winShmUnmap(
36837   sqlite3_file *fd,          /* Database holding shared memory */
36838   int deleteFlag             /* Delete after closing if true */
36839 ){
36840   winFile *pDbFd;       /* Database holding shared-memory */
36841   winShm *p;            /* The connection to be closed */
36842   winShmNode *pShmNode; /* The underlying shared-memory file */
36843   winShm **pp;          /* For looping over sibling connections */
36844
36845   pDbFd = (winFile*)fd;
36846   p = pDbFd->pShm;
36847   if( p==0 ) return SQLITE_OK;
36848   pShmNode = p->pShmNode;
36849
36850   /* Remove connection p from the set of connections associated
36851   ** with pShmNode */
36852   sqlite3_mutex_enter(pShmNode->mutex);
36853   for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
36854   *pp = p->pNext;
36855
36856   /* Free the connection p */
36857   sqlite3_free(p);
36858   pDbFd->pShm = 0;
36859   sqlite3_mutex_leave(pShmNode->mutex);
36860
36861   /* If pShmNode->nRef has reached 0, then close the underlying
36862   ** shared-memory file, too */
36863   winShmEnterMutex();
36864   assert( pShmNode->nRef>0 );
36865   pShmNode->nRef--;
36866   if( pShmNode->nRef==0 ){
36867     winShmPurge(pDbFd->pVfs, deleteFlag);
36868   }
36869   winShmLeaveMutex();
36870
36871   return SQLITE_OK;
36872 }
36873
36874 /*
36875 ** Change the lock state for a shared-memory segment.
36876 */
36877 static int winShmLock(
36878   sqlite3_file *fd,          /* Database file holding the shared memory */
36879   int ofst,                  /* First lock to acquire or release */
36880   int n,                     /* Number of locks to acquire or release */
36881   int flags                  /* What to do with the lock */
36882 ){
36883   winFile *pDbFd = (winFile*)fd;        /* Connection holding shared memory */
36884   winShm *p = pDbFd->pShm;              /* The shared memory being locked */
36885   winShm *pX;                           /* For looping over all siblings */
36886   winShmNode *pShmNode = p->pShmNode;
36887   int rc = SQLITE_OK;                   /* Result code */
36888   u16 mask;                             /* Mask of locks to take or release */
36889
36890   assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
36891   assert( n>=1 );
36892   assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
36893        || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
36894        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
36895        || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
36896   assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
36897
36898   mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
36899   assert( n>1 || mask==(1<<ofst) );
36900   sqlite3_mutex_enter(pShmNode->mutex);
36901   if( flags & SQLITE_SHM_UNLOCK ){
36902     u16 allMask = 0; /* Mask of locks held by siblings */
36903
36904     /* See if any siblings hold this same lock */
36905     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
36906       if( pX==p ) continue;
36907       assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
36908       allMask |= pX->sharedMask;
36909     }
36910
36911     /* Unlock the system-level locks */
36912     if( (mask & allMask)==0 ){
36913       rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
36914     }else{
36915       rc = SQLITE_OK;
36916     }
36917
36918     /* Undo the local locks */
36919     if( rc==SQLITE_OK ){
36920       p->exclMask &= ~mask;
36921       p->sharedMask &= ~mask;
36922     }
36923   }else if( flags & SQLITE_SHM_SHARED ){
36924     u16 allShared = 0;  /* Union of locks held by connections other than "p" */
36925
36926     /* Find out which shared locks are already held by sibling connections.
36927     ** If any sibling already holds an exclusive lock, go ahead and return
36928     ** SQLITE_BUSY.
36929     */
36930     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
36931       if( (pX->exclMask & mask)!=0 ){
36932         rc = SQLITE_BUSY;
36933         break;
36934       }
36935       allShared |= pX->sharedMask;
36936     }
36937
36938     /* Get shared locks at the system level, if necessary */
36939     if( rc==SQLITE_OK ){
36940       if( (allShared & mask)==0 ){
36941         rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
36942       }else{
36943         rc = SQLITE_OK;
36944       }
36945     }
36946
36947     /* Get the local shared locks */
36948     if( rc==SQLITE_OK ){
36949       p->sharedMask |= mask;
36950     }
36951   }else{
36952     /* Make sure no sibling connections hold locks that will block this
36953     ** lock.  If any do, return SQLITE_BUSY right away.
36954     */
36955     for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
36956       if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
36957         rc = SQLITE_BUSY;
36958         break;
36959       }
36960     }
36961
36962     /* Get the exclusive locks at the system level.  Then if successful
36963     ** also mark the local connection as being locked.
36964     */
36965     if( rc==SQLITE_OK ){
36966       rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
36967       if( rc==SQLITE_OK ){
36968         assert( (p->sharedMask & mask)==0 );
36969         p->exclMask |= mask;
36970       }
36971     }
36972   }
36973   sqlite3_mutex_leave(pShmNode->mutex);
36974   OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
36975            osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
36976            sqlite3ErrName(rc)));
36977   return rc;
36978 }
36979
36980 /*
36981 ** Implement a memory barrier or memory fence on shared memory.
36982 **
36983 ** All loads and stores begun before the barrier must complete before
36984 ** any load or store begun after the barrier.
36985 */
36986 static void winShmBarrier(
36987   sqlite3_file *fd          /* Database holding the shared memory */
36988 ){
36989   UNUSED_PARAMETER(fd);
36990   /* MemoryBarrier(); // does not work -- do not know why not */
36991   winShmEnterMutex();
36992   winShmLeaveMutex();
36993 }
36994
36995 /*
36996 ** This function is called to obtain a pointer to region iRegion of the
36997 ** shared-memory associated with the database file fd. Shared-memory regions
36998 ** are numbered starting from zero. Each shared-memory region is szRegion
36999 ** bytes in size.
37000 **
37001 ** If an error occurs, an error code is returned and *pp is set to NULL.
37002 **
37003 ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
37004 ** region has not been allocated (by any client, including one running in a
37005 ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
37006 ** isWrite is non-zero and the requested shared-memory region has not yet
37007 ** been allocated, it is allocated by this function.
37008 **
37009 ** If the shared-memory region has already been allocated or is allocated by
37010 ** this call as described above, then it is mapped into this processes
37011 ** address space (if it is not already), *pp is set to point to the mapped
37012 ** memory and SQLITE_OK returned.
37013 */
37014 static int winShmMap(
37015   sqlite3_file *fd,               /* Handle open on database file */
37016   int iRegion,                    /* Region to retrieve */
37017   int szRegion,                   /* Size of regions */
37018   int isWrite,                    /* True to extend file if necessary */
37019   void volatile **pp              /* OUT: Mapped memory */
37020 ){
37021   winFile *pDbFd = (winFile*)fd;
37022   winShm *pShm = pDbFd->pShm;
37023   winShmNode *pShmNode;
37024   int rc = SQLITE_OK;
37025
37026   if( !pShm ){
37027     rc = winOpenSharedMemory(pDbFd);
37028     if( rc!=SQLITE_OK ) return rc;
37029     pShm = pDbFd->pShm;
37030   }
37031   pShmNode = pShm->pShmNode;
37032
37033   sqlite3_mutex_enter(pShmNode->mutex);
37034   assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
37035
37036   if( pShmNode->nRegion<=iRegion ){
37037     struct ShmRegion *apNew;           /* New aRegion[] array */
37038     int nByte = (iRegion+1)*szRegion;  /* Minimum required file size */
37039     sqlite3_int64 sz;                  /* Current size of wal-index file */
37040
37041     pShmNode->szRegion = szRegion;
37042
37043     /* The requested region is not mapped into this processes address space.
37044     ** Check to see if it has been allocated (i.e. if the wal-index file is
37045     ** large enough to contain the requested region).
37046     */
37047     rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
37048     if( rc!=SQLITE_OK ){
37049       rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
37050                        "winShmMap1", pDbFd->zPath);
37051       goto shmpage_out;
37052     }
37053
37054     if( sz<nByte ){
37055       /* The requested memory region does not exist. If isWrite is set to
37056       ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
37057       **
37058       ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
37059       ** the requested memory region.
37060       */
37061       if( !isWrite ) goto shmpage_out;
37062       rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
37063       if( rc!=SQLITE_OK ){
37064         rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
37065                          "winShmMap2", pDbFd->zPath);
37066         goto shmpage_out;
37067       }
37068     }
37069
37070     /* Map the requested memory region into this processes address space. */
37071     apNew = (struct ShmRegion *)sqlite3_realloc(
37072         pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
37073     );
37074     if( !apNew ){
37075       rc = SQLITE_IOERR_NOMEM;
37076       goto shmpage_out;
37077     }
37078     pShmNode->aRegion = apNew;
37079
37080     while( pShmNode->nRegion<=iRegion ){
37081       HANDLE hMap = NULL;         /* file-mapping handle */
37082       void *pMap = 0;             /* Mapped memory region */
37083
37084 #if SQLITE_OS_WINRT
37085       hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
37086           NULL, PAGE_READWRITE, nByte, NULL
37087       );
37088 #elif defined(SQLITE_WIN32_HAS_WIDE)
37089       hMap = osCreateFileMappingW(pShmNode->hFile.h,
37090           NULL, PAGE_READWRITE, 0, nByte, NULL
37091       );
37092 #elif defined(SQLITE_WIN32_HAS_ANSI)
37093       hMap = osCreateFileMappingA(pShmNode->hFile.h,
37094           NULL, PAGE_READWRITE, 0, nByte, NULL
37095       );
37096 #endif
37097       OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
37098                osGetCurrentProcessId(), pShmNode->nRegion, nByte,
37099                hMap ? "ok" : "failed"));
37100       if( hMap ){
37101         int iOffset = pShmNode->nRegion*szRegion;
37102         int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
37103 #if SQLITE_OS_WINRT
37104         pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
37105             iOffset - iOffsetShift, szRegion + iOffsetShift
37106         );
37107 #else
37108         pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
37109             0, iOffset - iOffsetShift, szRegion + iOffsetShift
37110         );
37111 #endif
37112         OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
37113                  osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
37114                  szRegion, pMap ? "ok" : "failed"));
37115       }
37116       if( !pMap ){
37117         pShmNode->lastErrno = osGetLastError();
37118         rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
37119                          "winShmMap3", pDbFd->zPath);
37120         if( hMap ) osCloseHandle(hMap);
37121         goto shmpage_out;
37122       }
37123
37124       pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
37125       pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
37126       pShmNode->nRegion++;
37127     }
37128   }
37129
37130 shmpage_out:
37131   if( pShmNode->nRegion>iRegion ){
37132     int iOffset = iRegion*szRegion;
37133     int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
37134     char *p = (char *)pShmNode->aRegion[iRegion].pMap;
37135     *pp = (void *)&p[iOffsetShift];
37136   }else{
37137     *pp = 0;
37138   }
37139   sqlite3_mutex_leave(pShmNode->mutex);
37140   return rc;
37141 }
37142
37143 #else
37144 # define winShmMap     0
37145 # define winShmLock    0
37146 # define winShmBarrier 0
37147 # define winShmUnmap   0
37148 #endif /* #ifndef SQLITE_OMIT_WAL */
37149
37150 /*
37151 ** Cleans up the mapped region of the specified file, if any.
37152 */
37153 #if SQLITE_MAX_MMAP_SIZE>0
37154 static int winUnmapfile(winFile *pFile){
37155   assert( pFile!=0 );
37156   OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
37157            "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
37158            osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
37159            pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
37160   if( pFile->pMapRegion ){
37161     if( !osUnmapViewOfFile(pFile->pMapRegion) ){
37162       pFile->lastErrno = osGetLastError();
37163       OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
37164                "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
37165                pFile->pMapRegion));
37166       return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
37167                          "winUnmapfile1", pFile->zPath);
37168     }
37169     pFile->pMapRegion = 0;
37170     pFile->mmapSize = 0;
37171     pFile->mmapSizeActual = 0;
37172   }
37173   if( pFile->hMap!=NULL ){
37174     if( !osCloseHandle(pFile->hMap) ){
37175       pFile->lastErrno = osGetLastError();
37176       OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
37177                osGetCurrentProcessId(), pFile, pFile->hMap));
37178       return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
37179                          "winUnmapfile2", pFile->zPath);
37180     }
37181     pFile->hMap = NULL;
37182   }
37183   OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
37184            osGetCurrentProcessId(), pFile));
37185   return SQLITE_OK;
37186 }
37187
37188 /*
37189 ** Memory map or remap the file opened by file-descriptor pFd (if the file
37190 ** is already mapped, the existing mapping is replaced by the new). Or, if
37191 ** there already exists a mapping for this file, and there are still
37192 ** outstanding xFetch() references to it, this function is a no-op.
37193 **
37194 ** If parameter nByte is non-negative, then it is the requested size of
37195 ** the mapping to create. Otherwise, if nByte is less than zero, then the
37196 ** requested size is the size of the file on disk. The actual size of the
37197 ** created mapping is either the requested size or the value configured
37198 ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
37199 **
37200 ** SQLITE_OK is returned if no error occurs (even if the mapping is not
37201 ** recreated as a result of outstanding references) or an SQLite error
37202 ** code otherwise.
37203 */
37204 static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
37205   sqlite3_int64 nMap = nByte;
37206   int rc;
37207
37208   assert( nMap>=0 || pFd->nFetchOut==0 );
37209   OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
37210            osGetCurrentProcessId(), pFd, nByte));
37211
37212   if( pFd->nFetchOut>0 ) return SQLITE_OK;
37213
37214   if( nMap<0 ){
37215     rc = winFileSize((sqlite3_file*)pFd, &nMap);
37216     if( rc ){
37217       OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
37218                osGetCurrentProcessId(), pFd));
37219       return SQLITE_IOERR_FSTAT;
37220     }
37221   }
37222   if( nMap>pFd->mmapSizeMax ){
37223     nMap = pFd->mmapSizeMax;
37224   }
37225   nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
37226
37227   if( nMap==0 && pFd->mmapSize>0 ){
37228     winUnmapfile(pFd);
37229   }
37230   if( nMap!=pFd->mmapSize ){
37231     void *pNew = 0;
37232     DWORD protect = PAGE_READONLY;
37233     DWORD flags = FILE_MAP_READ;
37234
37235     winUnmapfile(pFd);
37236     if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
37237       protect = PAGE_READWRITE;
37238       flags |= FILE_MAP_WRITE;
37239     }
37240 #if SQLITE_OS_WINRT
37241     pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
37242 #elif defined(SQLITE_WIN32_HAS_WIDE)
37243     pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
37244                                 (DWORD)((nMap>>32) & 0xffffffff),
37245                                 (DWORD)(nMap & 0xffffffff), NULL);
37246 #elif defined(SQLITE_WIN32_HAS_ANSI)
37247     pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
37248                                 (DWORD)((nMap>>32) & 0xffffffff),
37249                                 (DWORD)(nMap & 0xffffffff), NULL);
37250 #endif
37251     if( pFd->hMap==NULL ){
37252       pFd->lastErrno = osGetLastError();
37253       rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
37254                        "winMapfile1", pFd->zPath);
37255       /* Log the error, but continue normal operation using xRead/xWrite */
37256       OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
37257                osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
37258       return SQLITE_OK;
37259     }
37260     assert( (nMap % winSysInfo.dwPageSize)==0 );
37261     assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
37262 #if SQLITE_OS_WINRT
37263     pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
37264 #else
37265     pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
37266 #endif
37267     if( pNew==NULL ){
37268       osCloseHandle(pFd->hMap);
37269       pFd->hMap = NULL;
37270       pFd->lastErrno = osGetLastError();
37271       rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
37272                        "winMapfile2", pFd->zPath);
37273       /* Log the error, but continue normal operation using xRead/xWrite */
37274       OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
37275                osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
37276       return SQLITE_OK;
37277     }
37278     pFd->pMapRegion = pNew;
37279     pFd->mmapSize = nMap;
37280     pFd->mmapSizeActual = nMap;
37281   }
37282
37283   OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
37284            osGetCurrentProcessId(), pFd));
37285   return SQLITE_OK;
37286 }
37287 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
37288
37289 /*
37290 ** If possible, return a pointer to a mapping of file fd starting at offset
37291 ** iOff. The mapping must be valid for at least nAmt bytes.
37292 **
37293 ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
37294 ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
37295 ** Finally, if an error does occur, return an SQLite error code. The final
37296 ** value of *pp is undefined in this case.
37297 **
37298 ** If this function does return a pointer, the caller must eventually
37299 ** release the reference by calling winUnfetch().
37300 */
37301 static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
37302 #if SQLITE_MAX_MMAP_SIZE>0
37303   winFile *pFd = (winFile*)fd;   /* The underlying database file */
37304 #endif
37305   *pp = 0;
37306
37307   OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
37308            osGetCurrentProcessId(), fd, iOff, nAmt, pp));
37309
37310 #if SQLITE_MAX_MMAP_SIZE>0
37311   if( pFd->mmapSizeMax>0 ){
37312     if( pFd->pMapRegion==0 ){
37313       int rc = winMapfile(pFd, -1);
37314       if( rc!=SQLITE_OK ){
37315         OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
37316                  osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
37317         return rc;
37318       }
37319     }
37320     if( pFd->mmapSize >= iOff+nAmt ){
37321       *pp = &((u8 *)pFd->pMapRegion)[iOff];
37322       pFd->nFetchOut++;
37323     }
37324   }
37325 #endif
37326
37327   OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
37328            osGetCurrentProcessId(), fd, pp, *pp));
37329   return SQLITE_OK;
37330 }
37331
37332 /*
37333 ** If the third argument is non-NULL, then this function releases a
37334 ** reference obtained by an earlier call to winFetch(). The second
37335 ** argument passed to this function must be the same as the corresponding
37336 ** argument that was passed to the winFetch() invocation.
37337 **
37338 ** Or, if the third argument is NULL, then this function is being called
37339 ** to inform the VFS layer that, according to POSIX, any existing mapping
37340 ** may now be invalid and should be unmapped.
37341 */
37342 static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
37343 #if SQLITE_MAX_MMAP_SIZE>0
37344   winFile *pFd = (winFile*)fd;   /* The underlying database file */
37345
37346   /* If p==0 (unmap the entire file) then there must be no outstanding
37347   ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
37348   ** then there must be at least one outstanding.  */
37349   assert( (p==0)==(pFd->nFetchOut==0) );
37350
37351   /* If p!=0, it must match the iOff value. */
37352   assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
37353
37354   OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
37355            osGetCurrentProcessId(), pFd, iOff, p));
37356
37357   if( p ){
37358     pFd->nFetchOut--;
37359   }else{
37360     /* FIXME:  If Windows truly always prevents truncating or deleting a
37361     ** file while a mapping is held, then the following winUnmapfile() call
37362     ** is unnecessary can be omitted - potentially improving
37363     ** performance.  */
37364     winUnmapfile(pFd);
37365   }
37366
37367   assert( pFd->nFetchOut>=0 );
37368 #endif
37369
37370   OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
37371            osGetCurrentProcessId(), fd));
37372   return SQLITE_OK;
37373 }
37374
37375 /*
37376 ** Here ends the implementation of all sqlite3_file methods.
37377 **
37378 ********************** End sqlite3_file Methods *******************************
37379 ******************************************************************************/
37380
37381 /*
37382 ** This vector defines all the methods that can operate on an
37383 ** sqlite3_file for win32.
37384 */
37385 static const sqlite3_io_methods winIoMethod = {
37386   3,                              /* iVersion */
37387   winClose,                       /* xClose */
37388   winRead,                        /* xRead */
37389   winWrite,                       /* xWrite */
37390   winTruncate,                    /* xTruncate */
37391   winSync,                        /* xSync */
37392   winFileSize,                    /* xFileSize */
37393   winLock,                        /* xLock */
37394   winUnlock,                      /* xUnlock */
37395   winCheckReservedLock,           /* xCheckReservedLock */
37396   winFileControl,                 /* xFileControl */
37397   winSectorSize,                  /* xSectorSize */
37398   winDeviceCharacteristics,       /* xDeviceCharacteristics */
37399   winShmMap,                      /* xShmMap */
37400   winShmLock,                     /* xShmLock */
37401   winShmBarrier,                  /* xShmBarrier */
37402   winShmUnmap,                    /* xShmUnmap */
37403   winFetch,                       /* xFetch */
37404   winUnfetch                      /* xUnfetch */
37405 };
37406
37407 /****************************************************************************
37408 **************************** sqlite3_vfs methods ****************************
37409 **
37410 ** This division contains the implementation of methods on the
37411 ** sqlite3_vfs object.
37412 */
37413
37414 #if defined(__CYGWIN__)
37415 /*
37416 ** Convert a filename from whatever the underlying operating system
37417 ** supports for filenames into UTF-8.  Space to hold the result is
37418 ** obtained from malloc and must be freed by the calling function.
37419 */
37420 static char *winConvertToUtf8Filename(const void *zFilename){
37421   char *zConverted = 0;
37422   if( osIsNT() ){
37423     zConverted = winUnicodeToUtf8(zFilename);
37424   }
37425 #ifdef SQLITE_WIN32_HAS_ANSI
37426   else{
37427     zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
37428   }
37429 #endif
37430   /* caller will handle out of memory */
37431   return zConverted;
37432 }
37433 #endif
37434
37435 /*
37436 ** Convert a UTF-8 filename into whatever form the underlying
37437 ** operating system wants filenames in.  Space to hold the result
37438 ** is obtained from malloc and must be freed by the calling
37439 ** function.
37440 */
37441 static void *winConvertFromUtf8Filename(const char *zFilename){
37442   void *zConverted = 0;
37443   if( osIsNT() ){
37444     zConverted = winUtf8ToUnicode(zFilename);
37445   }
37446 #ifdef SQLITE_WIN32_HAS_ANSI
37447   else{
37448     zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
37449   }
37450 #endif
37451   /* caller will handle out of memory */
37452   return zConverted;
37453 }
37454
37455 /*
37456 ** This function returns non-zero if the specified UTF-8 string buffer
37457 ** ends with a directory separator character or one was successfully
37458 ** added to it.
37459 */
37460 static int winMakeEndInDirSep(int nBuf, char *zBuf){
37461   if( zBuf ){
37462     int nLen = sqlite3Strlen30(zBuf);
37463     if( nLen>0 ){
37464       if( winIsDirSep(zBuf[nLen-1]) ){
37465         return 1;
37466       }else if( nLen+1<nBuf ){
37467         zBuf[nLen] = winGetDirSep();
37468         zBuf[nLen+1] = '\0';
37469         return 1;
37470       }
37471     }
37472   }
37473   return 0;
37474 }
37475
37476 /*
37477 ** Create a temporary file name and store the resulting pointer into pzBuf.
37478 ** The pointer returned in pzBuf must be freed via sqlite3_free().
37479 */
37480 static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
37481   static char zChars[] =
37482     "abcdefghijklmnopqrstuvwxyz"
37483     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
37484     "0123456789";
37485   size_t i, j;
37486   int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
37487   int nMax, nBuf, nDir, nLen;
37488   char *zBuf;
37489
37490   /* It's odd to simulate an io-error here, but really this is just
37491   ** using the io-error infrastructure to test that SQLite handles this
37492   ** function failing.
37493   */
37494   SimulateIOError( return SQLITE_IOERR );
37495
37496   /* Allocate a temporary buffer to store the fully qualified file
37497   ** name for the temporary file.  If this fails, we cannot continue.
37498   */
37499   nMax = pVfs->mxPathname; nBuf = nMax + 2;
37500   zBuf = sqlite3MallocZero( nBuf );
37501   if( !zBuf ){
37502     OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37503     return SQLITE_IOERR_NOMEM;
37504   }
37505
37506   /* Figure out the effective temporary directory.  First, check if one
37507   ** has been explicitly set by the application; otherwise, use the one
37508   ** configured by the operating system.
37509   */
37510   nDir = nMax - (nPre + 15);
37511   assert( nDir>0 );
37512   if( sqlite3_temp_directory ){
37513     int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
37514     if( nDirLen>0 ){
37515       if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
37516         nDirLen++;
37517       }
37518       if( nDirLen>nDir ){
37519         sqlite3_free(zBuf);
37520         OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
37521         return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
37522       }
37523       sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
37524     }
37525   }
37526 #if defined(__CYGWIN__)
37527   else{
37528     static const char *azDirs[] = {
37529        0, /* getenv("SQLITE_TMPDIR") */
37530        0, /* getenv("TMPDIR") */
37531        0, /* getenv("TMP") */
37532        0, /* getenv("TEMP") */
37533        0, /* getenv("USERPROFILE") */
37534        "/var/tmp",
37535        "/usr/tmp",
37536        "/tmp",
37537        ".",
37538        0        /* List terminator */
37539     };
37540     unsigned int i;
37541     const char *zDir = 0;
37542
37543     if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
37544     if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
37545     if( !azDirs[2] ) azDirs[2] = getenv("TMP");
37546     if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
37547     if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
37548     for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
37549       void *zConverted;
37550       if( zDir==0 ) continue;
37551       /* If the path starts with a drive letter followed by the colon
37552       ** character, assume it is already a native Win32 path; otherwise,
37553       ** it must be converted to a native Win32 path via the Cygwin API
37554       ** prior to using it.
37555       */
37556       if( winIsDriveLetterAndColon(zDir) ){
37557         zConverted = winConvertFromUtf8Filename(zDir);
37558         if( !zConverted ){
37559           sqlite3_free(zBuf);
37560           OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37561           return SQLITE_IOERR_NOMEM;
37562         }
37563         if( winIsDir(zConverted) ){
37564           sqlite3_snprintf(nMax, zBuf, "%s", zDir);
37565           sqlite3_free(zConverted);
37566           break;
37567         }
37568         sqlite3_free(zConverted);
37569       }else{
37570         zConverted = sqlite3MallocZero( nMax+1 );
37571         if( !zConverted ){
37572           sqlite3_free(zBuf);
37573           OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37574           return SQLITE_IOERR_NOMEM;
37575         }
37576         if( cygwin_conv_path(
37577                 osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
37578                 zConverted, nMax+1)<0 ){
37579           sqlite3_free(zConverted);
37580           sqlite3_free(zBuf);
37581           OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
37582           return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
37583                              "winGetTempname2", zDir);
37584         }
37585         if( winIsDir(zConverted) ){
37586           /* At this point, we know the candidate directory exists and should
37587           ** be used.  However, we may need to convert the string containing
37588           ** its name into UTF-8 (i.e. if it is UTF-16 right now).
37589           */
37590           char *zUtf8 = winConvertToUtf8Filename(zConverted);
37591           if( !zUtf8 ){
37592             sqlite3_free(zConverted);
37593             sqlite3_free(zBuf);
37594             OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37595             return SQLITE_IOERR_NOMEM;
37596           }
37597           sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
37598           sqlite3_free(zUtf8);
37599           sqlite3_free(zConverted);
37600           break;
37601         }
37602         sqlite3_free(zConverted);
37603       }
37604     }
37605   }
37606 #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
37607   else if( osIsNT() ){
37608     char *zMulti;
37609     LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
37610     if( !zWidePath ){
37611       sqlite3_free(zBuf);
37612       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37613       return SQLITE_IOERR_NOMEM;
37614     }
37615     if( osGetTempPathW(nMax, zWidePath)==0 ){
37616       sqlite3_free(zWidePath);
37617       sqlite3_free(zBuf);
37618       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
37619       return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
37620                          "winGetTempname2", 0);
37621     }
37622     zMulti = winUnicodeToUtf8(zWidePath);
37623     if( zMulti ){
37624       sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
37625       sqlite3_free(zMulti);
37626       sqlite3_free(zWidePath);
37627     }else{
37628       sqlite3_free(zWidePath);
37629       sqlite3_free(zBuf);
37630       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37631       return SQLITE_IOERR_NOMEM;
37632     }
37633   }
37634 #ifdef SQLITE_WIN32_HAS_ANSI
37635   else{
37636     char *zUtf8;
37637     char *zMbcsPath = sqlite3MallocZero( nMax );
37638     if( !zMbcsPath ){
37639       sqlite3_free(zBuf);
37640       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37641       return SQLITE_IOERR_NOMEM;
37642     }
37643     if( osGetTempPathA(nMax, zMbcsPath)==0 ){
37644       sqlite3_free(zBuf);
37645       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
37646       return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
37647                          "winGetTempname3", 0);
37648     }
37649     zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
37650     if( zUtf8 ){
37651       sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
37652       sqlite3_free(zUtf8);
37653     }else{
37654       sqlite3_free(zBuf);
37655       OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
37656       return SQLITE_IOERR_NOMEM;
37657     }
37658   }
37659 #endif /* SQLITE_WIN32_HAS_ANSI */
37660 #endif /* !SQLITE_OS_WINRT */
37661
37662   /*
37663   ** Check to make sure the temporary directory ends with an appropriate
37664   ** separator.  If it does not and there is not enough space left to add
37665   ** one, fail.
37666   */
37667   if( !winMakeEndInDirSep(nDir+1, zBuf) ){
37668     sqlite3_free(zBuf);
37669     OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
37670     return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
37671   }
37672
37673   /*
37674   ** Check that the output buffer is large enough for the temporary file
37675   ** name in the following format:
37676   **
37677   **   "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
37678   **
37679   ** If not, return SQLITE_ERROR.  The number 17 is used here in order to
37680   ** account for the space used by the 15 character random suffix and the
37681   ** two trailing NUL characters.  The final directory separator character
37682   ** has already added if it was not already present.
37683   */
37684   nLen = sqlite3Strlen30(zBuf);
37685   if( (nLen + nPre + 17) > nBuf ){
37686     sqlite3_free(zBuf);
37687     OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
37688     return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
37689   }
37690
37691   sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
37692
37693   j = sqlite3Strlen30(zBuf);
37694   sqlite3_randomness(15, &zBuf[j]);
37695   for(i=0; i<15; i++, j++){
37696     zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
37697   }
37698   zBuf[j] = 0;
37699   zBuf[j+1] = 0;
37700   *pzBuf = zBuf;
37701
37702   OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
37703   return SQLITE_OK;
37704 }
37705
37706 /*
37707 ** Return TRUE if the named file is really a directory.  Return false if
37708 ** it is something other than a directory, or if there is any kind of memory
37709 ** allocation failure.
37710 */
37711 static int winIsDir(const void *zConverted){
37712   DWORD attr;
37713   int rc = 0;
37714   DWORD lastErrno;
37715
37716   if( osIsNT() ){
37717     int cnt = 0;
37718     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
37719     memset(&sAttrData, 0, sizeof(sAttrData));
37720     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
37721                              GetFileExInfoStandard,
37722                              &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
37723     if( !rc ){
37724       return 0; /* Invalid name? */
37725     }
37726     attr = sAttrData.dwFileAttributes;
37727 #if SQLITE_OS_WINCE==0
37728   }else{
37729     attr = osGetFileAttributesA((char*)zConverted);
37730 #endif
37731   }
37732   return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
37733 }
37734
37735 /*
37736 ** Open a file.
37737 */
37738 static int winOpen(
37739   sqlite3_vfs *pVfs,        /* Used to get maximum path name length */
37740   const char *zName,        /* Name of the file (UTF-8) */
37741   sqlite3_file *id,         /* Write the SQLite file handle here */
37742   int flags,                /* Open mode flags */
37743   int *pOutFlags            /* Status return flags */
37744 ){
37745   HANDLE h;
37746   DWORD lastErrno = 0;
37747   DWORD dwDesiredAccess;
37748   DWORD dwShareMode;
37749   DWORD dwCreationDisposition;
37750   DWORD dwFlagsAndAttributes = 0;
37751 #if SQLITE_OS_WINCE
37752   int isTemp = 0;
37753 #endif
37754   winFile *pFile = (winFile*)id;
37755   void *zConverted;              /* Filename in OS encoding */
37756   const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
37757   int cnt = 0;
37758
37759   /* If argument zPath is a NULL pointer, this function is required to open
37760   ** a temporary file. Use this buffer to store the file name in.
37761   */
37762   char *zTmpname = 0; /* For temporary filename, if necessary. */
37763
37764   int rc = SQLITE_OK;            /* Function Return Code */
37765 #if !defined(NDEBUG) || SQLITE_OS_WINCE
37766   int eType = flags&0xFFFFFF00;  /* Type of file to open */
37767 #endif
37768
37769   int isExclusive  = (flags & SQLITE_OPEN_EXCLUSIVE);
37770   int isDelete     = (flags & SQLITE_OPEN_DELETEONCLOSE);
37771   int isCreate     = (flags & SQLITE_OPEN_CREATE);
37772   int isReadonly   = (flags & SQLITE_OPEN_READONLY);
37773   int isReadWrite  = (flags & SQLITE_OPEN_READWRITE);
37774
37775 #ifndef NDEBUG
37776   int isOpenJournal = (isCreate && (
37777         eType==SQLITE_OPEN_MASTER_JOURNAL
37778      || eType==SQLITE_OPEN_MAIN_JOURNAL
37779      || eType==SQLITE_OPEN_WAL
37780   ));
37781 #endif
37782
37783   OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
37784            zUtf8Name, id, flags, pOutFlags));
37785
37786   /* Check the following statements are true:
37787   **
37788   **   (a) Exactly one of the READWRITE and READONLY flags must be set, and
37789   **   (b) if CREATE is set, then READWRITE must also be set, and
37790   **   (c) if EXCLUSIVE is set, then CREATE must also be set.
37791   **   (d) if DELETEONCLOSE is set, then CREATE must also be set.
37792   */
37793   assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
37794   assert(isCreate==0 || isReadWrite);
37795   assert(isExclusive==0 || isCreate);
37796   assert(isDelete==0 || isCreate);
37797
37798   /* The main DB, main journal, WAL file and master journal are never
37799   ** automatically deleted. Nor are they ever temporary files.  */
37800   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
37801   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
37802   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
37803   assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
37804
37805   /* Assert that the upper layer has set one of the "file-type" flags. */
37806   assert( eType==SQLITE_OPEN_MAIN_DB      || eType==SQLITE_OPEN_TEMP_DB
37807        || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
37808        || eType==SQLITE_OPEN_SUBJOURNAL   || eType==SQLITE_OPEN_MASTER_JOURNAL
37809        || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
37810   );
37811
37812   assert( pFile!=0 );
37813   memset(pFile, 0, sizeof(winFile));
37814   pFile->h = INVALID_HANDLE_VALUE;
37815
37816 #if SQLITE_OS_WINRT
37817   if( !zUtf8Name && !sqlite3_temp_directory ){
37818     sqlite3_log(SQLITE_ERROR,
37819         "sqlite3_temp_directory variable should be set for WinRT");
37820   }
37821 #endif
37822
37823   /* If the second argument to this function is NULL, generate a
37824   ** temporary file name to use
37825   */
37826   if( !zUtf8Name ){
37827     assert( isDelete && !isOpenJournal );
37828     rc = winGetTempname(pVfs, &zTmpname);
37829     if( rc!=SQLITE_OK ){
37830       OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
37831       return rc;
37832     }
37833     zUtf8Name = zTmpname;
37834   }
37835
37836   /* Database filenames are double-zero terminated if they are not
37837   ** URIs with parameters.  Hence, they can always be passed into
37838   ** sqlite3_uri_parameter().
37839   */
37840   assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
37841        zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
37842
37843   /* Convert the filename to the system encoding. */
37844   zConverted = winConvertFromUtf8Filename(zUtf8Name);
37845   if( zConverted==0 ){
37846     sqlite3_free(zTmpname);
37847     OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
37848     return SQLITE_IOERR_NOMEM;
37849   }
37850
37851   if( winIsDir(zConverted) ){
37852     sqlite3_free(zConverted);
37853     sqlite3_free(zTmpname);
37854     OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
37855     return SQLITE_CANTOPEN_ISDIR;
37856   }
37857
37858   if( isReadWrite ){
37859     dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
37860   }else{
37861     dwDesiredAccess = GENERIC_READ;
37862   }
37863
37864   /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
37865   ** created. SQLite doesn't use it to indicate "exclusive access"
37866   ** as it is usually understood.
37867   */
37868   if( isExclusive ){
37869     /* Creates a new file, only if it does not already exist. */
37870     /* If the file exists, it fails. */
37871     dwCreationDisposition = CREATE_NEW;
37872   }else if( isCreate ){
37873     /* Open existing file, or create if it doesn't exist */
37874     dwCreationDisposition = OPEN_ALWAYS;
37875   }else{
37876     /* Opens a file, only if it exists. */
37877     dwCreationDisposition = OPEN_EXISTING;
37878   }
37879
37880   dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
37881
37882   if( isDelete ){
37883 #if SQLITE_OS_WINCE
37884     dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
37885     isTemp = 1;
37886 #else
37887     dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
37888                                | FILE_ATTRIBUTE_HIDDEN
37889                                | FILE_FLAG_DELETE_ON_CLOSE;
37890 #endif
37891   }else{
37892     dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
37893   }
37894   /* Reports from the internet are that performance is always
37895   ** better if FILE_FLAG_RANDOM_ACCESS is used.  Ticket #2699. */
37896 #if SQLITE_OS_WINCE
37897   dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
37898 #endif
37899
37900   if( osIsNT() ){
37901 #if SQLITE_OS_WINRT
37902     CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
37903     extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
37904     extendedParameters.dwFileAttributes =
37905             dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
37906     extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
37907     extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
37908     extendedParameters.lpSecurityAttributes = NULL;
37909     extendedParameters.hTemplateFile = NULL;
37910     while( (h = osCreateFile2((LPCWSTR)zConverted,
37911                               dwDesiredAccess,
37912                               dwShareMode,
37913                               dwCreationDisposition,
37914                               &extendedParameters))==INVALID_HANDLE_VALUE &&
37915                               winRetryIoerr(&cnt, &lastErrno) ){
37916                /* Noop */
37917     }
37918 #else
37919     while( (h = osCreateFileW((LPCWSTR)zConverted,
37920                               dwDesiredAccess,
37921                               dwShareMode, NULL,
37922                               dwCreationDisposition,
37923                               dwFlagsAndAttributes,
37924                               NULL))==INVALID_HANDLE_VALUE &&
37925                               winRetryIoerr(&cnt, &lastErrno) ){
37926                /* Noop */
37927     }
37928 #endif
37929   }
37930 #ifdef SQLITE_WIN32_HAS_ANSI
37931   else{
37932     while( (h = osCreateFileA((LPCSTR)zConverted,
37933                               dwDesiredAccess,
37934                               dwShareMode, NULL,
37935                               dwCreationDisposition,
37936                               dwFlagsAndAttributes,
37937                               NULL))==INVALID_HANDLE_VALUE &&
37938                               winRetryIoerr(&cnt, &lastErrno) ){
37939                /* Noop */
37940     }
37941   }
37942 #endif
37943   winLogIoerr(cnt, __LINE__);
37944
37945   OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
37946            dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
37947
37948   if( h==INVALID_HANDLE_VALUE ){
37949     pFile->lastErrno = lastErrno;
37950     winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
37951     sqlite3_free(zConverted);
37952     sqlite3_free(zTmpname);
37953     if( isReadWrite && !isExclusive ){
37954       return winOpen(pVfs, zName, id,
37955          ((flags|SQLITE_OPEN_READONLY) &
37956                      ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
37957          pOutFlags);
37958     }else{
37959       return SQLITE_CANTOPEN_BKPT;
37960     }
37961   }
37962
37963   if( pOutFlags ){
37964     if( isReadWrite ){
37965       *pOutFlags = SQLITE_OPEN_READWRITE;
37966     }else{
37967       *pOutFlags = SQLITE_OPEN_READONLY;
37968     }
37969   }
37970
37971   OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
37972            "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
37973            *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
37974
37975 #if SQLITE_OS_WINCE
37976   if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
37977        && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
37978   ){
37979     osCloseHandle(h);
37980     sqlite3_free(zConverted);
37981     sqlite3_free(zTmpname);
37982     OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
37983     return rc;
37984   }
37985   if( isTemp ){
37986     pFile->zDeleteOnClose = zConverted;
37987   }else
37988 #endif
37989   {
37990     sqlite3_free(zConverted);
37991   }
37992
37993   sqlite3_free(zTmpname);
37994   pFile->pMethod = &winIoMethod;
37995   pFile->pVfs = pVfs;
37996   pFile->h = h;
37997   if( isReadonly ){
37998     pFile->ctrlFlags |= WINFILE_RDONLY;
37999   }
38000   if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
38001     pFile->ctrlFlags |= WINFILE_PSOW;
38002   }
38003   pFile->lastErrno = NO_ERROR;
38004   pFile->zPath = zName;
38005 #if SQLITE_MAX_MMAP_SIZE>0
38006   pFile->hMap = NULL;
38007   pFile->pMapRegion = 0;
38008   pFile->mmapSize = 0;
38009   pFile->mmapSizeActual = 0;
38010   pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
38011 #endif
38012
38013   OpenCounter(+1);
38014   return rc;
38015 }
38016
38017 /*
38018 ** Delete the named file.
38019 **
38020 ** Note that Windows does not allow a file to be deleted if some other
38021 ** process has it open.  Sometimes a virus scanner or indexing program
38022 ** will open a journal file shortly after it is created in order to do
38023 ** whatever it does.  While this other process is holding the
38024 ** file open, we will be unable to delete it.  To work around this
38025 ** problem, we delay 100 milliseconds and try to delete again.  Up
38026 ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
38027 ** up and returning an error.
38028 */
38029 static int winDelete(
38030   sqlite3_vfs *pVfs,          /* Not used on win32 */
38031   const char *zFilename,      /* Name of file to delete */
38032   int syncDir                 /* Not used on win32 */
38033 ){
38034   int cnt = 0;
38035   int rc;
38036   DWORD attr;
38037   DWORD lastErrno = 0;
38038   void *zConverted;
38039   UNUSED_PARAMETER(pVfs);
38040   UNUSED_PARAMETER(syncDir);
38041
38042   SimulateIOError(return SQLITE_IOERR_DELETE);
38043   OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
38044
38045   zConverted = winConvertFromUtf8Filename(zFilename);
38046   if( zConverted==0 ){
38047     OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
38048     return SQLITE_IOERR_NOMEM;
38049   }
38050   if( osIsNT() ){
38051     do {
38052 #if SQLITE_OS_WINRT
38053       WIN32_FILE_ATTRIBUTE_DATA sAttrData;
38054       memset(&sAttrData, 0, sizeof(sAttrData));
38055       if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
38056                                   &sAttrData) ){
38057         attr = sAttrData.dwFileAttributes;
38058       }else{
38059         lastErrno = osGetLastError();
38060         if( lastErrno==ERROR_FILE_NOT_FOUND
38061          || lastErrno==ERROR_PATH_NOT_FOUND ){
38062           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
38063         }else{
38064           rc = SQLITE_ERROR;
38065         }
38066         break;
38067       }
38068 #else
38069       attr = osGetFileAttributesW(zConverted);
38070 #endif
38071       if ( attr==INVALID_FILE_ATTRIBUTES ){
38072         lastErrno = osGetLastError();
38073         if( lastErrno==ERROR_FILE_NOT_FOUND
38074          || lastErrno==ERROR_PATH_NOT_FOUND ){
38075           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
38076         }else{
38077           rc = SQLITE_ERROR;
38078         }
38079         break;
38080       }
38081       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
38082         rc = SQLITE_ERROR; /* Files only. */
38083         break;
38084       }
38085       if ( osDeleteFileW(zConverted) ){
38086         rc = SQLITE_OK; /* Deleted OK. */
38087         break;
38088       }
38089       if ( !winRetryIoerr(&cnt, &lastErrno) ){
38090         rc = SQLITE_ERROR; /* No more retries. */
38091         break;
38092       }
38093     } while(1);
38094   }
38095 #ifdef SQLITE_WIN32_HAS_ANSI
38096   else{
38097     do {
38098       attr = osGetFileAttributesA(zConverted);
38099       if ( attr==INVALID_FILE_ATTRIBUTES ){
38100         lastErrno = osGetLastError();
38101         if( lastErrno==ERROR_FILE_NOT_FOUND
38102          || lastErrno==ERROR_PATH_NOT_FOUND ){
38103           rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
38104         }else{
38105           rc = SQLITE_ERROR;
38106         }
38107         break;
38108       }
38109       if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
38110         rc = SQLITE_ERROR; /* Files only. */
38111         break;
38112       }
38113       if ( osDeleteFileA(zConverted) ){
38114         rc = SQLITE_OK; /* Deleted OK. */
38115         break;
38116       }
38117       if ( !winRetryIoerr(&cnt, &lastErrno) ){
38118         rc = SQLITE_ERROR; /* No more retries. */
38119         break;
38120       }
38121     } while(1);
38122   }
38123 #endif
38124   if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
38125     rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
38126   }else{
38127     winLogIoerr(cnt, __LINE__);
38128   }
38129   sqlite3_free(zConverted);
38130   OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
38131   return rc;
38132 }
38133
38134 /*
38135 ** Check the existence and status of a file.
38136 */
38137 static int winAccess(
38138   sqlite3_vfs *pVfs,         /* Not used on win32 */
38139   const char *zFilename,     /* Name of file to check */
38140   int flags,                 /* Type of test to make on this file */
38141   int *pResOut               /* OUT: Result */
38142 ){
38143   DWORD attr;
38144   int rc = 0;
38145   DWORD lastErrno = 0;
38146   void *zConverted;
38147   UNUSED_PARAMETER(pVfs);
38148
38149   SimulateIOError( return SQLITE_IOERR_ACCESS; );
38150   OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
38151            zFilename, flags, pResOut));
38152
38153   zConverted = winConvertFromUtf8Filename(zFilename);
38154   if( zConverted==0 ){
38155     OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
38156     return SQLITE_IOERR_NOMEM;
38157   }
38158   if( osIsNT() ){
38159     int cnt = 0;
38160     WIN32_FILE_ATTRIBUTE_DATA sAttrData;
38161     memset(&sAttrData, 0, sizeof(sAttrData));
38162     while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
38163                              GetFileExInfoStandard,
38164                              &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
38165     if( rc ){
38166       /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
38167       ** as if it does not exist.
38168       */
38169       if(    flags==SQLITE_ACCESS_EXISTS
38170           && sAttrData.nFileSizeHigh==0
38171           && sAttrData.nFileSizeLow==0 ){
38172         attr = INVALID_FILE_ATTRIBUTES;
38173       }else{
38174         attr = sAttrData.dwFileAttributes;
38175       }
38176     }else{
38177       winLogIoerr(cnt, __LINE__);
38178       if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
38179         sqlite3_free(zConverted);
38180         return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
38181                            zFilename);
38182       }else{
38183         attr = INVALID_FILE_ATTRIBUTES;
38184       }
38185     }
38186   }
38187 #ifdef SQLITE_WIN32_HAS_ANSI
38188   else{
38189     attr = osGetFileAttributesA((char*)zConverted);
38190   }
38191 #endif
38192   sqlite3_free(zConverted);
38193   switch( flags ){
38194     case SQLITE_ACCESS_READ:
38195     case SQLITE_ACCESS_EXISTS:
38196       rc = attr!=INVALID_FILE_ATTRIBUTES;
38197       break;
38198     case SQLITE_ACCESS_READWRITE:
38199       rc = attr!=INVALID_FILE_ATTRIBUTES &&
38200              (attr & FILE_ATTRIBUTE_READONLY)==0;
38201       break;
38202     default:
38203       assert(!"Invalid flags argument");
38204   }
38205   *pResOut = rc;
38206   OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
38207            zFilename, pResOut, *pResOut));
38208   return SQLITE_OK;
38209 }
38210
38211 /*
38212 ** Returns non-zero if the specified path name starts with a drive letter
38213 ** followed by a colon character.
38214 */
38215 static BOOL winIsDriveLetterAndColon(
38216   const char *zPathname
38217 ){
38218   return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
38219 }
38220
38221 /*
38222 ** Returns non-zero if the specified path name should be used verbatim.  If
38223 ** non-zero is returned from this function, the calling function must simply
38224 ** use the provided path name verbatim -OR- resolve it into a full path name
38225 ** using the GetFullPathName Win32 API function (if available).
38226 */
38227 static BOOL winIsVerbatimPathname(
38228   const char *zPathname
38229 ){
38230   /*
38231   ** If the path name starts with a forward slash or a backslash, it is either
38232   ** a legal UNC name, a volume relative path, or an absolute path name in the
38233   ** "Unix" format on Windows.  There is no easy way to differentiate between
38234   ** the final two cases; therefore, we return the safer return value of TRUE
38235   ** so that callers of this function will simply use it verbatim.
38236   */
38237   if ( winIsDirSep(zPathname[0]) ){
38238     return TRUE;
38239   }
38240
38241   /*
38242   ** If the path name starts with a letter and a colon it is either a volume
38243   ** relative path or an absolute path.  Callers of this function must not
38244   ** attempt to treat it as a relative path name (i.e. they should simply use
38245   ** it verbatim).
38246   */
38247   if ( winIsDriveLetterAndColon(zPathname) ){
38248     return TRUE;
38249   }
38250
38251   /*
38252   ** If we get to this point, the path name should almost certainly be a purely
38253   ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
38254   */
38255   return FALSE;
38256 }
38257
38258 /*
38259 ** Turn a relative pathname into a full pathname.  Write the full
38260 ** pathname into zOut[].  zOut[] will be at least pVfs->mxPathname
38261 ** bytes in size.
38262 */
38263 static int winFullPathname(
38264   sqlite3_vfs *pVfs,            /* Pointer to vfs object */
38265   const char *zRelative,        /* Possibly relative input path */
38266   int nFull,                    /* Size of output buffer in bytes */
38267   char *zFull                   /* Output buffer */
38268 ){
38269
38270 #if defined(__CYGWIN__)
38271   SimulateIOError( return SQLITE_ERROR );
38272   UNUSED_PARAMETER(nFull);
38273   assert( nFull>=pVfs->mxPathname );
38274   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
38275     /*
38276     ** NOTE: We are dealing with a relative path name and the data
38277     **       directory has been set.  Therefore, use it as the basis
38278     **       for converting the relative path name to an absolute
38279     **       one by prepending the data directory and a slash.
38280     */
38281     char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
38282     if( !zOut ){
38283       return SQLITE_IOERR_NOMEM;
38284     }
38285     if( cygwin_conv_path(
38286             (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
38287             CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
38288       sqlite3_free(zOut);
38289       return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
38290                          "winFullPathname1", zRelative);
38291     }else{
38292       char *zUtf8 = winConvertToUtf8Filename(zOut);
38293       if( !zUtf8 ){
38294         sqlite3_free(zOut);
38295         return SQLITE_IOERR_NOMEM;
38296       }
38297       sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
38298                        sqlite3_data_directory, winGetDirSep(), zUtf8);
38299       sqlite3_free(zUtf8);
38300       sqlite3_free(zOut);
38301     }
38302   }else{
38303     char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
38304     if( !zOut ){
38305       return SQLITE_IOERR_NOMEM;
38306     }
38307     if( cygwin_conv_path(
38308             (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
38309             zRelative, zOut, pVfs->mxPathname+1)<0 ){
38310       sqlite3_free(zOut);
38311       return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
38312                          "winFullPathname2", zRelative);
38313     }else{
38314       char *zUtf8 = winConvertToUtf8Filename(zOut);
38315       if( !zUtf8 ){
38316         sqlite3_free(zOut);
38317         return SQLITE_IOERR_NOMEM;
38318       }
38319       sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
38320       sqlite3_free(zUtf8);
38321       sqlite3_free(zOut);
38322     }
38323   }
38324   return SQLITE_OK;
38325 #endif
38326
38327 #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
38328   SimulateIOError( return SQLITE_ERROR );
38329   /* WinCE has no concept of a relative pathname, or so I am told. */
38330   /* WinRT has no way to convert a relative path to an absolute one. */
38331   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
38332     /*
38333     ** NOTE: We are dealing with a relative path name and the data
38334     **       directory has been set.  Therefore, use it as the basis
38335     **       for converting the relative path name to an absolute
38336     **       one by prepending the data directory and a backslash.
38337     */
38338     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
38339                      sqlite3_data_directory, winGetDirSep(), zRelative);
38340   }else{
38341     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
38342   }
38343   return SQLITE_OK;
38344 #endif
38345
38346 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
38347   DWORD nByte;
38348   void *zConverted;
38349   char *zOut;
38350
38351   /* If this path name begins with "/X:", where "X" is any alphabetic
38352   ** character, discard the initial "/" from the pathname.
38353   */
38354   if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
38355     zRelative++;
38356   }
38357
38358   /* It's odd to simulate an io-error here, but really this is just
38359   ** using the io-error infrastructure to test that SQLite handles this
38360   ** function failing. This function could fail if, for example, the
38361   ** current working directory has been unlinked.
38362   */
38363   SimulateIOError( return SQLITE_ERROR );
38364   if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
38365     /*
38366     ** NOTE: We are dealing with a relative path name and the data
38367     **       directory has been set.  Therefore, use it as the basis
38368     **       for converting the relative path name to an absolute
38369     **       one by prepending the data directory and a backslash.
38370     */
38371     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
38372                      sqlite3_data_directory, winGetDirSep(), zRelative);
38373     return SQLITE_OK;
38374   }
38375   zConverted = winConvertFromUtf8Filename(zRelative);
38376   if( zConverted==0 ){
38377     return SQLITE_IOERR_NOMEM;
38378   }
38379   if( osIsNT() ){
38380     LPWSTR zTemp;
38381     nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
38382     if( nByte==0 ){
38383       sqlite3_free(zConverted);
38384       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
38385                          "winFullPathname1", zRelative);
38386     }
38387     nByte += 3;
38388     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
38389     if( zTemp==0 ){
38390       sqlite3_free(zConverted);
38391       return SQLITE_IOERR_NOMEM;
38392     }
38393     nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
38394     if( nByte==0 ){
38395       sqlite3_free(zConverted);
38396       sqlite3_free(zTemp);
38397       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
38398                          "winFullPathname2", zRelative);
38399     }
38400     sqlite3_free(zConverted);
38401     zOut = winUnicodeToUtf8(zTemp);
38402     sqlite3_free(zTemp);
38403   }
38404 #ifdef SQLITE_WIN32_HAS_ANSI
38405   else{
38406     char *zTemp;
38407     nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
38408     if( nByte==0 ){
38409       sqlite3_free(zConverted);
38410       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
38411                          "winFullPathname3", zRelative);
38412     }
38413     nByte += 3;
38414     zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
38415     if( zTemp==0 ){
38416       sqlite3_free(zConverted);
38417       return SQLITE_IOERR_NOMEM;
38418     }
38419     nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
38420     if( nByte==0 ){
38421       sqlite3_free(zConverted);
38422       sqlite3_free(zTemp);
38423       return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
38424                          "winFullPathname4", zRelative);
38425     }
38426     sqlite3_free(zConverted);
38427     zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
38428     sqlite3_free(zTemp);
38429   }
38430 #endif
38431   if( zOut ){
38432     sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
38433     sqlite3_free(zOut);
38434     return SQLITE_OK;
38435   }else{
38436     return SQLITE_IOERR_NOMEM;
38437   }
38438 #endif
38439 }
38440
38441 #ifndef SQLITE_OMIT_LOAD_EXTENSION
38442 /*
38443 ** Interfaces for opening a shared library, finding entry points
38444 ** within the shared library, and closing the shared library.
38445 */
38446 static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
38447   HANDLE h;
38448 #if defined(__CYGWIN__)
38449   int nFull = pVfs->mxPathname+1;
38450   char *zFull = sqlite3MallocZero( nFull );
38451   void *zConverted = 0;
38452   if( zFull==0 ){
38453     OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
38454     return 0;
38455   }
38456   if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
38457     sqlite3_free(zFull);
38458     OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
38459     return 0;
38460   }
38461   zConverted = winConvertFromUtf8Filename(zFull);
38462   sqlite3_free(zFull);
38463 #else
38464   void *zConverted = winConvertFromUtf8Filename(zFilename);
38465   UNUSED_PARAMETER(pVfs);
38466 #endif
38467   if( zConverted==0 ){
38468     OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
38469     return 0;
38470   }
38471   if( osIsNT() ){
38472 #if SQLITE_OS_WINRT
38473     h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
38474 #else
38475     h = osLoadLibraryW((LPCWSTR)zConverted);
38476 #endif
38477   }
38478 #ifdef SQLITE_WIN32_HAS_ANSI
38479   else{
38480     h = osLoadLibraryA((char*)zConverted);
38481   }
38482 #endif
38483   OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
38484   sqlite3_free(zConverted);
38485   return (void*)h;
38486 }
38487 static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
38488   UNUSED_PARAMETER(pVfs);
38489   winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
38490 }
38491 static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
38492   FARPROC proc;
38493   UNUSED_PARAMETER(pVfs);
38494   proc = osGetProcAddressA((HANDLE)pH, zSym);
38495   OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
38496            (void*)pH, zSym, (void*)proc));
38497   return (void(*)(void))proc;
38498 }
38499 static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
38500   UNUSED_PARAMETER(pVfs);
38501   osFreeLibrary((HANDLE)pHandle);
38502   OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
38503 }
38504 #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
38505   #define winDlOpen  0
38506   #define winDlError 0
38507   #define winDlSym   0
38508   #define winDlClose 0
38509 #endif
38510
38511
38512 /*
38513 ** Write up to nBuf bytes of randomness into zBuf.
38514 */
38515 static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
38516   int n = 0;
38517   UNUSED_PARAMETER(pVfs);
38518 #if defined(SQLITE_TEST)
38519   n = nBuf;
38520   memset(zBuf, 0, nBuf);
38521 #else
38522   if( sizeof(SYSTEMTIME)<=nBuf-n ){
38523     SYSTEMTIME x;
38524     osGetSystemTime(&x);
38525     memcpy(&zBuf[n], &x, sizeof(x));
38526     n += sizeof(x);
38527   }
38528   if( sizeof(DWORD)<=nBuf-n ){
38529     DWORD pid = osGetCurrentProcessId();
38530     memcpy(&zBuf[n], &pid, sizeof(pid));
38531     n += sizeof(pid);
38532   }
38533 #if SQLITE_OS_WINRT
38534   if( sizeof(ULONGLONG)<=nBuf-n ){
38535     ULONGLONG cnt = osGetTickCount64();
38536     memcpy(&zBuf[n], &cnt, sizeof(cnt));
38537     n += sizeof(cnt);
38538   }
38539 #else
38540   if( sizeof(DWORD)<=nBuf-n ){
38541     DWORD cnt = osGetTickCount();
38542     memcpy(&zBuf[n], &cnt, sizeof(cnt));
38543     n += sizeof(cnt);
38544   }
38545 #endif
38546   if( sizeof(LARGE_INTEGER)<=nBuf-n ){
38547     LARGE_INTEGER i;
38548     osQueryPerformanceCounter(&i);
38549     memcpy(&zBuf[n], &i, sizeof(i));
38550     n += sizeof(i);
38551   }
38552 #endif
38553 #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_WIN32_USE_UUID
38554   if( sizeof(UUID)<=nBuf-n ){
38555     UUID id;
38556     memset(&id, 0, sizeof(UUID));
38557     osUuidCreate(&id);
38558     memcpy(zBuf, &id, sizeof(UUID));
38559     n += sizeof(UUID);
38560   }
38561   if( sizeof(UUID)<=nBuf-n ){
38562     UUID id;
38563     memset(&id, 0, sizeof(UUID));
38564     osUuidCreateSequential(&id);
38565     memcpy(zBuf, &id, sizeof(UUID));
38566     n += sizeof(UUID);
38567   }
38568 #endif
38569   return n;
38570 }
38571
38572
38573 /*
38574 ** Sleep for a little while.  Return the amount of time slept.
38575 */
38576 static int winSleep(sqlite3_vfs *pVfs, int microsec){
38577   sqlite3_win32_sleep((microsec+999)/1000);
38578   UNUSED_PARAMETER(pVfs);
38579   return ((microsec+999)/1000)*1000;
38580 }
38581
38582 /*
38583 ** The following variable, if set to a non-zero value, is interpreted as
38584 ** the number of seconds since 1970 and is used to set the result of
38585 ** sqlite3OsCurrentTime() during testing.
38586 */
38587 #ifdef SQLITE_TEST
38588 SQLITE_API int sqlite3_current_time = 0;  /* Fake system time in seconds since 1970. */
38589 #endif
38590
38591 /*
38592 ** Find the current time (in Universal Coordinated Time).  Write into *piNow
38593 ** the current time and date as a Julian Day number times 86_400_000.  In
38594 ** other words, write into *piNow the number of milliseconds since the Julian
38595 ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
38596 ** proleptic Gregorian calendar.
38597 **
38598 ** On success, return SQLITE_OK.  Return SQLITE_ERROR if the time and date
38599 ** cannot be found.
38600 */
38601 static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
38602   /* FILETIME structure is a 64-bit value representing the number of
38603      100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
38604   */
38605   FILETIME ft;
38606   static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
38607 #ifdef SQLITE_TEST
38608   static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
38609 #endif
38610   /* 2^32 - to avoid use of LL and warnings in gcc */
38611   static const sqlite3_int64 max32BitValue =
38612       (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
38613       (sqlite3_int64)294967296;
38614
38615 #if SQLITE_OS_WINCE
38616   SYSTEMTIME time;
38617   osGetSystemTime(&time);
38618   /* if SystemTimeToFileTime() fails, it returns zero. */
38619   if (!osSystemTimeToFileTime(&time,&ft)){
38620     return SQLITE_ERROR;
38621   }
38622 #else
38623   osGetSystemTimeAsFileTime( &ft );
38624 #endif
38625
38626   *piNow = winFiletimeEpoch +
38627             ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
38628                (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
38629
38630 #ifdef SQLITE_TEST
38631   if( sqlite3_current_time ){
38632     *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
38633   }
38634 #endif
38635   UNUSED_PARAMETER(pVfs);
38636   return SQLITE_OK;
38637 }
38638
38639 /*
38640 ** Find the current time (in Universal Coordinated Time).  Write the
38641 ** current time and date as a Julian Day number into *prNow and
38642 ** return 0.  Return 1 if the time and date cannot be found.
38643 */
38644 static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
38645   int rc;
38646   sqlite3_int64 i;
38647   rc = winCurrentTimeInt64(pVfs, &i);
38648   if( !rc ){
38649     *prNow = i/86400000.0;
38650   }
38651   return rc;
38652 }
38653
38654 /*
38655 ** The idea is that this function works like a combination of
38656 ** GetLastError() and FormatMessage() on Windows (or errno and
38657 ** strerror_r() on Unix). After an error is returned by an OS
38658 ** function, SQLite calls this function with zBuf pointing to
38659 ** a buffer of nBuf bytes. The OS layer should populate the
38660 ** buffer with a nul-terminated UTF-8 encoded error message
38661 ** describing the last IO error to have occurred within the calling
38662 ** thread.
38663 **
38664 ** If the error message is too large for the supplied buffer,
38665 ** it should be truncated. The return value of xGetLastError
38666 ** is zero if the error message fits in the buffer, or non-zero
38667 ** otherwise (if the message was truncated). If non-zero is returned,
38668 ** then it is not necessary to include the nul-terminator character
38669 ** in the output buffer.
38670 **
38671 ** Not supplying an error message will have no adverse effect
38672 ** on SQLite. It is fine to have an implementation that never
38673 ** returns an error message:
38674 **
38675 **   int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
38676 **     assert(zBuf[0]=='\0');
38677 **     return 0;
38678 **   }
38679 **
38680 ** However if an error message is supplied, it will be incorporated
38681 ** by sqlite into the error message available to the user using
38682 ** sqlite3_errmsg(), possibly making IO errors easier to debug.
38683 */
38684 static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
38685   UNUSED_PARAMETER(pVfs);
38686   return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf);
38687 }
38688
38689 /*
38690 ** Initialize and deinitialize the operating system interface.
38691 */
38692 SQLITE_API int SQLITE_STDCALL sqlite3_os_init(void){
38693   static sqlite3_vfs winVfs = {
38694     3,                   /* iVersion */
38695     sizeof(winFile),     /* szOsFile */
38696     SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
38697     0,                   /* pNext */
38698     "win32",             /* zName */
38699     0,                   /* pAppData */
38700     winOpen,             /* xOpen */
38701     winDelete,           /* xDelete */
38702     winAccess,           /* xAccess */
38703     winFullPathname,     /* xFullPathname */
38704     winDlOpen,           /* xDlOpen */
38705     winDlError,          /* xDlError */
38706     winDlSym,            /* xDlSym */
38707     winDlClose,          /* xDlClose */
38708     winRandomness,       /* xRandomness */
38709     winSleep,            /* xSleep */
38710     winCurrentTime,      /* xCurrentTime */
38711     winGetLastError,     /* xGetLastError */
38712     winCurrentTimeInt64, /* xCurrentTimeInt64 */
38713     winSetSystemCall,    /* xSetSystemCall */
38714     winGetSystemCall,    /* xGetSystemCall */
38715     winNextSystemCall,   /* xNextSystemCall */
38716   };
38717 #if defined(SQLITE_WIN32_HAS_WIDE)
38718   static sqlite3_vfs winLongPathVfs = {
38719     3,                   /* iVersion */
38720     sizeof(winFile),     /* szOsFile */
38721     SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
38722     0,                   /* pNext */
38723     "win32-longpath",    /* zName */
38724     0,                   /* pAppData */
38725     winOpen,             /* xOpen */
38726     winDelete,           /* xDelete */
38727     winAccess,           /* xAccess */
38728     winFullPathname,     /* xFullPathname */
38729     winDlOpen,           /* xDlOpen */
38730     winDlError,          /* xDlError */
38731     winDlSym,            /* xDlSym */
38732     winDlClose,          /* xDlClose */
38733     winRandomness,       /* xRandomness */
38734     winSleep,            /* xSleep */
38735     winCurrentTime,      /* xCurrentTime */
38736     winGetLastError,     /* xGetLastError */
38737     winCurrentTimeInt64, /* xCurrentTimeInt64 */
38738     winSetSystemCall,    /* xSetSystemCall */
38739     winGetSystemCall,    /* xGetSystemCall */
38740     winNextSystemCall,   /* xNextSystemCall */
38741   };
38742 #endif
38743
38744   /* Double-check that the aSyscall[] array has been constructed
38745   ** correctly.  See ticket [bb3a86e890c8e96ab] */
38746   assert( ArraySize(aSyscall)==80 );
38747
38748   /* get memory map allocation granularity */
38749   memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
38750 #if SQLITE_OS_WINRT
38751   osGetNativeSystemInfo(&winSysInfo);
38752 #else
38753   osGetSystemInfo(&winSysInfo);
38754 #endif
38755   assert( winSysInfo.dwAllocationGranularity>0 );
38756   assert( winSysInfo.dwPageSize>0 );
38757
38758   sqlite3_vfs_register(&winVfs, 1);
38759
38760 #if defined(SQLITE_WIN32_HAS_WIDE)
38761   sqlite3_vfs_register(&winLongPathVfs, 0);
38762 #endif
38763
38764   return SQLITE_OK;
38765 }
38766
38767 SQLITE_API int SQLITE_STDCALL sqlite3_os_end(void){
38768 #if SQLITE_OS_WINRT
38769   if( sleepObj!=NULL ){
38770     osCloseHandle(sleepObj);
38771     sleepObj = NULL;
38772   }
38773 #endif
38774   return SQLITE_OK;
38775 }
38776
38777 #endif /* SQLITE_OS_WIN */
38778
38779 /************** End of os_win.c **********************************************/
38780 /************** Begin file bitvec.c ******************************************/
38781 /*
38782 ** 2008 February 16
38783 **
38784 ** The author disclaims copyright to this source code.  In place of
38785 ** a legal notice, here is a blessing:
38786 **
38787 **    May you do good and not evil.
38788 **    May you find forgiveness for yourself and forgive others.
38789 **    May you share freely, never taking more than you give.
38790 **
38791 *************************************************************************
38792 ** This file implements an object that represents a fixed-length
38793 ** bitmap.  Bits are numbered starting with 1.
38794 **
38795 ** A bitmap is used to record which pages of a database file have been
38796 ** journalled during a transaction, or which pages have the "dont-write"
38797 ** property.  Usually only a few pages are meet either condition.
38798 ** So the bitmap is usually sparse and has low cardinality.
38799 ** But sometimes (for example when during a DROP of a large table) most
38800 ** or all of the pages in a database can get journalled.  In those cases, 
38801 ** the bitmap becomes dense with high cardinality.  The algorithm needs 
38802 ** to handle both cases well.
38803 **
38804 ** The size of the bitmap is fixed when the object is created.
38805 **
38806 ** All bits are clear when the bitmap is created.  Individual bits
38807 ** may be set or cleared one at a time.
38808 **
38809 ** Test operations are about 100 times more common that set operations.
38810 ** Clear operations are exceedingly rare.  There are usually between
38811 ** 5 and 500 set operations per Bitvec object, though the number of sets can
38812 ** sometimes grow into tens of thousands or larger.  The size of the
38813 ** Bitvec object is the number of pages in the database file at the
38814 ** start of a transaction, and is thus usually less than a few thousand,
38815 ** but can be as large as 2 billion for a really big database.
38816 */
38817
38818 /* Size of the Bitvec structure in bytes. */
38819 #define BITVEC_SZ        512
38820
38821 /* Round the union size down to the nearest pointer boundary, since that's how 
38822 ** it will be aligned within the Bitvec struct. */
38823 #define BITVEC_USIZE     (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
38824
38825 /* Type of the array "element" for the bitmap representation. 
38826 ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE. 
38827 ** Setting this to the "natural word" size of your CPU may improve
38828 ** performance. */
38829 #define BITVEC_TELEM     u8
38830 /* Size, in bits, of the bitmap element. */
38831 #define BITVEC_SZELEM    8
38832 /* Number of elements in a bitmap array. */
38833 #define BITVEC_NELEM     (BITVEC_USIZE/sizeof(BITVEC_TELEM))
38834 /* Number of bits in the bitmap array. */
38835 #define BITVEC_NBIT      (BITVEC_NELEM*BITVEC_SZELEM)
38836
38837 /* Number of u32 values in hash table. */
38838 #define BITVEC_NINT      (BITVEC_USIZE/sizeof(u32))
38839 /* Maximum number of entries in hash table before 
38840 ** sub-dividing and re-hashing. */
38841 #define BITVEC_MXHASH    (BITVEC_NINT/2)
38842 /* Hashing function for the aHash representation.
38843 ** Empirical testing showed that the *37 multiplier 
38844 ** (an arbitrary prime)in the hash function provided 
38845 ** no fewer collisions than the no-op *1. */
38846 #define BITVEC_HASH(X)   (((X)*1)%BITVEC_NINT)
38847
38848 #define BITVEC_NPTR      (BITVEC_USIZE/sizeof(Bitvec *))
38849
38850
38851 /*
38852 ** A bitmap is an instance of the following structure.
38853 **
38854 ** This bitmap records the existence of zero or more bits
38855 ** with values between 1 and iSize, inclusive.
38856 **
38857 ** There are three possible representations of the bitmap.
38858 ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
38859 ** bitmap.  The least significant bit is bit 1.
38860 **
38861 ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
38862 ** a hash table that will hold up to BITVEC_MXHASH distinct values.
38863 **
38864 ** Otherwise, the value i is redirected into one of BITVEC_NPTR
38865 ** sub-bitmaps pointed to by Bitvec.u.apSub[].  Each subbitmap
38866 ** handles up to iDivisor separate values of i.  apSub[0] holds
38867 ** values between 1 and iDivisor.  apSub[1] holds values between
38868 ** iDivisor+1 and 2*iDivisor.  apSub[N] holds values between
38869 ** N*iDivisor+1 and (N+1)*iDivisor.  Each subbitmap is normalized
38870 ** to hold deal with values between 1 and iDivisor.
38871 */
38872 struct Bitvec {
38873   u32 iSize;      /* Maximum bit index.  Max iSize is 4,294,967,296. */
38874   u32 nSet;       /* Number of bits that are set - only valid for aHash
38875                   ** element.  Max is BITVEC_NINT.  For BITVEC_SZ of 512,
38876                   ** this would be 125. */
38877   u32 iDivisor;   /* Number of bits handled by each apSub[] entry. */
38878                   /* Should >=0 for apSub element. */
38879                   /* Max iDivisor is max(u32) / BITVEC_NPTR + 1.  */
38880                   /* For a BITVEC_SZ of 512, this would be 34,359,739. */
38881   union {
38882     BITVEC_TELEM aBitmap[BITVEC_NELEM];    /* Bitmap representation */
38883     u32 aHash[BITVEC_NINT];      /* Hash table representation */
38884     Bitvec *apSub[BITVEC_NPTR];  /* Recursive representation */
38885   } u;
38886 };
38887
38888 /*
38889 ** Create a new bitmap object able to handle bits between 0 and iSize,
38890 ** inclusive.  Return a pointer to the new object.  Return NULL if 
38891 ** malloc fails.
38892 */
38893 SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
38894   Bitvec *p;
38895   assert( sizeof(*p)==BITVEC_SZ );
38896   p = sqlite3MallocZero( sizeof(*p) );
38897   if( p ){
38898     p->iSize = iSize;
38899   }
38900   return p;
38901 }
38902
38903 /*
38904 ** Check to see if the i-th bit is set.  Return true or false.
38905 ** If p is NULL (if the bitmap has not been created) or if
38906 ** i is out of range, then return false.
38907 */
38908 SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
38909   if( p==0 ) return 0;
38910   if( i>p->iSize || i==0 ) return 0;
38911   i--;
38912   while( p->iDivisor ){
38913     u32 bin = i/p->iDivisor;
38914     i = i%p->iDivisor;
38915     p = p->u.apSub[bin];
38916     if (!p) {
38917       return 0;
38918     }
38919   }
38920   if( p->iSize<=BITVEC_NBIT ){
38921     return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
38922   } else{
38923     u32 h = BITVEC_HASH(i++);
38924     while( p->u.aHash[h] ){
38925       if( p->u.aHash[h]==i ) return 1;
38926       h = (h+1) % BITVEC_NINT;
38927     }
38928     return 0;
38929   }
38930 }
38931
38932 /*
38933 ** Set the i-th bit.  Return 0 on success and an error code if
38934 ** anything goes wrong.
38935 **
38936 ** This routine might cause sub-bitmaps to be allocated.  Failing
38937 ** to get the memory needed to hold the sub-bitmap is the only
38938 ** that can go wrong with an insert, assuming p and i are valid.
38939 **
38940 ** The calling function must ensure that p is a valid Bitvec object
38941 ** and that the value for "i" is within range of the Bitvec object.
38942 ** Otherwise the behavior is undefined.
38943 */
38944 SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
38945   u32 h;
38946   if( p==0 ) return SQLITE_OK;
38947   assert( i>0 );
38948   assert( i<=p->iSize );
38949   i--;
38950   while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
38951     u32 bin = i/p->iDivisor;
38952     i = i%p->iDivisor;
38953     if( p->u.apSub[bin]==0 ){
38954       p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
38955       if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
38956     }
38957     p = p->u.apSub[bin];
38958   }
38959   if( p->iSize<=BITVEC_NBIT ){
38960     p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
38961     return SQLITE_OK;
38962   }
38963   h = BITVEC_HASH(i++);
38964   /* if there wasn't a hash collision, and this doesn't */
38965   /* completely fill the hash, then just add it without */
38966   /* worring about sub-dividing and re-hashing. */
38967   if( !p->u.aHash[h] ){
38968     if (p->nSet<(BITVEC_NINT-1)) {
38969       goto bitvec_set_end;
38970     } else {
38971       goto bitvec_set_rehash;
38972     }
38973   }
38974   /* there was a collision, check to see if it's already */
38975   /* in hash, if not, try to find a spot for it */
38976   do {
38977     if( p->u.aHash[h]==i ) return SQLITE_OK;
38978     h++;
38979     if( h>=BITVEC_NINT ) h = 0;
38980   } while( p->u.aHash[h] );
38981   /* we didn't find it in the hash.  h points to the first */
38982   /* available free spot. check to see if this is going to */
38983   /* make our hash too "full".  */
38984 bitvec_set_rehash:
38985   if( p->nSet>=BITVEC_MXHASH ){
38986     unsigned int j;
38987     int rc;
38988     u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
38989     if( aiValues==0 ){
38990       return SQLITE_NOMEM;
38991     }else{
38992       memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
38993       memset(p->u.apSub, 0, sizeof(p->u.apSub));
38994       p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
38995       rc = sqlite3BitvecSet(p, i);
38996       for(j=0; j<BITVEC_NINT; j++){
38997         if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
38998       }
38999       sqlite3StackFree(0, aiValues);
39000       return rc;
39001     }
39002   }
39003 bitvec_set_end:
39004   p->nSet++;
39005   p->u.aHash[h] = i;
39006   return SQLITE_OK;
39007 }
39008
39009 /*
39010 ** Clear the i-th bit.
39011 **
39012 ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
39013 ** that BitvecClear can use to rebuilt its hash table.
39014 */
39015 SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
39016   if( p==0 ) return;
39017   assert( i>0 );
39018   i--;
39019   while( p->iDivisor ){
39020     u32 bin = i/p->iDivisor;
39021     i = i%p->iDivisor;
39022     p = p->u.apSub[bin];
39023     if (!p) {
39024       return;
39025     }
39026   }
39027   if( p->iSize<=BITVEC_NBIT ){
39028     p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
39029   }else{
39030     unsigned int j;
39031     u32 *aiValues = pBuf;
39032     memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
39033     memset(p->u.aHash, 0, sizeof(p->u.aHash));
39034     p->nSet = 0;
39035     for(j=0; j<BITVEC_NINT; j++){
39036       if( aiValues[j] && aiValues[j]!=(i+1) ){
39037         u32 h = BITVEC_HASH(aiValues[j]-1);
39038         p->nSet++;
39039         while( p->u.aHash[h] ){
39040           h++;
39041           if( h>=BITVEC_NINT ) h = 0;
39042         }
39043         p->u.aHash[h] = aiValues[j];
39044       }
39045     }
39046   }
39047 }
39048
39049 /*
39050 ** Destroy a bitmap object.  Reclaim all memory used.
39051 */
39052 SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
39053   if( p==0 ) return;
39054   if( p->iDivisor ){
39055     unsigned int i;
39056     for(i=0; i<BITVEC_NPTR; i++){
39057       sqlite3BitvecDestroy(p->u.apSub[i]);
39058     }
39059   }
39060   sqlite3_free(p);
39061 }
39062
39063 /*
39064 ** Return the value of the iSize parameter specified when Bitvec *p
39065 ** was created.
39066 */
39067 SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
39068   return p->iSize;
39069 }
39070
39071 #ifndef SQLITE_OMIT_BUILTIN_TEST
39072 /*
39073 ** Let V[] be an array of unsigned characters sufficient to hold
39074 ** up to N bits.  Let I be an integer between 0 and N.  0<=I<N.
39075 ** Then the following macros can be used to set, clear, or test
39076 ** individual bits within V.
39077 */
39078 #define SETBIT(V,I)      V[I>>3] |= (1<<(I&7))
39079 #define CLEARBIT(V,I)    V[I>>3] &= ~(1<<(I&7))
39080 #define TESTBIT(V,I)     (V[I>>3]&(1<<(I&7)))!=0
39081
39082 /*
39083 ** This routine runs an extensive test of the Bitvec code.
39084 **
39085 ** The input is an array of integers that acts as a program
39086 ** to test the Bitvec.  The integers are opcodes followed
39087 ** by 0, 1, or 3 operands, depending on the opcode.  Another
39088 ** opcode follows immediately after the last operand.
39089 **
39090 ** There are 6 opcodes numbered from 0 through 5.  0 is the
39091 ** "halt" opcode and causes the test to end.
39092 **
39093 **    0          Halt and return the number of errors
39094 **    1 N S X    Set N bits beginning with S and incrementing by X
39095 **    2 N S X    Clear N bits beginning with S and incrementing by X
39096 **    3 N        Set N randomly chosen bits
39097 **    4 N        Clear N randomly chosen bits
39098 **    5 N S X    Set N bits from S increment X in array only, not in bitvec
39099 **
39100 ** The opcodes 1 through 4 perform set and clear operations are performed
39101 ** on both a Bitvec object and on a linear array of bits obtained from malloc.
39102 ** Opcode 5 works on the linear array only, not on the Bitvec.
39103 ** Opcode 5 is used to deliberately induce a fault in order to
39104 ** confirm that error detection works.
39105 **
39106 ** At the conclusion of the test the linear array is compared
39107 ** against the Bitvec object.  If there are any differences,
39108 ** an error is returned.  If they are the same, zero is returned.
39109 **
39110 ** If a memory allocation error occurs, return -1.
39111 */
39112 SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
39113   Bitvec *pBitvec = 0;
39114   unsigned char *pV = 0;
39115   int rc = -1;
39116   int i, nx, pc, op;
39117   void *pTmpSpace;
39118
39119   /* Allocate the Bitvec to be tested and a linear array of
39120   ** bits to act as the reference */
39121   pBitvec = sqlite3BitvecCreate( sz );
39122   pV = sqlite3MallocZero( (sz+7)/8 + 1 );
39123   pTmpSpace = sqlite3_malloc(BITVEC_SZ);
39124   if( pBitvec==0 || pV==0 || pTmpSpace==0  ) goto bitvec_end;
39125
39126   /* NULL pBitvec tests */
39127   sqlite3BitvecSet(0, 1);
39128   sqlite3BitvecClear(0, 1, pTmpSpace);
39129
39130   /* Run the program */
39131   pc = 0;
39132   while( (op = aOp[pc])!=0 ){
39133     switch( op ){
39134       case 1:
39135       case 2:
39136       case 5: {
39137         nx = 4;
39138         i = aOp[pc+2] - 1;
39139         aOp[pc+2] += aOp[pc+3];
39140         break;
39141       }
39142       case 3:
39143       case 4: 
39144       default: {
39145         nx = 2;
39146         sqlite3_randomness(sizeof(i), &i);
39147         break;
39148       }
39149     }
39150     if( (--aOp[pc+1]) > 0 ) nx = 0;
39151     pc += nx;
39152     i = (i & 0x7fffffff)%sz;
39153     if( (op & 1)!=0 ){
39154       SETBIT(pV, (i+1));
39155       if( op!=5 ){
39156         if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
39157       }
39158     }else{
39159       CLEARBIT(pV, (i+1));
39160       sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
39161     }
39162   }
39163
39164   /* Test to make sure the linear array exactly matches the
39165   ** Bitvec object.  Start with the assumption that they do
39166   ** match (rc==0).  Change rc to non-zero if a discrepancy
39167   ** is found.
39168   */
39169   rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
39170           + sqlite3BitvecTest(pBitvec, 0)
39171           + (sqlite3BitvecSize(pBitvec) - sz);
39172   for(i=1; i<=sz; i++){
39173     if(  (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
39174       rc = i;
39175       break;
39176     }
39177   }
39178
39179   /* Free allocated structure */
39180 bitvec_end:
39181   sqlite3_free(pTmpSpace);
39182   sqlite3_free(pV);
39183   sqlite3BitvecDestroy(pBitvec);
39184   return rc;
39185 }
39186 #endif /* SQLITE_OMIT_BUILTIN_TEST */
39187
39188 /************** End of bitvec.c **********************************************/
39189 /************** Begin file pcache.c ******************************************/
39190 /*
39191 ** 2008 August 05
39192 **
39193 ** The author disclaims copyright to this source code.  In place of
39194 ** a legal notice, here is a blessing:
39195 **
39196 **    May you do good and not evil.
39197 **    May you find forgiveness for yourself and forgive others.
39198 **    May you share freely, never taking more than you give.
39199 **
39200 *************************************************************************
39201 ** This file implements that page cache.
39202 */
39203
39204 /*
39205 ** A complete page cache is an instance of this structure.
39206 */
39207 struct PCache {
39208   PgHdr *pDirty, *pDirtyTail;         /* List of dirty pages in LRU order */
39209   PgHdr *pSynced;                     /* Last synced page in dirty page list */
39210   int nRef;                           /* Number of referenced pages */
39211   int szCache;                        /* Configured cache size */
39212   int szPage;                         /* Size of every page in this cache */
39213   int szExtra;                        /* Size of extra space for each page */
39214   u8 bPurgeable;                      /* True if pages are on backing store */
39215   u8 eCreate;                         /* eCreate value for for xFetch() */
39216   int (*xStress)(void*,PgHdr*);       /* Call to try make a page clean */
39217   void *pStress;                      /* Argument to xStress */
39218   sqlite3_pcache *pCache;             /* Pluggable cache module */
39219   PgHdr *pPage1;                      /* Reference to page 1 */
39220 };
39221
39222 /********************************** Linked List Management ********************/
39223
39224 /* Allowed values for second argument to pcacheManageDirtyList() */
39225 #define PCACHE_DIRTYLIST_REMOVE   1    /* Remove pPage from dirty list */
39226 #define PCACHE_DIRTYLIST_ADD      2    /* Add pPage to the dirty list */
39227 #define PCACHE_DIRTYLIST_FRONT    3    /* Move pPage to the front of the list */
39228
39229 /*
39230 ** Manage pPage's participation on the dirty list.  Bits of the addRemove
39231 ** argument determines what operation to do.  The 0x01 bit means first
39232 ** remove pPage from the dirty list.  The 0x02 means add pPage back to
39233 ** the dirty list.  Doing both moves pPage to the front of the dirty list.
39234 */
39235 static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
39236   PCache *p = pPage->pCache;
39237
39238   if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
39239     assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
39240     assert( pPage->pDirtyPrev || pPage==p->pDirty );
39241   
39242     /* Update the PCache1.pSynced variable if necessary. */
39243     if( p->pSynced==pPage ){
39244       PgHdr *pSynced = pPage->pDirtyPrev;
39245       while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
39246         pSynced = pSynced->pDirtyPrev;
39247       }
39248       p->pSynced = pSynced;
39249     }
39250   
39251     if( pPage->pDirtyNext ){
39252       pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
39253     }else{
39254       assert( pPage==p->pDirtyTail );
39255       p->pDirtyTail = pPage->pDirtyPrev;
39256     }
39257     if( pPage->pDirtyPrev ){
39258       pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
39259     }else{
39260       assert( pPage==p->pDirty );
39261       p->pDirty = pPage->pDirtyNext;
39262       if( p->pDirty==0 && p->bPurgeable ){
39263         assert( p->eCreate==1 );
39264         p->eCreate = 2;
39265       }
39266     }
39267     pPage->pDirtyNext = 0;
39268     pPage->pDirtyPrev = 0;
39269   }
39270   if( addRemove & PCACHE_DIRTYLIST_ADD ){
39271     assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
39272   
39273     pPage->pDirtyNext = p->pDirty;
39274     if( pPage->pDirtyNext ){
39275       assert( pPage->pDirtyNext->pDirtyPrev==0 );
39276       pPage->pDirtyNext->pDirtyPrev = pPage;
39277     }else{
39278       p->pDirtyTail = pPage;
39279       if( p->bPurgeable ){
39280         assert( p->eCreate==2 );
39281         p->eCreate = 1;
39282       }
39283     }
39284     p->pDirty = pPage;
39285     if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
39286       p->pSynced = pPage;
39287     }
39288   }
39289 }
39290
39291 /*
39292 ** Wrapper around the pluggable caches xUnpin method. If the cache is
39293 ** being used for an in-memory database, this function is a no-op.
39294 */
39295 static void pcacheUnpin(PgHdr *p){
39296   if( p->pCache->bPurgeable ){
39297     if( p->pgno==1 ){
39298       p->pCache->pPage1 = 0;
39299     }
39300     sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
39301   }
39302 }
39303
39304 /*
39305 ** Compute the number of pages of cache requested.  p->szCache is the
39306 ** cache size requested by the "PRAGMA cache_size" statement.
39307 **
39308 **
39309 */
39310 static int numberOfCachePages(PCache *p){
39311   if( p->szCache>=0 ){
39312     /* IMPLEMENTATION-OF: R-42059-47211 If the argument N is positive then the
39313     ** suggested cache size is set to N. */
39314     return p->szCache;
39315   }else{
39316     /* IMPLEMENTATION-OF: R-61436-13639 If the argument N is negative, then
39317     ** the number of cache pages is adjusted to use approximately abs(N*1024)
39318     ** bytes of memory. */
39319     return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
39320   }
39321 }
39322
39323 /*************************************************** General Interfaces ******
39324 **
39325 ** Initialize and shutdown the page cache subsystem. Neither of these 
39326 ** functions are threadsafe.
39327 */
39328 SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
39329   if( sqlite3GlobalConfig.pcache2.xInit==0 ){
39330     /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
39331     ** built-in default page cache is used instead of the application defined
39332     ** page cache. */
39333     sqlite3PCacheSetDefault();
39334   }
39335   return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
39336 }
39337 SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
39338   if( sqlite3GlobalConfig.pcache2.xShutdown ){
39339     /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
39340     sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
39341   }
39342 }
39343
39344 /*
39345 ** Return the size in bytes of a PCache object.
39346 */
39347 SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
39348
39349 /*
39350 ** Create a new PCache object. Storage space to hold the object
39351 ** has already been allocated and is passed in as the p pointer. 
39352 ** The caller discovers how much space needs to be allocated by 
39353 ** calling sqlite3PcacheSize().
39354 */
39355 SQLITE_PRIVATE int sqlite3PcacheOpen(
39356   int szPage,                  /* Size of every page */
39357   int szExtra,                 /* Extra space associated with each page */
39358   int bPurgeable,              /* True if pages are on backing store */
39359   int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
39360   void *pStress,               /* Argument to xStress */
39361   PCache *p                    /* Preallocated space for the PCache */
39362 ){
39363   memset(p, 0, sizeof(PCache));
39364   p->szPage = 1;
39365   p->szExtra = szExtra;
39366   p->bPurgeable = bPurgeable;
39367   p->eCreate = 2;
39368   p->xStress = xStress;
39369   p->pStress = pStress;
39370   p->szCache = 100;
39371   return sqlite3PcacheSetPageSize(p, szPage);
39372 }
39373
39374 /*
39375 ** Change the page size for PCache object. The caller must ensure that there
39376 ** are no outstanding page references when this function is called.
39377 */
39378 SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
39379   assert( pCache->nRef==0 && pCache->pDirty==0 );
39380   if( pCache->szPage ){
39381     sqlite3_pcache *pNew;
39382     pNew = sqlite3GlobalConfig.pcache2.xCreate(
39383                 szPage, pCache->szExtra + ROUND8(sizeof(PgHdr)),
39384                 pCache->bPurgeable
39385     );
39386     if( pNew==0 ) return SQLITE_NOMEM;
39387     sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
39388     if( pCache->pCache ){
39389       sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
39390     }
39391     pCache->pCache = pNew;
39392     pCache->pPage1 = 0;
39393     pCache->szPage = szPage;
39394   }
39395   return SQLITE_OK;
39396 }
39397
39398 /*
39399 ** Try to obtain a page from the cache.
39400 **
39401 ** This routine returns a pointer to an sqlite3_pcache_page object if
39402 ** such an object is already in cache, or if a new one is created.
39403 ** This routine returns a NULL pointer if the object was not in cache
39404 ** and could not be created.
39405 **
39406 ** The createFlags should be 0 to check for existing pages and should
39407 ** be 3 (not 1, but 3) to try to create a new page.
39408 **
39409 ** If the createFlag is 0, then NULL is always returned if the page
39410 ** is not already in the cache.  If createFlag is 1, then a new page
39411 ** is created only if that can be done without spilling dirty pages
39412 ** and without exceeding the cache size limit.
39413 **
39414 ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
39415 ** initialize the sqlite3_pcache_page object and convert it into a
39416 ** PgHdr object.  The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
39417 ** routines are split this way for performance reasons. When separated
39418 ** they can both (usually) operate without having to push values to
39419 ** the stack on entry and pop them back off on exit, which saves a
39420 ** lot of pushing and popping.
39421 */
39422 SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
39423   PCache *pCache,       /* Obtain the page from this cache */
39424   Pgno pgno,            /* Page number to obtain */
39425   int createFlag        /* If true, create page if it does not exist already */
39426 ){
39427   int eCreate;
39428
39429   assert( pCache!=0 );
39430   assert( pCache->pCache!=0 );
39431   assert( createFlag==3 || createFlag==0 );
39432   assert( pgno>0 );
39433
39434   /* eCreate defines what to do if the page does not exist.
39435   **    0     Do not allocate a new page.  (createFlag==0)
39436   **    1     Allocate a new page if doing so is inexpensive.
39437   **          (createFlag==1 AND bPurgeable AND pDirty)
39438   **    2     Allocate a new page even it doing so is difficult.
39439   **          (createFlag==1 AND !(bPurgeable AND pDirty)
39440   */
39441   eCreate = createFlag & pCache->eCreate;
39442   assert( eCreate==0 || eCreate==1 || eCreate==2 );
39443   assert( createFlag==0 || pCache->eCreate==eCreate );
39444   assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
39445   return sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
39446 }
39447
39448 /*
39449 ** If the sqlite3PcacheFetch() routine is unable to allocate a new
39450 ** page because new clean pages are available for reuse and the cache
39451 ** size limit has been reached, then this routine can be invoked to 
39452 ** try harder to allocate a page.  This routine might invoke the stress
39453 ** callback to spill dirty pages to the journal.  It will then try to
39454 ** allocate the new page and will only fail to allocate a new page on
39455 ** an OOM error.
39456 **
39457 ** This routine should be invoked only after sqlite3PcacheFetch() fails.
39458 */
39459 SQLITE_PRIVATE int sqlite3PcacheFetchStress(
39460   PCache *pCache,                 /* Obtain the page from this cache */
39461   Pgno pgno,                      /* Page number to obtain */
39462   sqlite3_pcache_page **ppPage    /* Write result here */
39463 ){
39464   PgHdr *pPg;
39465   if( pCache->eCreate==2 ) return 0;
39466
39467
39468   /* Find a dirty page to write-out and recycle. First try to find a 
39469   ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
39470   ** cleared), but if that is not possible settle for any other 
39471   ** unreferenced dirty page.
39472   */
39473   for(pPg=pCache->pSynced; 
39474       pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC)); 
39475       pPg=pPg->pDirtyPrev
39476   );
39477   pCache->pSynced = pPg;
39478   if( !pPg ){
39479     for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
39480   }
39481   if( pPg ){
39482     int rc;
39483 #ifdef SQLITE_LOG_CACHE_SPILL
39484     sqlite3_log(SQLITE_FULL, 
39485                 "spill page %d making room for %d - cache used: %d/%d",
39486                 pPg->pgno, pgno,
39487                 sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
39488                 numberOfCachePages(pCache));
39489 #endif
39490     rc = pCache->xStress(pCache->pStress, pPg);
39491     if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
39492       return rc;
39493     }
39494   }
39495   *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
39496   return *ppPage==0 ? SQLITE_NOMEM : SQLITE_OK;
39497 }
39498
39499 /*
39500 ** This is a helper routine for sqlite3PcacheFetchFinish()
39501 **
39502 ** In the uncommon case where the page being fetched has not been
39503 ** initialized, this routine is invoked to do the initialization.
39504 ** This routine is broken out into a separate function since it
39505 ** requires extra stack manipulation that can be avoided in the common
39506 ** case.
39507 */
39508 static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
39509   PCache *pCache,             /* Obtain the page from this cache */
39510   Pgno pgno,                  /* Page number obtained */
39511   sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
39512 ){
39513   PgHdr *pPgHdr;
39514   assert( pPage!=0 );
39515   pPgHdr = (PgHdr*)pPage->pExtra;
39516   assert( pPgHdr->pPage==0 );
39517  memset(pPgHdr, 0, sizeof(PgHdr));
39518   pPgHdr->pPage = pPage;
39519   pPgHdr->pData = pPage->pBuf;
39520   pPgHdr->pExtra = (void *)&pPgHdr[1];
39521   memset(pPgHdr->pExtra, 0, pCache->szExtra);
39522   pPgHdr->pCache = pCache;
39523   pPgHdr->pgno = pgno;
39524   return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
39525 }
39526
39527 /*
39528 ** This routine converts the sqlite3_pcache_page object returned by
39529 ** sqlite3PcacheFetch() into an initialized PgHdr object.  This routine
39530 ** must be called after sqlite3PcacheFetch() in order to get a usable
39531 ** result.
39532 */
39533 SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
39534   PCache *pCache,             /* Obtain the page from this cache */
39535   Pgno pgno,                  /* Page number obtained */
39536   sqlite3_pcache_page *pPage  /* Page obtained by prior PcacheFetch() call */
39537 ){
39538   PgHdr *pPgHdr;
39539
39540   if( pPage==0 ) return 0;
39541   pPgHdr = (PgHdr *)pPage->pExtra;
39542
39543   if( !pPgHdr->pPage ){
39544     return pcacheFetchFinishWithInit(pCache, pgno, pPage);
39545   }
39546   if( 0==pPgHdr->nRef ){
39547     pCache->nRef++;
39548   }
39549   pPgHdr->nRef++;
39550   if( pgno==1 ){
39551     pCache->pPage1 = pPgHdr;
39552   }
39553   return pPgHdr;
39554 }
39555
39556 /*
39557 ** Decrement the reference count on a page. If the page is clean and the
39558 ** reference count drops to 0, then it is made eligible for recycling.
39559 */
39560 SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
39561   assert( p->nRef>0 );
39562   p->nRef--;
39563   if( p->nRef==0 ){
39564     p->pCache->nRef--;
39565     if( (p->flags&PGHDR_DIRTY)==0 ){
39566       pcacheUnpin(p);
39567     }else if( p->pDirtyPrev!=0 ){
39568       /* Move the page to the head of the dirty list. */
39569       pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
39570     }
39571   }
39572 }
39573
39574 /*
39575 ** Increase the reference count of a supplied page by 1.
39576 */
39577 SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
39578   assert(p->nRef>0);
39579   p->nRef++;
39580 }
39581
39582 /*
39583 ** Drop a page from the cache. There must be exactly one reference to the
39584 ** page. This function deletes that reference, so after it returns the
39585 ** page pointed to by p is invalid.
39586 */
39587 SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
39588   assert( p->nRef==1 );
39589   if( p->flags&PGHDR_DIRTY ){
39590     pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
39591   }
39592   p->pCache->nRef--;
39593   if( p->pgno==1 ){
39594     p->pCache->pPage1 = 0;
39595   }
39596   sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
39597 }
39598
39599 /*
39600 ** Make sure the page is marked as dirty. If it isn't dirty already,
39601 ** make it so.
39602 */
39603 SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
39604   p->flags &= ~PGHDR_DONT_WRITE;
39605   assert( p->nRef>0 );
39606   if( 0==(p->flags & PGHDR_DIRTY) ){
39607     p->flags |= PGHDR_DIRTY;
39608     pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
39609   }
39610 }
39611
39612 /*
39613 ** Make sure the page is marked as clean. If it isn't clean already,
39614 ** make it so.
39615 */
39616 SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
39617   if( (p->flags & PGHDR_DIRTY) ){
39618     pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
39619     p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
39620     if( p->nRef==0 ){
39621       pcacheUnpin(p);
39622     }
39623   }
39624 }
39625
39626 /*
39627 ** Make every page in the cache clean.
39628 */
39629 SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
39630   PgHdr *p;
39631   while( (p = pCache->pDirty)!=0 ){
39632     sqlite3PcacheMakeClean(p);
39633   }
39634 }
39635
39636 /*
39637 ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
39638 */
39639 SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
39640   PgHdr *p;
39641   for(p=pCache->pDirty; p; p=p->pDirtyNext){
39642     p->flags &= ~PGHDR_NEED_SYNC;
39643   }
39644   pCache->pSynced = pCache->pDirtyTail;
39645 }
39646
39647 /*
39648 ** Change the page number of page p to newPgno. 
39649 */
39650 SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
39651   PCache *pCache = p->pCache;
39652   assert( p->nRef>0 );
39653   assert( newPgno>0 );
39654   sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
39655   p->pgno = newPgno;
39656   if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
39657     pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
39658   }
39659 }
39660
39661 /*
39662 ** Drop every cache entry whose page number is greater than "pgno". The
39663 ** caller must ensure that there are no outstanding references to any pages
39664 ** other than page 1 with a page number greater than pgno.
39665 **
39666 ** If there is a reference to page 1 and the pgno parameter passed to this
39667 ** function is 0, then the data area associated with page 1 is zeroed, but
39668 ** the page object is not dropped.
39669 */
39670 SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
39671   if( pCache->pCache ){
39672     PgHdr *p;
39673     PgHdr *pNext;
39674     for(p=pCache->pDirty; p; p=pNext){
39675       pNext = p->pDirtyNext;
39676       /* This routine never gets call with a positive pgno except right
39677       ** after sqlite3PcacheCleanAll().  So if there are dirty pages,
39678       ** it must be that pgno==0.
39679       */
39680       assert( p->pgno>0 );
39681       if( ALWAYS(p->pgno>pgno) ){
39682         assert( p->flags&PGHDR_DIRTY );
39683         sqlite3PcacheMakeClean(p);
39684       }
39685     }
39686     if( pgno==0 && pCache->pPage1 ){
39687       memset(pCache->pPage1->pData, 0, pCache->szPage);
39688       pgno = 1;
39689     }
39690     sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
39691   }
39692 }
39693
39694 /*
39695 ** Close a cache.
39696 */
39697 SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
39698   assert( pCache->pCache!=0 );
39699   sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
39700 }
39701
39702 /* 
39703 ** Discard the contents of the cache.
39704 */
39705 SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
39706   sqlite3PcacheTruncate(pCache, 0);
39707 }
39708
39709 /*
39710 ** Merge two lists of pages connected by pDirty and in pgno order.
39711 ** Do not both fixing the pDirtyPrev pointers.
39712 */
39713 static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
39714   PgHdr result, *pTail;
39715   pTail = &result;
39716   while( pA && pB ){
39717     if( pA->pgno<pB->pgno ){
39718       pTail->pDirty = pA;
39719       pTail = pA;
39720       pA = pA->pDirty;
39721     }else{
39722       pTail->pDirty = pB;
39723       pTail = pB;
39724       pB = pB->pDirty;
39725     }
39726   }
39727   if( pA ){
39728     pTail->pDirty = pA;
39729   }else if( pB ){
39730     pTail->pDirty = pB;
39731   }else{
39732     pTail->pDirty = 0;
39733   }
39734   return result.pDirty;
39735 }
39736
39737 /*
39738 ** Sort the list of pages in accending order by pgno.  Pages are
39739 ** connected by pDirty pointers.  The pDirtyPrev pointers are
39740 ** corrupted by this sort.
39741 **
39742 ** Since there cannot be more than 2^31 distinct pages in a database,
39743 ** there cannot be more than 31 buckets required by the merge sorter.
39744 ** One extra bucket is added to catch overflow in case something
39745 ** ever changes to make the previous sentence incorrect.
39746 */
39747 #define N_SORT_BUCKET  32
39748 static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
39749   PgHdr *a[N_SORT_BUCKET], *p;
39750   int i;
39751   memset(a, 0, sizeof(a));
39752   while( pIn ){
39753     p = pIn;
39754     pIn = p->pDirty;
39755     p->pDirty = 0;
39756     for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
39757       if( a[i]==0 ){
39758         a[i] = p;
39759         break;
39760       }else{
39761         p = pcacheMergeDirtyList(a[i], p);
39762         a[i] = 0;
39763       }
39764     }
39765     if( NEVER(i==N_SORT_BUCKET-1) ){
39766       /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
39767       ** the input list.  But that is impossible.
39768       */
39769       a[i] = pcacheMergeDirtyList(a[i], p);
39770     }
39771   }
39772   p = a[0];
39773   for(i=1; i<N_SORT_BUCKET; i++){
39774     p = pcacheMergeDirtyList(p, a[i]);
39775   }
39776   return p;
39777 }
39778
39779 /*
39780 ** Return a list of all dirty pages in the cache, sorted by page number.
39781 */
39782 SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
39783   PgHdr *p;
39784   for(p=pCache->pDirty; p; p=p->pDirtyNext){
39785     p->pDirty = p->pDirtyNext;
39786   }
39787   return pcacheSortDirtyList(pCache->pDirty);
39788 }
39789
39790 /* 
39791 ** Return the total number of referenced pages held by the cache.
39792 */
39793 SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
39794   return pCache->nRef;
39795 }
39796
39797 /*
39798 ** Return the number of references to the page supplied as an argument.
39799 */
39800 SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
39801   return p->nRef;
39802 }
39803
39804 /* 
39805 ** Return the total number of pages in the cache.
39806 */
39807 SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
39808   assert( pCache->pCache!=0 );
39809   return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
39810 }
39811
39812 #ifdef SQLITE_TEST
39813 /*
39814 ** Get the suggested cache-size value.
39815 */
39816 SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
39817   return numberOfCachePages(pCache);
39818 }
39819 #endif
39820
39821 /*
39822 ** Set the suggested cache-size value.
39823 */
39824 SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
39825   assert( pCache->pCache!=0 );
39826   pCache->szCache = mxPage;
39827   sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
39828                                          numberOfCachePages(pCache));
39829 }
39830
39831 /*
39832 ** Free up as much memory as possible from the page cache.
39833 */
39834 SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
39835   assert( pCache->pCache!=0 );
39836   sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
39837 }
39838
39839 /*
39840 ** Return the size of the header added by this middleware layer
39841 ** in the page-cache hierarchy.
39842 */
39843 SQLITE_PRIVATE int sqlite3HeaderSizePcache(void){ return ROUND8(sizeof(PgHdr)); }
39844
39845
39846 #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
39847 /*
39848 ** For all dirty pages currently in the cache, invoke the specified
39849 ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
39850 ** defined.
39851 */
39852 SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
39853   PgHdr *pDirty;
39854   for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
39855     xIter(pDirty);
39856   }
39857 }
39858 #endif
39859
39860 /************** End of pcache.c **********************************************/
39861 /************** Begin file pcache1.c *****************************************/
39862 /*
39863 ** 2008 November 05
39864 **
39865 ** The author disclaims copyright to this source code.  In place of
39866 ** a legal notice, here is a blessing:
39867 **
39868 **    May you do good and not evil.
39869 **    May you find forgiveness for yourself and forgive others.
39870 **    May you share freely, never taking more than you give.
39871 **
39872 *************************************************************************
39873 **
39874 ** This file implements the default page cache implementation (the
39875 ** sqlite3_pcache interface). It also contains part of the implementation
39876 ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
39877 ** If the default page cache implementation is overridden, then neither of
39878 ** these two features are available.
39879 */
39880
39881
39882 typedef struct PCache1 PCache1;
39883 typedef struct PgHdr1 PgHdr1;
39884 typedef struct PgFreeslot PgFreeslot;
39885 typedef struct PGroup PGroup;
39886
39887 /* Each page cache (or PCache) belongs to a PGroup.  A PGroup is a set 
39888 ** of one or more PCaches that are able to recycle each other's unpinned
39889 ** pages when they are under memory pressure.  A PGroup is an instance of
39890 ** the following object.
39891 **
39892 ** This page cache implementation works in one of two modes:
39893 **
39894 **   (1)  Every PCache is the sole member of its own PGroup.  There is
39895 **        one PGroup per PCache.
39896 **
39897 **   (2)  There is a single global PGroup that all PCaches are a member
39898 **        of.
39899 **
39900 ** Mode 1 uses more memory (since PCache instances are not able to rob
39901 ** unused pages from other PCaches) but it also operates without a mutex,
39902 ** and is therefore often faster.  Mode 2 requires a mutex in order to be
39903 ** threadsafe, but recycles pages more efficiently.
39904 **
39905 ** For mode (1), PGroup.mutex is NULL.  For mode (2) there is only a single
39906 ** PGroup which is the pcache1.grp global variable and its mutex is
39907 ** SQLITE_MUTEX_STATIC_LRU.
39908 */
39909 struct PGroup {
39910   sqlite3_mutex *mutex;          /* MUTEX_STATIC_LRU or NULL */
39911   unsigned int nMaxPage;         /* Sum of nMax for purgeable caches */
39912   unsigned int nMinPage;         /* Sum of nMin for purgeable caches */
39913   unsigned int mxPinned;         /* nMaxpage + 10 - nMinPage */
39914   unsigned int nCurrentPage;     /* Number of purgeable pages allocated */
39915   PgHdr1 *pLruHead, *pLruTail;   /* LRU list of unpinned pages */
39916 };
39917
39918 /* Each page cache is an instance of the following object.  Every
39919 ** open database file (including each in-memory database and each
39920 ** temporary or transient database) has a single page cache which
39921 ** is an instance of this object.
39922 **
39923 ** Pointers to structures of this type are cast and returned as 
39924 ** opaque sqlite3_pcache* handles.
39925 */
39926 struct PCache1 {
39927   /* Cache configuration parameters. Page size (szPage) and the purgeable
39928   ** flag (bPurgeable) are set when the cache is created. nMax may be 
39929   ** modified at any time by a call to the pcache1Cachesize() method.
39930   ** The PGroup mutex must be held when accessing nMax.
39931   */
39932   PGroup *pGroup;                     /* PGroup this cache belongs to */
39933   int szPage;                         /* Size of allocated pages in bytes */
39934   int szExtra;                        /* Size of extra space in bytes */
39935   int bPurgeable;                     /* True if cache is purgeable */
39936   unsigned int nMin;                  /* Minimum number of pages reserved */
39937   unsigned int nMax;                  /* Configured "cache_size" value */
39938   unsigned int n90pct;                /* nMax*9/10 */
39939   unsigned int iMaxKey;               /* Largest key seen since xTruncate() */
39940
39941   /* Hash table of all pages. The following variables may only be accessed
39942   ** when the accessor is holding the PGroup mutex.
39943   */
39944   unsigned int nRecyclable;           /* Number of pages in the LRU list */
39945   unsigned int nPage;                 /* Total number of pages in apHash */
39946   unsigned int nHash;                 /* Number of slots in apHash[] */
39947   PgHdr1 **apHash;                    /* Hash table for fast lookup by key */
39948 };
39949
39950 /*
39951 ** Each cache entry is represented by an instance of the following 
39952 ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
39953 ** PgHdr1.pCache->szPage bytes is allocated directly before this structure 
39954 ** in memory.
39955 */
39956 struct PgHdr1 {
39957   sqlite3_pcache_page page;
39958   unsigned int iKey;             /* Key value (page number) */
39959   u8 isPinned;                   /* Page in use, not on the LRU list */
39960   PgHdr1 *pNext;                 /* Next in hash table chain */
39961   PCache1 *pCache;               /* Cache that currently owns this page */
39962   PgHdr1 *pLruNext;              /* Next in LRU list of unpinned pages */
39963   PgHdr1 *pLruPrev;              /* Previous in LRU list of unpinned pages */
39964 };
39965
39966 /*
39967 ** Free slots in the allocator used to divide up the buffer provided using
39968 ** the SQLITE_CONFIG_PAGECACHE mechanism.
39969 */
39970 struct PgFreeslot {
39971   PgFreeslot *pNext;  /* Next free slot */
39972 };
39973
39974 /*
39975 ** Global data used by this cache.
39976 */
39977 static SQLITE_WSD struct PCacheGlobal {
39978   PGroup grp;                    /* The global PGroup for mode (2) */
39979
39980   /* Variables related to SQLITE_CONFIG_PAGECACHE settings.  The
39981   ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
39982   ** fixed at sqlite3_initialize() time and do not require mutex protection.
39983   ** The nFreeSlot and pFree values do require mutex protection.
39984   */
39985   int isInit;                    /* True if initialized */
39986   int szSlot;                    /* Size of each free slot */
39987   int nSlot;                     /* The number of pcache slots */
39988   int nReserve;                  /* Try to keep nFreeSlot above this */
39989   void *pStart, *pEnd;           /* Bounds of pagecache malloc range */
39990   /* Above requires no mutex.  Use mutex below for variable that follow. */
39991   sqlite3_mutex *mutex;          /* Mutex for accessing the following: */
39992   PgFreeslot *pFree;             /* Free page blocks */
39993   int nFreeSlot;                 /* Number of unused pcache slots */
39994   /* The following value requires a mutex to change.  We skip the mutex on
39995   ** reading because (1) most platforms read a 32-bit integer atomically and
39996   ** (2) even if an incorrect value is read, no great harm is done since this
39997   ** is really just an optimization. */
39998   int bUnderPressure;            /* True if low on PAGECACHE memory */
39999 } pcache1_g;
40000
40001 /*
40002 ** All code in this file should access the global structure above via the
40003 ** alias "pcache1". This ensures that the WSD emulation is used when
40004 ** compiling for systems that do not support real WSD.
40005 */
40006 #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
40007
40008 /*
40009 ** Macros to enter and leave the PCache LRU mutex.
40010 */
40011 #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
40012 #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
40013
40014 /******************************************************************************/
40015 /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
40016
40017 /*
40018 ** This function is called during initialization if a static buffer is 
40019 ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
40020 ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
40021 ** enough to contain 'n' buffers of 'sz' bytes each.
40022 **
40023 ** This routine is called from sqlite3_initialize() and so it is guaranteed
40024 ** to be serialized already.  There is no need for further mutexing.
40025 */
40026 SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
40027   if( pcache1.isInit ){
40028     PgFreeslot *p;
40029     sz = ROUNDDOWN8(sz);
40030     pcache1.szSlot = sz;
40031     pcache1.nSlot = pcache1.nFreeSlot = n;
40032     pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
40033     pcache1.pStart = pBuf;
40034     pcache1.pFree = 0;
40035     pcache1.bUnderPressure = 0;
40036     while( n-- ){
40037       p = (PgFreeslot*)pBuf;
40038       p->pNext = pcache1.pFree;
40039       pcache1.pFree = p;
40040       pBuf = (void*)&((char*)pBuf)[sz];
40041     }
40042     pcache1.pEnd = pBuf;
40043   }
40044 }
40045
40046 /*
40047 ** Malloc function used within this file to allocate space from the buffer
40048 ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no 
40049 ** such buffer exists or there is no space left in it, this function falls 
40050 ** back to sqlite3Malloc().
40051 **
40052 ** Multiple threads can run this routine at the same time.  Global variables
40053 ** in pcache1 need to be protected via mutex.
40054 */
40055 static void *pcache1Alloc(int nByte){
40056   void *p = 0;
40057   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
40058   if( nByte<=pcache1.szSlot ){
40059     sqlite3_mutex_enter(pcache1.mutex);
40060     p = (PgHdr1 *)pcache1.pFree;
40061     if( p ){
40062       pcache1.pFree = pcache1.pFree->pNext;
40063       pcache1.nFreeSlot--;
40064       pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
40065       assert( pcache1.nFreeSlot>=0 );
40066       sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
40067       sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_USED, 1);
40068     }
40069     sqlite3_mutex_leave(pcache1.mutex);
40070   }
40071   if( p==0 ){
40072     /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool.  Get
40073     ** it from sqlite3Malloc instead.
40074     */
40075     p = sqlite3Malloc(nByte);
40076 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
40077     if( p ){
40078       int sz = sqlite3MallocSize(p);
40079       sqlite3_mutex_enter(pcache1.mutex);
40080       sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
40081       sqlite3StatusUp(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
40082       sqlite3_mutex_leave(pcache1.mutex);
40083     }
40084 #endif
40085     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
40086   }
40087   return p;
40088 }
40089
40090 /*
40091 ** Free an allocated buffer obtained from pcache1Alloc().
40092 */
40093 static int pcache1Free(void *p){
40094   int nFreed = 0;
40095   if( p==0 ) return 0;
40096   if( p>=pcache1.pStart && p<pcache1.pEnd ){
40097     PgFreeslot *pSlot;
40098     sqlite3_mutex_enter(pcache1.mutex);
40099     sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_USED, 1);
40100     pSlot = (PgFreeslot*)p;
40101     pSlot->pNext = pcache1.pFree;
40102     pcache1.pFree = pSlot;
40103     pcache1.nFreeSlot++;
40104     pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
40105     assert( pcache1.nFreeSlot<=pcache1.nSlot );
40106     sqlite3_mutex_leave(pcache1.mutex);
40107   }else{
40108     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
40109     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
40110     nFreed = sqlite3MallocSize(p);
40111 #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
40112     sqlite3_mutex_enter(pcache1.mutex);
40113     sqlite3StatusDown(SQLITE_STATUS_PAGECACHE_OVERFLOW, nFreed);
40114     sqlite3_mutex_leave(pcache1.mutex);
40115 #endif
40116     sqlite3_free(p);
40117   }
40118   return nFreed;
40119 }
40120
40121 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
40122 /*
40123 ** Return the size of a pcache allocation
40124 */
40125 static int pcache1MemSize(void *p){
40126   if( p>=pcache1.pStart && p<pcache1.pEnd ){
40127     return pcache1.szSlot;
40128   }else{
40129     int iSize;
40130     assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
40131     sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
40132     iSize = sqlite3MallocSize(p);
40133     sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
40134     return iSize;
40135   }
40136 }
40137 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
40138
40139 /*
40140 ** Allocate a new page object initially associated with cache pCache.
40141 */
40142 static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
40143   PgHdr1 *p = 0;
40144   void *pPg;
40145
40146   /* The group mutex must be released before pcache1Alloc() is called. This
40147   ** is because it may call sqlite3_release_memory(), which assumes that 
40148   ** this mutex is not held. */
40149   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
40150   pcache1LeaveMutex(pCache->pGroup);
40151 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
40152   pPg = pcache1Alloc(pCache->szPage);
40153   p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
40154   if( !pPg || !p ){
40155     pcache1Free(pPg);
40156     sqlite3_free(p);
40157     pPg = 0;
40158   }
40159 #else
40160   pPg = pcache1Alloc(ROUND8(sizeof(PgHdr1)) + pCache->szPage + pCache->szExtra);
40161   p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
40162 #endif
40163   pcache1EnterMutex(pCache->pGroup);
40164
40165   if( pPg ){
40166     p->page.pBuf = pPg;
40167     p->page.pExtra = &p[1];
40168     if( pCache->bPurgeable ){
40169       pCache->pGroup->nCurrentPage++;
40170     }
40171     return p;
40172   }
40173   return 0;
40174 }
40175
40176 /*
40177 ** Free a page object allocated by pcache1AllocPage().
40178 **
40179 ** The pointer is allowed to be NULL, which is prudent.  But it turns out
40180 ** that the current implementation happens to never call this routine
40181 ** with a NULL pointer, so we mark the NULL test with ALWAYS().
40182 */
40183 static void pcache1FreePage(PgHdr1 *p){
40184   if( ALWAYS(p) ){
40185     PCache1 *pCache = p->pCache;
40186     assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
40187     pcache1Free(p->page.pBuf);
40188 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
40189     sqlite3_free(p);
40190 #endif
40191     if( pCache->bPurgeable ){
40192       pCache->pGroup->nCurrentPage--;
40193     }
40194   }
40195 }
40196
40197 /*
40198 ** Malloc function used by SQLite to obtain space from the buffer configured
40199 ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
40200 ** exists, this function falls back to sqlite3Malloc().
40201 */
40202 SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
40203   return pcache1Alloc(sz);
40204 }
40205
40206 /*
40207 ** Free an allocated buffer obtained from sqlite3PageMalloc().
40208 */
40209 SQLITE_PRIVATE void sqlite3PageFree(void *p){
40210   pcache1Free(p);
40211 }
40212
40213
40214 /*
40215 ** Return true if it desirable to avoid allocating a new page cache
40216 ** entry.
40217 **
40218 ** If memory was allocated specifically to the page cache using
40219 ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
40220 ** it is desirable to avoid allocating a new page cache entry because
40221 ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
40222 ** for all page cache needs and we should not need to spill the
40223 ** allocation onto the heap.
40224 **
40225 ** Or, the heap is used for all page cache memory but the heap is
40226 ** under memory pressure, then again it is desirable to avoid
40227 ** allocating a new page cache entry in order to avoid stressing
40228 ** the heap even further.
40229 */
40230 static int pcache1UnderMemoryPressure(PCache1 *pCache){
40231   if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
40232     return pcache1.bUnderPressure;
40233   }else{
40234     return sqlite3HeapNearlyFull();
40235   }
40236 }
40237
40238 /******************************************************************************/
40239 /******** General Implementation Functions ************************************/
40240
40241 /*
40242 ** This function is used to resize the hash table used by the cache passed
40243 ** as the first argument.
40244 **
40245 ** The PCache mutex must be held when this function is called.
40246 */
40247 static void pcache1ResizeHash(PCache1 *p){
40248   PgHdr1 **apNew;
40249   unsigned int nNew;
40250   unsigned int i;
40251
40252   assert( sqlite3_mutex_held(p->pGroup->mutex) );
40253
40254   nNew = p->nHash*2;
40255   if( nNew<256 ){
40256     nNew = 256;
40257   }
40258
40259   pcache1LeaveMutex(p->pGroup);
40260   if( p->nHash ){ sqlite3BeginBenignMalloc(); }
40261   apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
40262   if( p->nHash ){ sqlite3EndBenignMalloc(); }
40263   pcache1EnterMutex(p->pGroup);
40264   if( apNew ){
40265     for(i=0; i<p->nHash; i++){
40266       PgHdr1 *pPage;
40267       PgHdr1 *pNext = p->apHash[i];
40268       while( (pPage = pNext)!=0 ){
40269         unsigned int h = pPage->iKey % nNew;
40270         pNext = pPage->pNext;
40271         pPage->pNext = apNew[h];
40272         apNew[h] = pPage;
40273       }
40274     }
40275     sqlite3_free(p->apHash);
40276     p->apHash = apNew;
40277     p->nHash = nNew;
40278   }
40279 }
40280
40281 /*
40282 ** This function is used internally to remove the page pPage from the 
40283 ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
40284 ** LRU list, then this function is a no-op.
40285 **
40286 ** The PGroup mutex must be held when this function is called.
40287 */
40288 static void pcache1PinPage(PgHdr1 *pPage){
40289   PCache1 *pCache;
40290   PGroup *pGroup;
40291
40292   assert( pPage!=0 );
40293   assert( pPage->isPinned==0 );
40294   pCache = pPage->pCache;
40295   pGroup = pCache->pGroup;
40296   assert( pPage->pLruNext || pPage==pGroup->pLruTail );
40297   assert( pPage->pLruPrev || pPage==pGroup->pLruHead );
40298   assert( sqlite3_mutex_held(pGroup->mutex) );
40299   if( pPage->pLruPrev ){
40300     pPage->pLruPrev->pLruNext = pPage->pLruNext;
40301   }else{
40302     pGroup->pLruHead = pPage->pLruNext;
40303   }
40304   if( pPage->pLruNext ){
40305     pPage->pLruNext->pLruPrev = pPage->pLruPrev;
40306   }else{
40307     pGroup->pLruTail = pPage->pLruPrev;
40308   }
40309   pPage->pLruNext = 0;
40310   pPage->pLruPrev = 0;
40311   pPage->isPinned = 1;
40312   pCache->nRecyclable--;
40313 }
40314
40315
40316 /*
40317 ** Remove the page supplied as an argument from the hash table 
40318 ** (PCache1.apHash structure) that it is currently stored in.
40319 **
40320 ** The PGroup mutex must be held when this function is called.
40321 */
40322 static void pcache1RemoveFromHash(PgHdr1 *pPage){
40323   unsigned int h;
40324   PCache1 *pCache = pPage->pCache;
40325   PgHdr1 **pp;
40326
40327   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
40328   h = pPage->iKey % pCache->nHash;
40329   for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
40330   *pp = (*pp)->pNext;
40331
40332   pCache->nPage--;
40333 }
40334
40335 /*
40336 ** If there are currently more than nMaxPage pages allocated, try
40337 ** to recycle pages to reduce the number allocated to nMaxPage.
40338 */
40339 static void pcache1EnforceMaxPage(PGroup *pGroup){
40340   assert( sqlite3_mutex_held(pGroup->mutex) );
40341   while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
40342     PgHdr1 *p = pGroup->pLruTail;
40343     assert( p->pCache->pGroup==pGroup );
40344     assert( p->isPinned==0 );
40345     pcache1PinPage(p);
40346     pcache1RemoveFromHash(p);
40347     pcache1FreePage(p);
40348   }
40349 }
40350
40351 /*
40352 ** Discard all pages from cache pCache with a page number (key value) 
40353 ** greater than or equal to iLimit. Any pinned pages that meet this 
40354 ** criteria are unpinned before they are discarded.
40355 **
40356 ** The PCache mutex must be held when this function is called.
40357 */
40358 static void pcache1TruncateUnsafe(
40359   PCache1 *pCache,             /* The cache to truncate */
40360   unsigned int iLimit          /* Drop pages with this pgno or larger */
40361 ){
40362   TESTONLY( unsigned int nPage = 0; )  /* To assert pCache->nPage is correct */
40363   unsigned int h;
40364   assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
40365   for(h=0; h<pCache->nHash; h++){
40366     PgHdr1 **pp = &pCache->apHash[h]; 
40367     PgHdr1 *pPage;
40368     while( (pPage = *pp)!=0 ){
40369       if( pPage->iKey>=iLimit ){
40370         pCache->nPage--;
40371         *pp = pPage->pNext;
40372         if( !pPage->isPinned ) pcache1PinPage(pPage);
40373         pcache1FreePage(pPage);
40374       }else{
40375         pp = &pPage->pNext;
40376         TESTONLY( nPage++; )
40377       }
40378     }
40379   }
40380   assert( pCache->nPage==nPage );
40381 }
40382
40383 /******************************************************************************/
40384 /******** sqlite3_pcache Methods **********************************************/
40385
40386 /*
40387 ** Implementation of the sqlite3_pcache.xInit method.
40388 */
40389 static int pcache1Init(void *NotUsed){
40390   UNUSED_PARAMETER(NotUsed);
40391   assert( pcache1.isInit==0 );
40392   memset(&pcache1, 0, sizeof(pcache1));
40393   if( sqlite3GlobalConfig.bCoreMutex ){
40394     pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
40395     pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
40396   }
40397   pcache1.grp.mxPinned = 10;
40398   pcache1.isInit = 1;
40399   return SQLITE_OK;
40400 }
40401
40402 /*
40403 ** Implementation of the sqlite3_pcache.xShutdown method.
40404 ** Note that the static mutex allocated in xInit does 
40405 ** not need to be freed.
40406 */
40407 static void pcache1Shutdown(void *NotUsed){
40408   UNUSED_PARAMETER(NotUsed);
40409   assert( pcache1.isInit!=0 );
40410   memset(&pcache1, 0, sizeof(pcache1));
40411 }
40412
40413 /* forward declaration */
40414 static void pcache1Destroy(sqlite3_pcache *p);
40415
40416 /*
40417 ** Implementation of the sqlite3_pcache.xCreate method.
40418 **
40419 ** Allocate a new cache.
40420 */
40421 static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
40422   PCache1 *pCache;      /* The newly created page cache */
40423   PGroup *pGroup;       /* The group the new page cache will belong to */
40424   int sz;               /* Bytes of memory required to allocate the new cache */
40425
40426   /*
40427   ** The separateCache variable is true if each PCache has its own private
40428   ** PGroup.  In other words, separateCache is true for mode (1) where no
40429   ** mutexing is required.
40430   **
40431   **   *  Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
40432   **
40433   **   *  Always use a unified cache in single-threaded applications
40434   **
40435   **   *  Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
40436   **      use separate caches (mode-1)
40437   */
40438 #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
40439   const int separateCache = 0;
40440 #else
40441   int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
40442 #endif
40443
40444   assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
40445   assert( szExtra < 300 );
40446
40447   sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
40448   pCache = (PCache1 *)sqlite3MallocZero(sz);
40449   if( pCache ){
40450     if( separateCache ){
40451       pGroup = (PGroup*)&pCache[1];
40452       pGroup->mxPinned = 10;
40453     }else{
40454       pGroup = &pcache1.grp;
40455     }
40456     pCache->pGroup = pGroup;
40457     pCache->szPage = szPage;
40458     pCache->szExtra = szExtra;
40459     pCache->bPurgeable = (bPurgeable ? 1 : 0);
40460     pcache1EnterMutex(pGroup);
40461     pcache1ResizeHash(pCache);
40462     if( bPurgeable ){
40463       pCache->nMin = 10;
40464       pGroup->nMinPage += pCache->nMin;
40465       pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
40466     }
40467     pcache1LeaveMutex(pGroup);
40468     if( pCache->nHash==0 ){
40469       pcache1Destroy((sqlite3_pcache*)pCache);
40470       pCache = 0;
40471     }
40472   }
40473   return (sqlite3_pcache *)pCache;
40474 }
40475
40476 /*
40477 ** Implementation of the sqlite3_pcache.xCachesize method. 
40478 **
40479 ** Configure the cache_size limit for a cache.
40480 */
40481 static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
40482   PCache1 *pCache = (PCache1 *)p;
40483   if( pCache->bPurgeable ){
40484     PGroup *pGroup = pCache->pGroup;
40485     pcache1EnterMutex(pGroup);
40486     pGroup->nMaxPage += (nMax - pCache->nMax);
40487     pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
40488     pCache->nMax = nMax;
40489     pCache->n90pct = pCache->nMax*9/10;
40490     pcache1EnforceMaxPage(pGroup);
40491     pcache1LeaveMutex(pGroup);
40492   }
40493 }
40494
40495 /*
40496 ** Implementation of the sqlite3_pcache.xShrink method. 
40497 **
40498 ** Free up as much memory as possible.
40499 */
40500 static void pcache1Shrink(sqlite3_pcache *p){
40501   PCache1 *pCache = (PCache1*)p;
40502   if( pCache->bPurgeable ){
40503     PGroup *pGroup = pCache->pGroup;
40504     int savedMaxPage;
40505     pcache1EnterMutex(pGroup);
40506     savedMaxPage = pGroup->nMaxPage;
40507     pGroup->nMaxPage = 0;
40508     pcache1EnforceMaxPage(pGroup);
40509     pGroup->nMaxPage = savedMaxPage;
40510     pcache1LeaveMutex(pGroup);
40511   }
40512 }
40513
40514 /*
40515 ** Implementation of the sqlite3_pcache.xPagecount method. 
40516 */
40517 static int pcache1Pagecount(sqlite3_pcache *p){
40518   int n;
40519   PCache1 *pCache = (PCache1*)p;
40520   pcache1EnterMutex(pCache->pGroup);
40521   n = pCache->nPage;
40522   pcache1LeaveMutex(pCache->pGroup);
40523   return n;
40524 }
40525
40526
40527 /*
40528 ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
40529 ** in the header of the pcache1Fetch() procedure.
40530 **
40531 ** This steps are broken out into a separate procedure because they are
40532 ** usually not needed, and by avoiding the stack initialization required
40533 ** for these steps, the main pcache1Fetch() procedure can run faster.
40534 */
40535 static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
40536   PCache1 *pCache, 
40537   unsigned int iKey, 
40538   int createFlag
40539 ){
40540   unsigned int nPinned;
40541   PGroup *pGroup = pCache->pGroup;
40542   PgHdr1 *pPage = 0;
40543
40544   /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
40545   assert( pCache->nPage >= pCache->nRecyclable );
40546   nPinned = pCache->nPage - pCache->nRecyclable;
40547   assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
40548   assert( pCache->n90pct == pCache->nMax*9/10 );
40549   if( createFlag==1 && (
40550         nPinned>=pGroup->mxPinned
40551      || nPinned>=pCache->n90pct
40552      || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
40553   )){
40554     return 0;
40555   }
40556
40557   if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
40558   assert( pCache->nHash>0 && pCache->apHash );
40559
40560   /* Step 4. Try to recycle a page. */
40561   if( pCache->bPurgeable && pGroup->pLruTail && (
40562          (pCache->nPage+1>=pCache->nMax)
40563       || pGroup->nCurrentPage>=pGroup->nMaxPage
40564       || pcache1UnderMemoryPressure(pCache)
40565   )){
40566     PCache1 *pOther;
40567     pPage = pGroup->pLruTail;
40568     assert( pPage->isPinned==0 );
40569     pcache1RemoveFromHash(pPage);
40570     pcache1PinPage(pPage);
40571     pOther = pPage->pCache;
40572
40573     /* We want to verify that szPage and szExtra are the same for pOther
40574     ** and pCache.  Assert that we can verify this by comparing sums. */
40575     assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
40576     assert( pCache->szExtra<512 );
40577     assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
40578     assert( pOther->szExtra<512 );
40579
40580     if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
40581       pcache1FreePage(pPage);
40582       pPage = 0;
40583     }else{
40584       pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
40585     }
40586   }
40587
40588   /* Step 5. If a usable page buffer has still not been found, 
40589   ** attempt to allocate a new one. 
40590   */
40591   if( !pPage ){
40592     if( createFlag==1 ) sqlite3BeginBenignMalloc();
40593     pPage = pcache1AllocPage(pCache);
40594     if( createFlag==1 ) sqlite3EndBenignMalloc();
40595   }
40596
40597   if( pPage ){
40598     unsigned int h = iKey % pCache->nHash;
40599     pCache->nPage++;
40600     pPage->iKey = iKey;
40601     pPage->pNext = pCache->apHash[h];
40602     pPage->pCache = pCache;
40603     pPage->pLruPrev = 0;
40604     pPage->pLruNext = 0;
40605     pPage->isPinned = 1;
40606     *(void **)pPage->page.pExtra = 0;
40607     pCache->apHash[h] = pPage;
40608     if( iKey>pCache->iMaxKey ){
40609       pCache->iMaxKey = iKey;
40610     }
40611   }
40612   return pPage;
40613 }
40614
40615 /*
40616 ** Implementation of the sqlite3_pcache.xFetch method. 
40617 **
40618 ** Fetch a page by key value.
40619 **
40620 ** Whether or not a new page may be allocated by this function depends on
40621 ** the value of the createFlag argument.  0 means do not allocate a new
40622 ** page.  1 means allocate a new page if space is easily available.  2 
40623 ** means to try really hard to allocate a new page.
40624 **
40625 ** For a non-purgeable cache (a cache used as the storage for an in-memory
40626 ** database) there is really no difference between createFlag 1 and 2.  So
40627 ** the calling function (pcache.c) will never have a createFlag of 1 on
40628 ** a non-purgeable cache.
40629 **
40630 ** There are three different approaches to obtaining space for a page,
40631 ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
40632 **
40633 **   1. Regardless of the value of createFlag, the cache is searched for a 
40634 **      copy of the requested page. If one is found, it is returned.
40635 **
40636 **   2. If createFlag==0 and the page is not already in the cache, NULL is
40637 **      returned.
40638 **
40639 **   3. If createFlag is 1, and the page is not already in the cache, then
40640 **      return NULL (do not allocate a new page) if any of the following
40641 **      conditions are true:
40642 **
40643 **       (a) the number of pages pinned by the cache is greater than
40644 **           PCache1.nMax, or
40645 **
40646 **       (b) the number of pages pinned by the cache is greater than
40647 **           the sum of nMax for all purgeable caches, less the sum of 
40648 **           nMin for all other purgeable caches, or
40649 **
40650 **   4. If none of the first three conditions apply and the cache is marked
40651 **      as purgeable, and if one of the following is true:
40652 **
40653 **       (a) The number of pages allocated for the cache is already 
40654 **           PCache1.nMax, or
40655 **
40656 **       (b) The number of pages allocated for all purgeable caches is
40657 **           already equal to or greater than the sum of nMax for all
40658 **           purgeable caches,
40659 **
40660 **       (c) The system is under memory pressure and wants to avoid
40661 **           unnecessary pages cache entry allocations
40662 **
40663 **      then attempt to recycle a page from the LRU list. If it is the right
40664 **      size, return the recycled buffer. Otherwise, free the buffer and
40665 **      proceed to step 5. 
40666 **
40667 **   5. Otherwise, allocate and return a new page buffer.
40668 */
40669 static sqlite3_pcache_page *pcache1Fetch(
40670   sqlite3_pcache *p, 
40671   unsigned int iKey, 
40672   int createFlag
40673 ){
40674   PCache1 *pCache = (PCache1 *)p;
40675   PgHdr1 *pPage = 0;
40676
40677   assert( offsetof(PgHdr1,page)==0 );
40678   assert( pCache->bPurgeable || createFlag!=1 );
40679   assert( pCache->bPurgeable || pCache->nMin==0 );
40680   assert( pCache->bPurgeable==0 || pCache->nMin==10 );
40681   assert( pCache->nMin==0 || pCache->bPurgeable );
40682   assert( pCache->nHash>0 );
40683   pcache1EnterMutex(pCache->pGroup);
40684
40685   /* Step 1: Search the hash table for an existing entry. */
40686   pPage = pCache->apHash[iKey % pCache->nHash];
40687   while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
40688
40689   /* Step 2: Abort if no existing page is found and createFlag is 0 */
40690   if( pPage ){
40691     if( !pPage->isPinned ) pcache1PinPage(pPage);
40692   }else if( createFlag ){
40693     /* Steps 3, 4, and 5 implemented by this subroutine */
40694     pPage = pcache1FetchStage2(pCache, iKey, createFlag);
40695   }
40696   assert( pPage==0 || pCache->iMaxKey>=iKey );
40697   pcache1LeaveMutex(pCache->pGroup);
40698   return (sqlite3_pcache_page*)pPage;
40699 }
40700
40701
40702 /*
40703 ** Implementation of the sqlite3_pcache.xUnpin method.
40704 **
40705 ** Mark a page as unpinned (eligible for asynchronous recycling).
40706 */
40707 static void pcache1Unpin(
40708   sqlite3_pcache *p, 
40709   sqlite3_pcache_page *pPg, 
40710   int reuseUnlikely
40711 ){
40712   PCache1 *pCache = (PCache1 *)p;
40713   PgHdr1 *pPage = (PgHdr1 *)pPg;
40714   PGroup *pGroup = pCache->pGroup;
40715  
40716   assert( pPage->pCache==pCache );
40717   pcache1EnterMutex(pGroup);
40718
40719   /* It is an error to call this function if the page is already 
40720   ** part of the PGroup LRU list.
40721   */
40722   assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
40723   assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
40724   assert( pPage->isPinned==1 );
40725
40726   if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
40727     pcache1RemoveFromHash(pPage);
40728     pcache1FreePage(pPage);
40729   }else{
40730     /* Add the page to the PGroup LRU list. */
40731     if( pGroup->pLruHead ){
40732       pGroup->pLruHead->pLruPrev = pPage;
40733       pPage->pLruNext = pGroup->pLruHead;
40734       pGroup->pLruHead = pPage;
40735     }else{
40736       pGroup->pLruTail = pPage;
40737       pGroup->pLruHead = pPage;
40738     }
40739     pCache->nRecyclable++;
40740     pPage->isPinned = 0;
40741   }
40742
40743   pcache1LeaveMutex(pCache->pGroup);
40744 }
40745
40746 /*
40747 ** Implementation of the sqlite3_pcache.xRekey method. 
40748 */
40749 static void pcache1Rekey(
40750   sqlite3_pcache *p,
40751   sqlite3_pcache_page *pPg,
40752   unsigned int iOld,
40753   unsigned int iNew
40754 ){
40755   PCache1 *pCache = (PCache1 *)p;
40756   PgHdr1 *pPage = (PgHdr1 *)pPg;
40757   PgHdr1 **pp;
40758   unsigned int h; 
40759   assert( pPage->iKey==iOld );
40760   assert( pPage->pCache==pCache );
40761
40762   pcache1EnterMutex(pCache->pGroup);
40763
40764   h = iOld%pCache->nHash;
40765   pp = &pCache->apHash[h];
40766   while( (*pp)!=pPage ){
40767     pp = &(*pp)->pNext;
40768   }
40769   *pp = pPage->pNext;
40770
40771   h = iNew%pCache->nHash;
40772   pPage->iKey = iNew;
40773   pPage->pNext = pCache->apHash[h];
40774   pCache->apHash[h] = pPage;
40775   if( iNew>pCache->iMaxKey ){
40776     pCache->iMaxKey = iNew;
40777   }
40778
40779   pcache1LeaveMutex(pCache->pGroup);
40780 }
40781
40782 /*
40783 ** Implementation of the sqlite3_pcache.xTruncate method. 
40784 **
40785 ** Discard all unpinned pages in the cache with a page number equal to
40786 ** or greater than parameter iLimit. Any pinned pages with a page number
40787 ** equal to or greater than iLimit are implicitly unpinned.
40788 */
40789 static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
40790   PCache1 *pCache = (PCache1 *)p;
40791   pcache1EnterMutex(pCache->pGroup);
40792   if( iLimit<=pCache->iMaxKey ){
40793     pcache1TruncateUnsafe(pCache, iLimit);
40794     pCache->iMaxKey = iLimit-1;
40795   }
40796   pcache1LeaveMutex(pCache->pGroup);
40797 }
40798
40799 /*
40800 ** Implementation of the sqlite3_pcache.xDestroy method. 
40801 **
40802 ** Destroy a cache allocated using pcache1Create().
40803 */
40804 static void pcache1Destroy(sqlite3_pcache *p){
40805   PCache1 *pCache = (PCache1 *)p;
40806   PGroup *pGroup = pCache->pGroup;
40807   assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
40808   pcache1EnterMutex(pGroup);
40809   pcache1TruncateUnsafe(pCache, 0);
40810   assert( pGroup->nMaxPage >= pCache->nMax );
40811   pGroup->nMaxPage -= pCache->nMax;
40812   assert( pGroup->nMinPage >= pCache->nMin );
40813   pGroup->nMinPage -= pCache->nMin;
40814   pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
40815   pcache1EnforceMaxPage(pGroup);
40816   pcache1LeaveMutex(pGroup);
40817   sqlite3_free(pCache->apHash);
40818   sqlite3_free(pCache);
40819 }
40820
40821 /*
40822 ** This function is called during initialization (sqlite3_initialize()) to
40823 ** install the default pluggable cache module, assuming the user has not
40824 ** already provided an alternative.
40825 */
40826 SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
40827   static const sqlite3_pcache_methods2 defaultMethods = {
40828     1,                       /* iVersion */
40829     0,                       /* pArg */
40830     pcache1Init,             /* xInit */
40831     pcache1Shutdown,         /* xShutdown */
40832     pcache1Create,           /* xCreate */
40833     pcache1Cachesize,        /* xCachesize */
40834     pcache1Pagecount,        /* xPagecount */
40835     pcache1Fetch,            /* xFetch */
40836     pcache1Unpin,            /* xUnpin */
40837     pcache1Rekey,            /* xRekey */
40838     pcache1Truncate,         /* xTruncate */
40839     pcache1Destroy,          /* xDestroy */
40840     pcache1Shrink            /* xShrink */
40841   };
40842   sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
40843 }
40844
40845 /*
40846 ** Return the size of the header on each page of this PCACHE implementation.
40847 */
40848 SQLITE_PRIVATE int sqlite3HeaderSizePcache1(void){ return ROUND8(sizeof(PgHdr1)); }
40849
40850 /*
40851 ** Return the global mutex used by this PCACHE implementation.  The
40852 ** sqlite3_status() routine needs access to this mutex.
40853 */
40854 SQLITE_PRIVATE sqlite3_mutex *sqlite3Pcache1Mutex(void){
40855   return pcache1.mutex;
40856 }
40857
40858 #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
40859 /*
40860 ** This function is called to free superfluous dynamically allocated memory
40861 ** held by the pager system. Memory in use by any SQLite pager allocated
40862 ** by the current thread may be sqlite3_free()ed.
40863 **
40864 ** nReq is the number of bytes of memory required. Once this much has
40865 ** been released, the function returns. The return value is the total number 
40866 ** of bytes of memory released.
40867 */
40868 SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
40869   int nFree = 0;
40870   assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
40871   assert( sqlite3_mutex_notheld(pcache1.mutex) );
40872   if( pcache1.pStart==0 ){
40873     PgHdr1 *p;
40874     pcache1EnterMutex(&pcache1.grp);
40875     while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
40876       nFree += pcache1MemSize(p->page.pBuf);
40877 #ifdef SQLITE_PCACHE_SEPARATE_HEADER
40878       nFree += sqlite3MemSize(p);
40879 #endif
40880       assert( p->isPinned==0 );
40881       pcache1PinPage(p);
40882       pcache1RemoveFromHash(p);
40883       pcache1FreePage(p);
40884     }
40885     pcache1LeaveMutex(&pcache1.grp);
40886   }
40887   return nFree;
40888 }
40889 #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
40890
40891 #ifdef SQLITE_TEST
40892 /*
40893 ** This function is used by test procedures to inspect the internal state
40894 ** of the global cache.
40895 */
40896 SQLITE_PRIVATE void sqlite3PcacheStats(
40897   int *pnCurrent,      /* OUT: Total number of pages cached */
40898   int *pnMax,          /* OUT: Global maximum cache size */
40899   int *pnMin,          /* OUT: Sum of PCache1.nMin for purgeable caches */
40900   int *pnRecyclable    /* OUT: Total number of pages available for recycling */
40901 ){
40902   PgHdr1 *p;
40903   int nRecyclable = 0;
40904   for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
40905     assert( p->isPinned==0 );
40906     nRecyclable++;
40907   }
40908   *pnCurrent = pcache1.grp.nCurrentPage;
40909   *pnMax = (int)pcache1.grp.nMaxPage;
40910   *pnMin = (int)pcache1.grp.nMinPage;
40911   *pnRecyclable = nRecyclable;
40912 }
40913 #endif
40914
40915 /************** End of pcache1.c *********************************************/
40916 /************** Begin file rowset.c ******************************************/
40917 /*
40918 ** 2008 December 3
40919 **
40920 ** The author disclaims copyright to this source code.  In place of
40921 ** a legal notice, here is a blessing:
40922 **
40923 **    May you do good and not evil.
40924 **    May you find forgiveness for yourself and forgive others.
40925 **    May you share freely, never taking more than you give.
40926 **
40927 *************************************************************************
40928 **
40929 ** This module implements an object we call a "RowSet".
40930 **
40931 ** The RowSet object is a collection of rowids.  Rowids
40932 ** are inserted into the RowSet in an arbitrary order.  Inserts
40933 ** can be intermixed with tests to see if a given rowid has been
40934 ** previously inserted into the RowSet.
40935 **
40936 ** After all inserts are finished, it is possible to extract the
40937 ** elements of the RowSet in sorted order.  Once this extraction
40938 ** process has started, no new elements may be inserted.
40939 **
40940 ** Hence, the primitive operations for a RowSet are:
40941 **
40942 **    CREATE
40943 **    INSERT
40944 **    TEST
40945 **    SMALLEST
40946 **    DESTROY
40947 **
40948 ** The CREATE and DESTROY primitives are the constructor and destructor,
40949 ** obviously.  The INSERT primitive adds a new element to the RowSet.
40950 ** TEST checks to see if an element is already in the RowSet.  SMALLEST
40951 ** extracts the least value from the RowSet.
40952 **
40953 ** The INSERT primitive might allocate additional memory.  Memory is
40954 ** allocated in chunks so most INSERTs do no allocation.  There is an 
40955 ** upper bound on the size of allocated memory.  No memory is freed
40956 ** until DESTROY.
40957 **
40958 ** The TEST primitive includes a "batch" number.  The TEST primitive
40959 ** will only see elements that were inserted before the last change
40960 ** in the batch number.  In other words, if an INSERT occurs between
40961 ** two TESTs where the TESTs have the same batch nubmer, then the
40962 ** value added by the INSERT will not be visible to the second TEST.
40963 ** The initial batch number is zero, so if the very first TEST contains
40964 ** a non-zero batch number, it will see all prior INSERTs.
40965 **
40966 ** No INSERTs may occurs after a SMALLEST.  An assertion will fail if
40967 ** that is attempted.
40968 **
40969 ** The cost of an INSERT is roughly constant.  (Sometimes new memory
40970 ** has to be allocated on an INSERT.)  The cost of a TEST with a new
40971 ** batch number is O(NlogN) where N is the number of elements in the RowSet.
40972 ** The cost of a TEST using the same batch number is O(logN).  The cost
40973 ** of the first SMALLEST is O(NlogN).  Second and subsequent SMALLEST
40974 ** primitives are constant time.  The cost of DESTROY is O(N).
40975 **
40976 ** There is an added cost of O(N) when switching between TEST and
40977 ** SMALLEST primitives.
40978 */
40979
40980
40981 /*
40982 ** Target size for allocation chunks.
40983 */
40984 #define ROWSET_ALLOCATION_SIZE 1024
40985
40986 /*
40987 ** The number of rowset entries per allocation chunk.
40988 */
40989 #define ROWSET_ENTRY_PER_CHUNK  \
40990                        ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
40991
40992 /*
40993 ** Each entry in a RowSet is an instance of the following object.
40994 **
40995 ** This same object is reused to store a linked list of trees of RowSetEntry
40996 ** objects.  In that alternative use, pRight points to the next entry
40997 ** in the list, pLeft points to the tree, and v is unused.  The
40998 ** RowSet.pForest value points to the head of this forest list.
40999 */
41000 struct RowSetEntry {            
41001   i64 v;                        /* ROWID value for this entry */
41002   struct RowSetEntry *pRight;   /* Right subtree (larger entries) or list */
41003   struct RowSetEntry *pLeft;    /* Left subtree (smaller entries) */
41004 };
41005
41006 /*
41007 ** RowSetEntry objects are allocated in large chunks (instances of the
41008 ** following structure) to reduce memory allocation overhead.  The
41009 ** chunks are kept on a linked list so that they can be deallocated
41010 ** when the RowSet is destroyed.
41011 */
41012 struct RowSetChunk {
41013   struct RowSetChunk *pNextChunk;        /* Next chunk on list of them all */
41014   struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
41015 };
41016
41017 /*
41018 ** A RowSet in an instance of the following structure.
41019 **
41020 ** A typedef of this structure if found in sqliteInt.h.
41021 */
41022 struct RowSet {
41023   struct RowSetChunk *pChunk;    /* List of all chunk allocations */
41024   sqlite3 *db;                   /* The database connection */
41025   struct RowSetEntry *pEntry;    /* List of entries using pRight */
41026   struct RowSetEntry *pLast;     /* Last entry on the pEntry list */
41027   struct RowSetEntry *pFresh;    /* Source of new entry objects */
41028   struct RowSetEntry *pForest;   /* List of binary trees of entries */
41029   u16 nFresh;                    /* Number of objects on pFresh */
41030   u16 rsFlags;                   /* Various flags */
41031   int iBatch;                    /* Current insert batch */
41032 };
41033
41034 /*
41035 ** Allowed values for RowSet.rsFlags
41036 */
41037 #define ROWSET_SORTED  0x01   /* True if RowSet.pEntry is sorted */
41038 #define ROWSET_NEXT    0x02   /* True if sqlite3RowSetNext() has been called */
41039
41040 /*
41041 ** Turn bulk memory into a RowSet object.  N bytes of memory
41042 ** are available at pSpace.  The db pointer is used as a memory context
41043 ** for any subsequent allocations that need to occur.
41044 ** Return a pointer to the new RowSet object.
41045 **
41046 ** It must be the case that N is sufficient to make a Rowset.  If not
41047 ** an assertion fault occurs.
41048 ** 
41049 ** If N is larger than the minimum, use the surplus as an initial
41050 ** allocation of entries available to be filled.
41051 */
41052 SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
41053   RowSet *p;
41054   assert( N >= ROUND8(sizeof(*p)) );
41055   p = pSpace;
41056   p->pChunk = 0;
41057   p->db = db;
41058   p->pEntry = 0;
41059   p->pLast = 0;
41060   p->pForest = 0;
41061   p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
41062   p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
41063   p->rsFlags = ROWSET_SORTED;
41064   p->iBatch = 0;
41065   return p;
41066 }
41067
41068 /*
41069 ** Deallocate all chunks from a RowSet.  This frees all memory that
41070 ** the RowSet has allocated over its lifetime.  This routine is
41071 ** the destructor for the RowSet.
41072 */
41073 SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
41074   struct RowSetChunk *pChunk, *pNextChunk;
41075   for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
41076     pNextChunk = pChunk->pNextChunk;
41077     sqlite3DbFree(p->db, pChunk);
41078   }
41079   p->pChunk = 0;
41080   p->nFresh = 0;
41081   p->pEntry = 0;
41082   p->pLast = 0;
41083   p->pForest = 0;
41084   p->rsFlags = ROWSET_SORTED;
41085 }
41086
41087 /*
41088 ** Allocate a new RowSetEntry object that is associated with the
41089 ** given RowSet.  Return a pointer to the new and completely uninitialized
41090 ** objected.
41091 **
41092 ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
41093 ** routine returns NULL.
41094 */
41095 static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
41096   assert( p!=0 );
41097   if( p->nFresh==0 ){
41098     struct RowSetChunk *pNew;
41099     pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
41100     if( pNew==0 ){
41101       return 0;
41102     }
41103     pNew->pNextChunk = p->pChunk;
41104     p->pChunk = pNew;
41105     p->pFresh = pNew->aEntry;
41106     p->nFresh = ROWSET_ENTRY_PER_CHUNK;
41107   }
41108   p->nFresh--;
41109   return p->pFresh++;
41110 }
41111
41112 /*
41113 ** Insert a new value into a RowSet.
41114 **
41115 ** The mallocFailed flag of the database connection is set if a
41116 ** memory allocation fails.
41117 */
41118 SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
41119   struct RowSetEntry *pEntry;  /* The new entry */
41120   struct RowSetEntry *pLast;   /* The last prior entry */
41121
41122   /* This routine is never called after sqlite3RowSetNext() */
41123   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
41124
41125   pEntry = rowSetEntryAlloc(p);
41126   if( pEntry==0 ) return;
41127   pEntry->v = rowid;
41128   pEntry->pRight = 0;
41129   pLast = p->pLast;
41130   if( pLast ){
41131     if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
41132       p->rsFlags &= ~ROWSET_SORTED;
41133     }
41134     pLast->pRight = pEntry;
41135   }else{
41136     p->pEntry = pEntry;
41137   }
41138   p->pLast = pEntry;
41139 }
41140
41141 /*
41142 ** Merge two lists of RowSetEntry objects.  Remove duplicates.
41143 **
41144 ** The input lists are connected via pRight pointers and are 
41145 ** assumed to each already be in sorted order.
41146 */
41147 static struct RowSetEntry *rowSetEntryMerge(
41148   struct RowSetEntry *pA,    /* First sorted list to be merged */
41149   struct RowSetEntry *pB     /* Second sorted list to be merged */
41150 ){
41151   struct RowSetEntry head;
41152   struct RowSetEntry *pTail;
41153
41154   pTail = &head;
41155   while( pA && pB ){
41156     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
41157     assert( pB->pRight==0 || pB->v<=pB->pRight->v );
41158     if( pA->v<pB->v ){
41159       pTail->pRight = pA;
41160       pA = pA->pRight;
41161       pTail = pTail->pRight;
41162     }else if( pB->v<pA->v ){
41163       pTail->pRight = pB;
41164       pB = pB->pRight;
41165       pTail = pTail->pRight;
41166     }else{
41167       pA = pA->pRight;
41168     }
41169   }
41170   if( pA ){
41171     assert( pA->pRight==0 || pA->v<=pA->pRight->v );
41172     pTail->pRight = pA;
41173   }else{
41174     assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
41175     pTail->pRight = pB;
41176   }
41177   return head.pRight;
41178 }
41179
41180 /*
41181 ** Sort all elements on the list of RowSetEntry objects into order of
41182 ** increasing v.
41183 */ 
41184 static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
41185   unsigned int i;
41186   struct RowSetEntry *pNext, *aBucket[40];
41187
41188   memset(aBucket, 0, sizeof(aBucket));
41189   while( pIn ){
41190     pNext = pIn->pRight;
41191     pIn->pRight = 0;
41192     for(i=0; aBucket[i]; i++){
41193       pIn = rowSetEntryMerge(aBucket[i], pIn);
41194       aBucket[i] = 0;
41195     }
41196     aBucket[i] = pIn;
41197     pIn = pNext;
41198   }
41199   pIn = 0;
41200   for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
41201     pIn = rowSetEntryMerge(pIn, aBucket[i]);
41202   }
41203   return pIn;
41204 }
41205
41206
41207 /*
41208 ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
41209 ** Convert this tree into a linked list connected by the pRight pointers
41210 ** and return pointers to the first and last elements of the new list.
41211 */
41212 static void rowSetTreeToList(
41213   struct RowSetEntry *pIn,         /* Root of the input tree */
41214   struct RowSetEntry **ppFirst,    /* Write head of the output list here */
41215   struct RowSetEntry **ppLast      /* Write tail of the output list here */
41216 ){
41217   assert( pIn!=0 );
41218   if( pIn->pLeft ){
41219     struct RowSetEntry *p;
41220     rowSetTreeToList(pIn->pLeft, ppFirst, &p);
41221     p->pRight = pIn;
41222   }else{
41223     *ppFirst = pIn;
41224   }
41225   if( pIn->pRight ){
41226     rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
41227   }else{
41228     *ppLast = pIn;
41229   }
41230   assert( (*ppLast)->pRight==0 );
41231 }
41232
41233
41234 /*
41235 ** Convert a sorted list of elements (connected by pRight) into a binary
41236 ** tree with depth of iDepth.  A depth of 1 means the tree contains a single
41237 ** node taken from the head of *ppList.  A depth of 2 means a tree with
41238 ** three nodes.  And so forth.
41239 **
41240 ** Use as many entries from the input list as required and update the
41241 ** *ppList to point to the unused elements of the list.  If the input
41242 ** list contains too few elements, then construct an incomplete tree
41243 ** and leave *ppList set to NULL.
41244 **
41245 ** Return a pointer to the root of the constructed binary tree.
41246 */
41247 static struct RowSetEntry *rowSetNDeepTree(
41248   struct RowSetEntry **ppList,
41249   int iDepth
41250 ){
41251   struct RowSetEntry *p;         /* Root of the new tree */
41252   struct RowSetEntry *pLeft;     /* Left subtree */
41253   if( *ppList==0 ){
41254     return 0;
41255   }
41256   if( iDepth==1 ){
41257     p = *ppList;
41258     *ppList = p->pRight;
41259     p->pLeft = p->pRight = 0;
41260     return p;
41261   }
41262   pLeft = rowSetNDeepTree(ppList, iDepth-1);
41263   p = *ppList;
41264   if( p==0 ){
41265     return pLeft;
41266   }
41267   p->pLeft = pLeft;
41268   *ppList = p->pRight;
41269   p->pRight = rowSetNDeepTree(ppList, iDepth-1);
41270   return p;
41271 }
41272
41273 /*
41274 ** Convert a sorted list of elements into a binary tree. Make the tree
41275 ** as deep as it needs to be in order to contain the entire list.
41276 */
41277 static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
41278   int iDepth;           /* Depth of the tree so far */
41279   struct RowSetEntry *p;       /* Current tree root */
41280   struct RowSetEntry *pLeft;   /* Left subtree */
41281
41282   assert( pList!=0 );
41283   p = pList;
41284   pList = p->pRight;
41285   p->pLeft = p->pRight = 0;
41286   for(iDepth=1; pList; iDepth++){
41287     pLeft = p;
41288     p = pList;
41289     pList = p->pRight;
41290     p->pLeft = pLeft;
41291     p->pRight = rowSetNDeepTree(&pList, iDepth);
41292   }
41293   return p;
41294 }
41295
41296 /*
41297 ** Take all the entries on p->pEntry and on the trees in p->pForest and
41298 ** sort them all together into one big ordered list on p->pEntry.
41299 **
41300 ** This routine should only be called once in the life of a RowSet.
41301 */
41302 static void rowSetToList(RowSet *p){
41303
41304   /* This routine is called only once */
41305   assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
41306
41307   if( (p->rsFlags & ROWSET_SORTED)==0 ){
41308     p->pEntry = rowSetEntrySort(p->pEntry);
41309   }
41310
41311   /* While this module could theoretically support it, sqlite3RowSetNext()
41312   ** is never called after sqlite3RowSetText() for the same RowSet.  So
41313   ** there is never a forest to deal with.  Should this change, simply
41314   ** remove the assert() and the #if 0. */
41315   assert( p->pForest==0 );
41316 #if 0
41317   while( p->pForest ){
41318     struct RowSetEntry *pTree = p->pForest->pLeft;
41319     if( pTree ){
41320       struct RowSetEntry *pHead, *pTail;
41321       rowSetTreeToList(pTree, &pHead, &pTail);
41322       p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
41323     }
41324     p->pForest = p->pForest->pRight;
41325   }
41326 #endif
41327   p->rsFlags |= ROWSET_NEXT;  /* Verify this routine is never called again */
41328 }
41329
41330 /*
41331 ** Extract the smallest element from the RowSet.
41332 ** Write the element into *pRowid.  Return 1 on success.  Return
41333 ** 0 if the RowSet is already empty.
41334 **
41335 ** After this routine has been called, the sqlite3RowSetInsert()
41336 ** routine may not be called again.  
41337 */
41338 SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
41339   assert( p!=0 );
41340
41341   /* Merge the forest into a single sorted list on first call */
41342   if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
41343
41344   /* Return the next entry on the list */
41345   if( p->pEntry ){
41346     *pRowid = p->pEntry->v;
41347     p->pEntry = p->pEntry->pRight;
41348     if( p->pEntry==0 ){
41349       sqlite3RowSetClear(p);
41350     }
41351     return 1;
41352   }else{
41353     return 0;
41354   }
41355 }
41356
41357 /*
41358 ** Check to see if element iRowid was inserted into the rowset as
41359 ** part of any insert batch prior to iBatch.  Return 1 or 0.
41360 **
41361 ** If this is the first test of a new batch and if there exist entries
41362 ** on pRowSet->pEntry, then sort those entries into the forest at
41363 ** pRowSet->pForest so that they can be tested.
41364 */
41365 SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
41366   struct RowSetEntry *p, *pTree;
41367
41368   /* This routine is never called after sqlite3RowSetNext() */
41369   assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
41370
41371   /* Sort entries into the forest on the first test of a new batch 
41372   */
41373   if( iBatch!=pRowSet->iBatch ){
41374     p = pRowSet->pEntry;
41375     if( p ){
41376       struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
41377       if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
41378         p = rowSetEntrySort(p);
41379       }
41380       for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
41381         ppPrevTree = &pTree->pRight;
41382         if( pTree->pLeft==0 ){
41383           pTree->pLeft = rowSetListToTree(p);
41384           break;
41385         }else{
41386           struct RowSetEntry *pAux, *pTail;
41387           rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
41388           pTree->pLeft = 0;
41389           p = rowSetEntryMerge(pAux, p);
41390         }
41391       }
41392       if( pTree==0 ){
41393         *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
41394         if( pTree ){
41395           pTree->v = 0;
41396           pTree->pRight = 0;
41397           pTree->pLeft = rowSetListToTree(p);
41398         }
41399       }
41400       pRowSet->pEntry = 0;
41401       pRowSet->pLast = 0;
41402       pRowSet->rsFlags |= ROWSET_SORTED;
41403     }
41404     pRowSet->iBatch = iBatch;
41405   }
41406
41407   /* Test to see if the iRowid value appears anywhere in the forest.
41408   ** Return 1 if it does and 0 if not.
41409   */
41410   for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
41411     p = pTree->pLeft;
41412     while( p ){
41413       if( p->v<iRowid ){
41414         p = p->pRight;
41415       }else if( p->v>iRowid ){
41416         p = p->pLeft;
41417       }else{
41418         return 1;
41419       }
41420     }
41421   }
41422   return 0;
41423 }
41424
41425 /************** End of rowset.c **********************************************/
41426 /************** Begin file pager.c *******************************************/
41427 /*
41428 ** 2001 September 15
41429 **
41430 ** The author disclaims copyright to this source code.  In place of
41431 ** a legal notice, here is a blessing:
41432 **
41433 **    May you do good and not evil.
41434 **    May you find forgiveness for yourself and forgive others.
41435 **    May you share freely, never taking more than you give.
41436 **
41437 *************************************************************************
41438 ** This is the implementation of the page cache subsystem or "pager".
41439 ** 
41440 ** The pager is used to access a database disk file.  It implements
41441 ** atomic commit and rollback through the use of a journal file that
41442 ** is separate from the database file.  The pager also implements file
41443 ** locking to prevent two processes from writing the same database
41444 ** file simultaneously, or one process from reading the database while
41445 ** another is writing.
41446 */
41447 #ifndef SQLITE_OMIT_DISKIO
41448 /************** Include wal.h in the middle of pager.c ***********************/
41449 /************** Begin file wal.h *********************************************/
41450 /*
41451 ** 2010 February 1
41452 **
41453 ** The author disclaims copyright to this source code.  In place of
41454 ** a legal notice, here is a blessing:
41455 **
41456 **    May you do good and not evil.
41457 **    May you find forgiveness for yourself and forgive others.
41458 **    May you share freely, never taking more than you give.
41459 **
41460 *************************************************************************
41461 ** This header file defines the interface to the write-ahead logging 
41462 ** system. Refer to the comments below and the header comment attached to 
41463 ** the implementation of each function in log.c for further details.
41464 */
41465
41466 #ifndef _WAL_H_
41467 #define _WAL_H_
41468
41469
41470 /* Additional values that can be added to the sync_flags argument of
41471 ** sqlite3WalFrames():
41472 */
41473 #define WAL_SYNC_TRANSACTIONS  0x20   /* Sync at the end of each transaction */
41474 #define SQLITE_SYNC_MASK       0x13   /* Mask off the SQLITE_SYNC_* values */
41475
41476 #ifdef SQLITE_OMIT_WAL
41477 # define sqlite3WalOpen(x,y,z)                   0
41478 # define sqlite3WalLimit(x,y)
41479 # define sqlite3WalClose(w,x,y,z)                0
41480 # define sqlite3WalBeginReadTransaction(y,z)     0
41481 # define sqlite3WalEndReadTransaction(z)
41482 # define sqlite3WalDbsize(y)                     0
41483 # define sqlite3WalBeginWriteTransaction(y)      0
41484 # define sqlite3WalEndWriteTransaction(x)        0
41485 # define sqlite3WalUndo(x,y,z)                   0
41486 # define sqlite3WalSavepoint(y,z)
41487 # define sqlite3WalSavepointUndo(y,z)            0
41488 # define sqlite3WalFrames(u,v,w,x,y,z)           0
41489 # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
41490 # define sqlite3WalCallback(z)                   0
41491 # define sqlite3WalExclusiveMode(y,z)            0
41492 # define sqlite3WalHeapMemory(z)                 0
41493 # define sqlite3WalFramesize(z)                  0
41494 # define sqlite3WalFindFrame(x,y,z)              0
41495 #else
41496
41497 #define WAL_SAVEPOINT_NDATA 4
41498
41499 /* Connection to a write-ahead log (WAL) file. 
41500 ** There is one object of this type for each pager. 
41501 */
41502 typedef struct Wal Wal;
41503
41504 /* Open and close a connection to a write-ahead log. */
41505 SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
41506 SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
41507
41508 /* Set the limiting size of a WAL file. */
41509 SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
41510
41511 /* Used by readers to open (lock) and close (unlock) a snapshot.  A 
41512 ** snapshot is like a read-transaction.  It is the state of the database
41513 ** at an instant in time.  sqlite3WalOpenSnapshot gets a read lock and
41514 ** preserves the current state even if the other threads or processes
41515 ** write to or checkpoint the WAL.  sqlite3WalCloseSnapshot() closes the
41516 ** transaction and releases the lock.
41517 */
41518 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
41519 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
41520
41521 /* Read a page from the write-ahead log, if it is present. */
41522 SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
41523 SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
41524
41525 /* If the WAL is not empty, return the size of the database. */
41526 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
41527
41528 /* Obtain or release the WRITER lock. */
41529 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
41530 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
41531
41532 /* Undo any frames written (but not committed) to the log */
41533 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
41534
41535 /* Return an integer that records the current (uncommitted) write
41536 ** position in the WAL */
41537 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
41538
41539 /* Move the write position of the WAL back to iFrame.  Called in
41540 ** response to a ROLLBACK TO command. */
41541 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
41542
41543 /* Write a frame or frames to the log. */
41544 SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
41545
41546 /* Copy pages from the log to the database file */ 
41547 SQLITE_PRIVATE int sqlite3WalCheckpoint(
41548   Wal *pWal,                      /* Write-ahead log connection */
41549   int eMode,                      /* One of PASSIVE, FULL and RESTART */
41550   int (*xBusy)(void*),            /* Function to call when busy */
41551   void *pBusyArg,                 /* Context argument for xBusyHandler */
41552   int sync_flags,                 /* Flags to sync db file with (or 0) */
41553   int nBuf,                       /* Size of buffer nBuf */
41554   u8 *zBuf,                       /* Temporary buffer to use */
41555   int *pnLog,                     /* OUT: Number of frames in WAL */
41556   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
41557 );
41558
41559 /* Return the value to pass to a sqlite3_wal_hook callback, the
41560 ** number of frames in the WAL at the point of the last commit since
41561 ** sqlite3WalCallback() was called.  If no commits have occurred since
41562 ** the last call, then return 0.
41563 */
41564 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
41565
41566 /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
41567 ** by the pager layer on the database file.
41568 */
41569 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
41570
41571 /* Return true if the argument is non-NULL and the WAL module is using
41572 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
41573 ** WAL module is using shared-memory, return false. 
41574 */
41575 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
41576
41577 #ifdef SQLITE_ENABLE_ZIPVFS
41578 /* If the WAL file is not empty, return the number of bytes of content
41579 ** stored in each frame (i.e. the db page-size when the WAL was created).
41580 */
41581 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
41582 #endif
41583
41584 #endif /* ifndef SQLITE_OMIT_WAL */
41585 #endif /* _WAL_H_ */
41586
41587 /************** End of wal.h *************************************************/
41588 /************** Continuing where we left off in pager.c **********************/
41589
41590
41591 /******************* NOTES ON THE DESIGN OF THE PAGER ************************
41592 **
41593 ** This comment block describes invariants that hold when using a rollback
41594 ** journal.  These invariants do not apply for journal_mode=WAL,
41595 ** journal_mode=MEMORY, or journal_mode=OFF.
41596 **
41597 ** Within this comment block, a page is deemed to have been synced
41598 ** automatically as soon as it is written when PRAGMA synchronous=OFF.
41599 ** Otherwise, the page is not synced until the xSync method of the VFS
41600 ** is called successfully on the file containing the page.
41601 **
41602 ** Definition:  A page of the database file is said to be "overwriteable" if
41603 ** one or more of the following are true about the page:
41604 ** 
41605 **     (a)  The original content of the page as it was at the beginning of
41606 **          the transaction has been written into the rollback journal and
41607 **          synced.
41608 ** 
41609 **     (b)  The page was a freelist leaf page at the start of the transaction.
41610 ** 
41611 **     (c)  The page number is greater than the largest page that existed in
41612 **          the database file at the start of the transaction.
41613 ** 
41614 ** (1) A page of the database file is never overwritten unless one of the
41615 **     following are true:
41616 ** 
41617 **     (a) The page and all other pages on the same sector are overwriteable.
41618 ** 
41619 **     (b) The atomic page write optimization is enabled, and the entire
41620 **         transaction other than the update of the transaction sequence
41621 **         number consists of a single page change.
41622 ** 
41623 ** (2) The content of a page written into the rollback journal exactly matches
41624 **     both the content in the database when the rollback journal was written
41625 **     and the content in the database at the beginning of the current
41626 **     transaction.
41627 ** 
41628 ** (3) Writes to the database file are an integer multiple of the page size
41629 **     in length and are aligned on a page boundary.
41630 ** 
41631 ** (4) Reads from the database file are either aligned on a page boundary and
41632 **     an integer multiple of the page size in length or are taken from the
41633 **     first 100 bytes of the database file.
41634 ** 
41635 ** (5) All writes to the database file are synced prior to the rollback journal
41636 **     being deleted, truncated, or zeroed.
41637 ** 
41638 ** (6) If a master journal file is used, then all writes to the database file
41639 **     are synced prior to the master journal being deleted.
41640 ** 
41641 ** Definition: Two databases (or the same database at two points it time)
41642 ** are said to be "logically equivalent" if they give the same answer to
41643 ** all queries.  Note in particular the content of freelist leaf
41644 ** pages can be changed arbitrarily without affecting the logical equivalence
41645 ** of the database.
41646 ** 
41647 ** (7) At any time, if any subset, including the empty set and the total set,
41648 **     of the unsynced changes to a rollback journal are removed and the 
41649 **     journal is rolled back, the resulting database file will be logically
41650 **     equivalent to the database file at the beginning of the transaction.
41651 ** 
41652 ** (8) When a transaction is rolled back, the xTruncate method of the VFS
41653 **     is called to restore the database file to the same size it was at
41654 **     the beginning of the transaction.  (In some VFSes, the xTruncate
41655 **     method is a no-op, but that does not change the fact the SQLite will
41656 **     invoke it.)
41657 ** 
41658 ** (9) Whenever the database file is modified, at least one bit in the range
41659 **     of bytes from 24 through 39 inclusive will be changed prior to releasing
41660 **     the EXCLUSIVE lock, thus signaling other connections on the same
41661 **     database to flush their caches.
41662 **
41663 ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
41664 **      than one billion transactions.
41665 **
41666 ** (11) A database file is well-formed at the beginning and at the conclusion
41667 **      of every transaction.
41668 **
41669 ** (12) An EXCLUSIVE lock is held on the database file when writing to
41670 **      the database file.
41671 **
41672 ** (13) A SHARED lock is held on the database file while reading any
41673 **      content out of the database file.
41674 **
41675 ******************************************************************************/
41676
41677 /*
41678 ** Macros for troubleshooting.  Normally turned off
41679 */
41680 #if 0
41681 int sqlite3PagerTrace=1;  /* True to enable tracing */
41682 #define sqlite3DebugPrintf printf
41683 #define PAGERTRACE(X)     if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
41684 #else
41685 #define PAGERTRACE(X)
41686 #endif
41687
41688 /*
41689 ** The following two macros are used within the PAGERTRACE() macros above
41690 ** to print out file-descriptors. 
41691 **
41692 ** PAGERID() takes a pointer to a Pager struct as its argument. The
41693 ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
41694 ** struct as its argument.
41695 */
41696 #define PAGERID(p) ((int)(p->fd))
41697 #define FILEHANDLEID(fd) ((int)fd)
41698
41699 /*
41700 ** The Pager.eState variable stores the current 'state' of a pager. A
41701 ** pager may be in any one of the seven states shown in the following
41702 ** state diagram.
41703 **
41704 **                            OPEN <------+------+
41705 **                              |         |      |
41706 **                              V         |      |
41707 **               +---------> READER-------+      |
41708 **               |              |                |
41709 **               |              V                |
41710 **               |<-------WRITER_LOCKED------> ERROR
41711 **               |              |                ^  
41712 **               |              V                |
41713 **               |<------WRITER_CACHEMOD-------->|
41714 **               |              |                |
41715 **               |              V                |
41716 **               |<-------WRITER_DBMOD---------->|
41717 **               |              |                |
41718 **               |              V                |
41719 **               +<------WRITER_FINISHED-------->+
41720 **
41721 **
41722 ** List of state transitions and the C [function] that performs each:
41723 ** 
41724 **   OPEN              -> READER              [sqlite3PagerSharedLock]
41725 **   READER            -> OPEN                [pager_unlock]
41726 **
41727 **   READER            -> WRITER_LOCKED       [sqlite3PagerBegin]
41728 **   WRITER_LOCKED     -> WRITER_CACHEMOD     [pager_open_journal]
41729 **   WRITER_CACHEMOD   -> WRITER_DBMOD        [syncJournal]
41730 **   WRITER_DBMOD      -> WRITER_FINISHED     [sqlite3PagerCommitPhaseOne]
41731 **   WRITER_***        -> READER              [pager_end_transaction]
41732 **
41733 **   WRITER_***        -> ERROR               [pager_error]
41734 **   ERROR             -> OPEN                [pager_unlock]
41735 ** 
41736 **
41737 **  OPEN:
41738 **
41739 **    The pager starts up in this state. Nothing is guaranteed in this
41740 **    state - the file may or may not be locked and the database size is
41741 **    unknown. The database may not be read or written.
41742 **
41743 **    * No read or write transaction is active.
41744 **    * Any lock, or no lock at all, may be held on the database file.
41745 **    * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
41746 **
41747 **  READER:
41748 **
41749 **    In this state all the requirements for reading the database in 
41750 **    rollback (non-WAL) mode are met. Unless the pager is (or recently
41751 **    was) in exclusive-locking mode, a user-level read transaction is 
41752 **    open. The database size is known in this state.
41753 **
41754 **    A connection running with locking_mode=normal enters this state when
41755 **    it opens a read-transaction on the database and returns to state
41756 **    OPEN after the read-transaction is completed. However a connection
41757 **    running in locking_mode=exclusive (including temp databases) remains in
41758 **    this state even after the read-transaction is closed. The only way
41759 **    a locking_mode=exclusive connection can transition from READER to OPEN
41760 **    is via the ERROR state (see below).
41761 ** 
41762 **    * A read transaction may be active (but a write-transaction cannot).
41763 **    * A SHARED or greater lock is held on the database file.
41764 **    * The dbSize variable may be trusted (even if a user-level read 
41765 **      transaction is not active). The dbOrigSize and dbFileSize variables
41766 **      may not be trusted at this point.
41767 **    * If the database is a WAL database, then the WAL connection is open.
41768 **    * Even if a read-transaction is not open, it is guaranteed that 
41769 **      there is no hot-journal in the file-system.
41770 **
41771 **  WRITER_LOCKED:
41772 **
41773 **    The pager moves to this state from READER when a write-transaction
41774 **    is first opened on the database. In WRITER_LOCKED state, all locks 
41775 **    required to start a write-transaction are held, but no actual 
41776 **    modifications to the cache or database have taken place.
41777 **
41778 **    In rollback mode, a RESERVED or (if the transaction was opened with 
41779 **    BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
41780 **    moving to this state, but the journal file is not written to or opened 
41781 **    to in this state. If the transaction is committed or rolled back while 
41782 **    in WRITER_LOCKED state, all that is required is to unlock the database 
41783 **    file.
41784 **
41785 **    IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
41786 **    If the connection is running with locking_mode=exclusive, an attempt
41787 **    is made to obtain an EXCLUSIVE lock on the database file.
41788 **
41789 **    * A write transaction is active.
41790 **    * If the connection is open in rollback-mode, a RESERVED or greater 
41791 **      lock is held on the database file.
41792 **    * If the connection is open in WAL-mode, a WAL write transaction
41793 **      is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
41794 **      called).
41795 **    * The dbSize, dbOrigSize and dbFileSize variables are all valid.
41796 **    * The contents of the pager cache have not been modified.
41797 **    * The journal file may or may not be open.
41798 **    * Nothing (not even the first header) has been written to the journal.
41799 **
41800 **  WRITER_CACHEMOD:
41801 **
41802 **    A pager moves from WRITER_LOCKED state to this state when a page is
41803 **    first modified by the upper layer. In rollback mode the journal file
41804 **    is opened (if it is not already open) and a header written to the
41805 **    start of it. The database file on disk has not been modified.
41806 **
41807 **    * A write transaction is active.
41808 **    * A RESERVED or greater lock is held on the database file.
41809 **    * The journal file is open and the first header has been written 
41810 **      to it, but the header has not been synced to disk.
41811 **    * The contents of the page cache have been modified.
41812 **
41813 **  WRITER_DBMOD:
41814 **
41815 **    The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
41816 **    when it modifies the contents of the database file. WAL connections
41817 **    never enter this state (since they do not modify the database file,
41818 **    just the log file).
41819 **
41820 **    * A write transaction is active.
41821 **    * An EXCLUSIVE or greater lock is held on the database file.
41822 **    * The journal file is open and the first header has been written 
41823 **      and synced to disk.
41824 **    * The contents of the page cache have been modified (and possibly
41825 **      written to disk).
41826 **
41827 **  WRITER_FINISHED:
41828 **
41829 **    It is not possible for a WAL connection to enter this state.
41830 **
41831 **    A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
41832 **    state after the entire transaction has been successfully written into the
41833 **    database file. In this state the transaction may be committed simply
41834 **    by finalizing the journal file. Once in WRITER_FINISHED state, it is 
41835 **    not possible to modify the database further. At this point, the upper 
41836 **    layer must either commit or rollback the transaction.
41837 **
41838 **    * A write transaction is active.
41839 **    * An EXCLUSIVE or greater lock is held on the database file.
41840 **    * All writing and syncing of journal and database data has finished.
41841 **      If no error occurred, all that remains is to finalize the journal to
41842 **      commit the transaction. If an error did occur, the caller will need
41843 **      to rollback the transaction. 
41844 **
41845 **  ERROR:
41846 **
41847 **    The ERROR state is entered when an IO or disk-full error (including
41848 **    SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it 
41849 **    difficult to be sure that the in-memory pager state (cache contents, 
41850 **    db size etc.) are consistent with the contents of the file-system.
41851 **
41852 **    Temporary pager files may enter the ERROR state, but in-memory pagers
41853 **    cannot.
41854 **
41855 **    For example, if an IO error occurs while performing a rollback, 
41856 **    the contents of the page-cache may be left in an inconsistent state.
41857 **    At this point it would be dangerous to change back to READER state
41858 **    (as usually happens after a rollback). Any subsequent readers might
41859 **    report database corruption (due to the inconsistent cache), and if
41860 **    they upgrade to writers, they may inadvertently corrupt the database
41861 **    file. To avoid this hazard, the pager switches into the ERROR state
41862 **    instead of READER following such an error.
41863 **
41864 **    Once it has entered the ERROR state, any attempt to use the pager
41865 **    to read or write data returns an error. Eventually, once all 
41866 **    outstanding transactions have been abandoned, the pager is able to
41867 **    transition back to OPEN state, discarding the contents of the 
41868 **    page-cache and any other in-memory state at the same time. Everything
41869 **    is reloaded from disk (and, if necessary, hot-journal rollback peformed)
41870 **    when a read-transaction is next opened on the pager (transitioning
41871 **    the pager into READER state). At that point the system has recovered 
41872 **    from the error.
41873 **
41874 **    Specifically, the pager jumps into the ERROR state if:
41875 **
41876 **      1. An error occurs while attempting a rollback. This happens in
41877 **         function sqlite3PagerRollback().
41878 **
41879 **      2. An error occurs while attempting to finalize a journal file
41880 **         following a commit in function sqlite3PagerCommitPhaseTwo().
41881 **
41882 **      3. An error occurs while attempting to write to the journal or
41883 **         database file in function pagerStress() in order to free up
41884 **         memory.
41885 **
41886 **    In other cases, the error is returned to the b-tree layer. The b-tree
41887 **    layer then attempts a rollback operation. If the error condition 
41888 **    persists, the pager enters the ERROR state via condition (1) above.
41889 **
41890 **    Condition (3) is necessary because it can be triggered by a read-only
41891 **    statement executed within a transaction. In this case, if the error
41892 **    code were simply returned to the user, the b-tree layer would not
41893 **    automatically attempt a rollback, as it assumes that an error in a
41894 **    read-only statement cannot leave the pager in an internally inconsistent 
41895 **    state.
41896 **
41897 **    * The Pager.errCode variable is set to something other than SQLITE_OK.
41898 **    * There are one or more outstanding references to pages (after the
41899 **      last reference is dropped the pager should move back to OPEN state).
41900 **    * The pager is not an in-memory pager.
41901 **    
41902 **
41903 ** Notes:
41904 **
41905 **   * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
41906 **     connection is open in WAL mode. A WAL connection is always in one
41907 **     of the first four states.
41908 **
41909 **   * Normally, a connection open in exclusive mode is never in PAGER_OPEN
41910 **     state. There are two exceptions: immediately after exclusive-mode has
41911 **     been turned on (and before any read or write transactions are 
41912 **     executed), and when the pager is leaving the "error state".
41913 **
41914 **   * See also: assert_pager_state().
41915 */
41916 #define PAGER_OPEN                  0
41917 #define PAGER_READER                1
41918 #define PAGER_WRITER_LOCKED         2
41919 #define PAGER_WRITER_CACHEMOD       3
41920 #define PAGER_WRITER_DBMOD          4
41921 #define PAGER_WRITER_FINISHED       5
41922 #define PAGER_ERROR                 6
41923
41924 /*
41925 ** The Pager.eLock variable is almost always set to one of the 
41926 ** following locking-states, according to the lock currently held on
41927 ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
41928 ** This variable is kept up to date as locks are taken and released by
41929 ** the pagerLockDb() and pagerUnlockDb() wrappers.
41930 **
41931 ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
41932 ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
41933 ** the operation was successful. In these circumstances pagerLockDb() and
41934 ** pagerUnlockDb() take a conservative approach - eLock is always updated
41935 ** when unlocking the file, and only updated when locking the file if the
41936 ** VFS call is successful. This way, the Pager.eLock variable may be set
41937 ** to a less exclusive (lower) value than the lock that is actually held
41938 ** at the system level, but it is never set to a more exclusive value.
41939 **
41940 ** This is usually safe. If an xUnlock fails or appears to fail, there may 
41941 ** be a few redundant xLock() calls or a lock may be held for longer than
41942 ** required, but nothing really goes wrong.
41943 **
41944 ** The exception is when the database file is unlocked as the pager moves
41945 ** from ERROR to OPEN state. At this point there may be a hot-journal file 
41946 ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
41947 ** transition, by the same pager or any other). If the call to xUnlock()
41948 ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
41949 ** can confuse the call to xCheckReservedLock() call made later as part
41950 ** of hot-journal detection.
41951 **
41952 ** xCheckReservedLock() is defined as returning true "if there is a RESERVED 
41953 ** lock held by this process or any others". So xCheckReservedLock may 
41954 ** return true because the caller itself is holding an EXCLUSIVE lock (but
41955 ** doesn't know it because of a previous error in xUnlock). If this happens
41956 ** a hot-journal may be mistaken for a journal being created by an active
41957 ** transaction in another process, causing SQLite to read from the database
41958 ** without rolling it back.
41959 **
41960 ** To work around this, if a call to xUnlock() fails when unlocking the
41961 ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
41962 ** is only changed back to a real locking state after a successful call
41963 ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
41964 ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK 
41965 ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
41966 ** lock on the database file before attempting to roll it back. See function
41967 ** PagerSharedLock() for more detail.
41968 **
41969 ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in 
41970 ** PAGER_OPEN state.
41971 */
41972 #define UNKNOWN_LOCK                (EXCLUSIVE_LOCK+1)
41973
41974 /*
41975 ** A macro used for invoking the codec if there is one
41976 */
41977 #ifdef SQLITE_HAS_CODEC
41978 # define CODEC1(P,D,N,X,E) \
41979     if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
41980 # define CODEC2(P,D,N,X,E,O) \
41981     if( P->xCodec==0 ){ O=(char*)D; }else \
41982     if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
41983 #else
41984 # define CODEC1(P,D,N,X,E)   /* NO-OP */
41985 # define CODEC2(P,D,N,X,E,O) O=(char*)D
41986 #endif
41987
41988 /*
41989 ** The maximum allowed sector size. 64KiB. If the xSectorsize() method 
41990 ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
41991 ** This could conceivably cause corruption following a power failure on
41992 ** such a system. This is currently an undocumented limit.
41993 */
41994 #define MAX_SECTOR_SIZE 0x10000
41995
41996 /*
41997 ** An instance of the following structure is allocated for each active
41998 ** savepoint and statement transaction in the system. All such structures
41999 ** are stored in the Pager.aSavepoint[] array, which is allocated and
42000 ** resized using sqlite3Realloc().
42001 **
42002 ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
42003 ** set to 0. If a journal-header is written into the main journal while
42004 ** the savepoint is active, then iHdrOffset is set to the byte offset 
42005 ** immediately following the last journal record written into the main
42006 ** journal before the journal-header. This is required during savepoint
42007 ** rollback (see pagerPlaybackSavepoint()).
42008 */
42009 typedef struct PagerSavepoint PagerSavepoint;
42010 struct PagerSavepoint {
42011   i64 iOffset;                 /* Starting offset in main journal */
42012   i64 iHdrOffset;              /* See above */
42013   Bitvec *pInSavepoint;        /* Set of pages in this savepoint */
42014   Pgno nOrig;                  /* Original number of pages in file */
42015   Pgno iSubRec;                /* Index of first record in sub-journal */
42016 #ifndef SQLITE_OMIT_WAL
42017   u32 aWalData[WAL_SAVEPOINT_NDATA];        /* WAL savepoint context */
42018 #endif
42019 };
42020
42021 /*
42022 ** Bits of the Pager.doNotSpill flag.  See further description below.
42023 */
42024 #define SPILLFLAG_OFF         0x01      /* Never spill cache.  Set via pragma */
42025 #define SPILLFLAG_ROLLBACK    0x02      /* Current rolling back, so do not spill */
42026 #define SPILLFLAG_NOSYNC      0x04      /* Spill is ok, but do not sync */
42027
42028 /*
42029 ** An open page cache is an instance of struct Pager. A description of
42030 ** some of the more important member variables follows:
42031 **
42032 ** eState
42033 **
42034 **   The current 'state' of the pager object. See the comment and state
42035 **   diagram above for a description of the pager state.
42036 **
42037 ** eLock
42038 **
42039 **   For a real on-disk database, the current lock held on the database file -
42040 **   NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
42041 **
42042 **   For a temporary or in-memory database (neither of which require any
42043 **   locks), this variable is always set to EXCLUSIVE_LOCK. Since such
42044 **   databases always have Pager.exclusiveMode==1, this tricks the pager
42045 **   logic into thinking that it already has all the locks it will ever
42046 **   need (and no reason to release them).
42047 **
42048 **   In some (obscure) circumstances, this variable may also be set to
42049 **   UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
42050 **   details.
42051 **
42052 ** changeCountDone
42053 **
42054 **   This boolean variable is used to make sure that the change-counter 
42055 **   (the 4-byte header field at byte offset 24 of the database file) is 
42056 **   not updated more often than necessary. 
42057 **
42058 **   It is set to true when the change-counter field is updated, which 
42059 **   can only happen if an exclusive lock is held on the database file.
42060 **   It is cleared (set to false) whenever an exclusive lock is 
42061 **   relinquished on the database file. Each time a transaction is committed,
42062 **   The changeCountDone flag is inspected. If it is true, the work of
42063 **   updating the change-counter is omitted for the current transaction.
42064 **
42065 **   This mechanism means that when running in exclusive mode, a connection 
42066 **   need only update the change-counter once, for the first transaction
42067 **   committed.
42068 **
42069 ** setMaster
42070 **
42071 **   When PagerCommitPhaseOne() is called to commit a transaction, it may
42072 **   (or may not) specify a master-journal name to be written into the 
42073 **   journal file before it is synced to disk.
42074 **
42075 **   Whether or not a journal file contains a master-journal pointer affects 
42076 **   the way in which the journal file is finalized after the transaction is 
42077 **   committed or rolled back when running in "journal_mode=PERSIST" mode.
42078 **   If a journal file does not contain a master-journal pointer, it is
42079 **   finalized by overwriting the first journal header with zeroes. If
42080 **   it does contain a master-journal pointer the journal file is finalized 
42081 **   by truncating it to zero bytes, just as if the connection were 
42082 **   running in "journal_mode=truncate" mode.
42083 **
42084 **   Journal files that contain master journal pointers cannot be finalized
42085 **   simply by overwriting the first journal-header with zeroes, as the
42086 **   master journal pointer could interfere with hot-journal rollback of any
42087 **   subsequently interrupted transaction that reuses the journal file.
42088 **
42089 **   The flag is cleared as soon as the journal file is finalized (either
42090 **   by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
42091 **   journal file from being successfully finalized, the setMaster flag
42092 **   is cleared anyway (and the pager will move to ERROR state).
42093 **
42094 ** doNotSpill
42095 **
42096 **   This variables control the behavior of cache-spills  (calls made by
42097 **   the pcache module to the pagerStress() routine to write cached data
42098 **   to the file-system in order to free up memory).
42099 **
42100 **   When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
42101 **   writing to the database from pagerStress() is disabled altogether.
42102 **   The SPILLFLAG_ROLLBACK case is done in a very obscure case that
42103 **   comes up during savepoint rollback that requires the pcache module
42104 **   to allocate a new page to prevent the journal file from being written
42105 **   while it is being traversed by code in pager_playback().  The SPILLFLAG_OFF
42106 **   case is a user preference.
42107 ** 
42108 **   If the SPILLFLAG_NOSYNC bit is set, writing to the database from pagerStress()
42109 **   is permitted, but syncing the journal file is not. This flag is set
42110 **   by sqlite3PagerWrite() when the file-system sector-size is larger than
42111 **   the database page-size in order to prevent a journal sync from happening 
42112 **   in between the journalling of two pages on the same sector. 
42113 **
42114 ** subjInMemory
42115 **
42116 **   This is a boolean variable. If true, then any required sub-journal
42117 **   is opened as an in-memory journal file. If false, then in-memory
42118 **   sub-journals are only used for in-memory pager files.
42119 **
42120 **   This variable is updated by the upper layer each time a new 
42121 **   write-transaction is opened.
42122 **
42123 ** dbSize, dbOrigSize, dbFileSize
42124 **
42125 **   Variable dbSize is set to the number of pages in the database file.
42126 **   It is valid in PAGER_READER and higher states (all states except for
42127 **   OPEN and ERROR). 
42128 **
42129 **   dbSize is set based on the size of the database file, which may be 
42130 **   larger than the size of the database (the value stored at offset
42131 **   28 of the database header by the btree). If the size of the file
42132 **   is not an integer multiple of the page-size, the value stored in
42133 **   dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
42134 **   Except, any file that is greater than 0 bytes in size is considered
42135 **   to have at least one page. (i.e. a 1KB file with 2K page-size leads
42136 **   to dbSize==1).
42137 **
42138 **   During a write-transaction, if pages with page-numbers greater than
42139 **   dbSize are modified in the cache, dbSize is updated accordingly.
42140 **   Similarly, if the database is truncated using PagerTruncateImage(), 
42141 **   dbSize is updated.
42142 **
42143 **   Variables dbOrigSize and dbFileSize are valid in states 
42144 **   PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
42145 **   variable at the start of the transaction. It is used during rollback,
42146 **   and to determine whether or not pages need to be journalled before
42147 **   being modified.
42148 **
42149 **   Throughout a write-transaction, dbFileSize contains the size of
42150 **   the file on disk in pages. It is set to a copy of dbSize when the
42151 **   write-transaction is first opened, and updated when VFS calls are made
42152 **   to write or truncate the database file on disk. 
42153 **
42154 **   The only reason the dbFileSize variable is required is to suppress 
42155 **   unnecessary calls to xTruncate() after committing a transaction. If, 
42156 **   when a transaction is committed, the dbFileSize variable indicates 
42157 **   that the database file is larger than the database image (Pager.dbSize), 
42158 **   pager_truncate() is called. The pager_truncate() call uses xFilesize()
42159 **   to measure the database file on disk, and then truncates it if required.
42160 **   dbFileSize is not used when rolling back a transaction. In this case
42161 **   pager_truncate() is called unconditionally (which means there may be
42162 **   a call to xFilesize() that is not strictly required). In either case,
42163 **   pager_truncate() may cause the file to become smaller or larger.
42164 **
42165 ** dbHintSize
42166 **
42167 **   The dbHintSize variable is used to limit the number of calls made to
42168 **   the VFS xFileControl(FCNTL_SIZE_HINT) method. 
42169 **
42170 **   dbHintSize is set to a copy of the dbSize variable when a
42171 **   write-transaction is opened (at the same time as dbFileSize and
42172 **   dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
42173 **   dbHintSize is increased to the number of pages that correspond to the
42174 **   size-hint passed to the method call. See pager_write_pagelist() for 
42175 **   details.
42176 **
42177 ** errCode
42178 **
42179 **   The Pager.errCode variable is only ever used in PAGER_ERROR state. It
42180 **   is set to zero in all other states. In PAGER_ERROR state, Pager.errCode 
42181 **   is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX 
42182 **   sub-codes.
42183 */
42184 struct Pager {
42185   sqlite3_vfs *pVfs;          /* OS functions to use for IO */
42186   u8 exclusiveMode;           /* Boolean. True if locking_mode==EXCLUSIVE */
42187   u8 journalMode;             /* One of the PAGER_JOURNALMODE_* values */
42188   u8 useJournal;              /* Use a rollback journal on this file */
42189   u8 noSync;                  /* Do not sync the journal if true */
42190   u8 fullSync;                /* Do extra syncs of the journal for robustness */
42191   u8 ckptSyncFlags;           /* SYNC_NORMAL or SYNC_FULL for checkpoint */
42192   u8 walSyncFlags;            /* SYNC_NORMAL or SYNC_FULL for wal writes */
42193   u8 syncFlags;               /* SYNC_NORMAL or SYNC_FULL otherwise */
42194   u8 tempFile;                /* zFilename is a temporary or immutable file */
42195   u8 noLock;                  /* Do not lock (except in WAL mode) */
42196   u8 readOnly;                /* True for a read-only database */
42197   u8 memDb;                   /* True to inhibit all file I/O */
42198
42199   /**************************************************************************
42200   ** The following block contains those class members that change during
42201   ** routine operation.  Class members not in this block are either fixed
42202   ** when the pager is first created or else only change when there is a
42203   ** significant mode change (such as changing the page_size, locking_mode,
42204   ** or the journal_mode).  From another view, these class members describe
42205   ** the "state" of the pager, while other class members describe the
42206   ** "configuration" of the pager.
42207   */
42208   u8 eState;                  /* Pager state (OPEN, READER, WRITER_LOCKED..) */
42209   u8 eLock;                   /* Current lock held on database file */
42210   u8 changeCountDone;         /* Set after incrementing the change-counter */
42211   u8 setMaster;               /* True if a m-j name has been written to jrnl */
42212   u8 doNotSpill;              /* Do not spill the cache when non-zero */
42213   u8 subjInMemory;            /* True to use in-memory sub-journals */
42214   u8 bUseFetch;               /* True to use xFetch() */
42215   u8 hasBeenUsed;             /* True if any content previously read from this pager*/
42216   Pgno dbSize;                /* Number of pages in the database */
42217   Pgno dbOrigSize;            /* dbSize before the current transaction */
42218   Pgno dbFileSize;            /* Number of pages in the database file */
42219   Pgno dbHintSize;            /* Value passed to FCNTL_SIZE_HINT call */
42220   int errCode;                /* One of several kinds of errors */
42221   int nRec;                   /* Pages journalled since last j-header written */
42222   u32 cksumInit;              /* Quasi-random value added to every checksum */
42223   u32 nSubRec;                /* Number of records written to sub-journal */
42224   Bitvec *pInJournal;         /* One bit for each page in the database file */
42225   sqlite3_file *fd;           /* File descriptor for database */
42226   sqlite3_file *jfd;          /* File descriptor for main journal */
42227   sqlite3_file *sjfd;         /* File descriptor for sub-journal */
42228   i64 journalOff;             /* Current write offset in the journal file */
42229   i64 journalHdr;             /* Byte offset to previous journal header */
42230   sqlite3_backup *pBackup;    /* Pointer to list of ongoing backup processes */
42231   PagerSavepoint *aSavepoint; /* Array of active savepoints */
42232   int nSavepoint;             /* Number of elements in aSavepoint[] */
42233   u32 iDataVersion;           /* Changes whenever database content changes */
42234   char dbFileVers[16];        /* Changes whenever database file changes */
42235
42236   int nMmapOut;               /* Number of mmap pages currently outstanding */
42237   sqlite3_int64 szMmap;       /* Desired maximum mmap size */
42238   PgHdr *pMmapFreelist;       /* List of free mmap page headers (pDirty) */
42239   /*
42240   ** End of the routinely-changing class members
42241   ***************************************************************************/
42242
42243   u16 nExtra;                 /* Add this many bytes to each in-memory page */
42244   i16 nReserve;               /* Number of unused bytes at end of each page */
42245   u32 vfsFlags;               /* Flags for sqlite3_vfs.xOpen() */
42246   u32 sectorSize;             /* Assumed sector size during rollback */
42247   int pageSize;               /* Number of bytes in a page */
42248   Pgno mxPgno;                /* Maximum allowed size of the database */
42249   i64 journalSizeLimit;       /* Size limit for persistent journal files */
42250   char *zFilename;            /* Name of the database file */
42251   char *zJournal;             /* Name of the journal file */
42252   int (*xBusyHandler)(void*); /* Function to call when busy */
42253   void *pBusyHandlerArg;      /* Context argument for xBusyHandler */
42254   int aStat[3];               /* Total cache hits, misses and writes */
42255 #ifdef SQLITE_TEST
42256   int nRead;                  /* Database pages read */
42257 #endif
42258   void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
42259 #ifdef SQLITE_HAS_CODEC
42260   void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
42261   void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
42262   void (*xCodecFree)(void*);             /* Destructor for the codec */
42263   void *pCodec;               /* First argument to xCodec... methods */
42264 #endif
42265   char *pTmpSpace;            /* Pager.pageSize bytes of space for tmp use */
42266   PCache *pPCache;            /* Pointer to page cache object */
42267 #ifndef SQLITE_OMIT_WAL
42268   Wal *pWal;                  /* Write-ahead log used by "journal_mode=wal" */
42269   char *zWal;                 /* File name for write-ahead log */
42270 #endif
42271 };
42272
42273 /*
42274 ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
42275 ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS 
42276 ** or CACHE_WRITE to sqlite3_db_status().
42277 */
42278 #define PAGER_STAT_HIT   0
42279 #define PAGER_STAT_MISS  1
42280 #define PAGER_STAT_WRITE 2
42281
42282 /*
42283 ** The following global variables hold counters used for
42284 ** testing purposes only.  These variables do not exist in
42285 ** a non-testing build.  These variables are not thread-safe.
42286 */
42287 #ifdef SQLITE_TEST
42288 SQLITE_API int sqlite3_pager_readdb_count = 0;    /* Number of full pages read from DB */
42289 SQLITE_API int sqlite3_pager_writedb_count = 0;   /* Number of full pages written to DB */
42290 SQLITE_API int sqlite3_pager_writej_count = 0;    /* Number of pages written to journal */
42291 # define PAGER_INCR(v)  v++
42292 #else
42293 # define PAGER_INCR(v)
42294 #endif
42295
42296
42297
42298 /*
42299 ** Journal files begin with the following magic string.  The data
42300 ** was obtained from /dev/random.  It is used only as a sanity check.
42301 **
42302 ** Since version 2.8.0, the journal format contains additional sanity
42303 ** checking information.  If the power fails while the journal is being
42304 ** written, semi-random garbage data might appear in the journal
42305 ** file after power is restored.  If an attempt is then made
42306 ** to roll the journal back, the database could be corrupted.  The additional
42307 ** sanity checking data is an attempt to discover the garbage in the
42308 ** journal and ignore it.
42309 **
42310 ** The sanity checking information for the new journal format consists
42311 ** of a 32-bit checksum on each page of data.  The checksum covers both
42312 ** the page number and the pPager->pageSize bytes of data for the page.
42313 ** This cksum is initialized to a 32-bit random value that appears in the
42314 ** journal file right after the header.  The random initializer is important,
42315 ** because garbage data that appears at the end of a journal is likely
42316 ** data that was once in other files that have now been deleted.  If the
42317 ** garbage data came from an obsolete journal file, the checksums might
42318 ** be correct.  But by initializing the checksum to random value which
42319 ** is different for every journal, we minimize that risk.
42320 */
42321 static const unsigned char aJournalMagic[] = {
42322   0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
42323 };
42324
42325 /*
42326 ** The size of the of each page record in the journal is given by
42327 ** the following macro.
42328 */
42329 #define JOURNAL_PG_SZ(pPager)  ((pPager->pageSize) + 8)
42330
42331 /*
42332 ** The journal header size for this pager. This is usually the same 
42333 ** size as a single disk sector. See also setSectorSize().
42334 */
42335 #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
42336
42337 /*
42338 ** The macro MEMDB is true if we are dealing with an in-memory database.
42339 ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
42340 ** the value of MEMDB will be a constant and the compiler will optimize
42341 ** out code that would never execute.
42342 */
42343 #ifdef SQLITE_OMIT_MEMORYDB
42344 # define MEMDB 0
42345 #else
42346 # define MEMDB pPager->memDb
42347 #endif
42348
42349 /*
42350 ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
42351 ** interfaces to access the database using memory-mapped I/O.
42352 */
42353 #if SQLITE_MAX_MMAP_SIZE>0
42354 # define USEFETCH(x) ((x)->bUseFetch)
42355 #else
42356 # define USEFETCH(x) 0
42357 #endif
42358
42359 /*
42360 ** The maximum legal page number is (2^31 - 1).
42361 */
42362 #define PAGER_MAX_PGNO 2147483647
42363
42364 /*
42365 ** The argument to this macro is a file descriptor (type sqlite3_file*).
42366 ** Return 0 if it is not open, or non-zero (but not 1) if it is.
42367 **
42368 ** This is so that expressions can be written as:
42369 **
42370 **   if( isOpen(pPager->jfd) ){ ...
42371 **
42372 ** instead of
42373 **
42374 **   if( pPager->jfd->pMethods ){ ...
42375 */
42376 #define isOpen(pFd) ((pFd)->pMethods)
42377
42378 /*
42379 ** Return true if this pager uses a write-ahead log instead of the usual
42380 ** rollback journal. Otherwise false.
42381 */
42382 #ifndef SQLITE_OMIT_WAL
42383 static int pagerUseWal(Pager *pPager){
42384   return (pPager->pWal!=0);
42385 }
42386 #else
42387 # define pagerUseWal(x) 0
42388 # define pagerRollbackWal(x) 0
42389 # define pagerWalFrames(v,w,x,y) 0
42390 # define pagerOpenWalIfPresent(z) SQLITE_OK
42391 # define pagerBeginReadTransaction(z) SQLITE_OK
42392 #endif
42393
42394 #ifndef NDEBUG 
42395 /*
42396 ** Usage:
42397 **
42398 **   assert( assert_pager_state(pPager) );
42399 **
42400 ** This function runs many asserts to try to find inconsistencies in
42401 ** the internal state of the Pager object.
42402 */
42403 static int assert_pager_state(Pager *p){
42404   Pager *pPager = p;
42405
42406   /* State must be valid. */
42407   assert( p->eState==PAGER_OPEN
42408        || p->eState==PAGER_READER
42409        || p->eState==PAGER_WRITER_LOCKED
42410        || p->eState==PAGER_WRITER_CACHEMOD
42411        || p->eState==PAGER_WRITER_DBMOD
42412        || p->eState==PAGER_WRITER_FINISHED
42413        || p->eState==PAGER_ERROR
42414   );
42415
42416   /* Regardless of the current state, a temp-file connection always behaves
42417   ** as if it has an exclusive lock on the database file. It never updates
42418   ** the change-counter field, so the changeCountDone flag is always set.
42419   */
42420   assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
42421   assert( p->tempFile==0 || pPager->changeCountDone );
42422
42423   /* If the useJournal flag is clear, the journal-mode must be "OFF". 
42424   ** And if the journal-mode is "OFF", the journal file must not be open.
42425   */
42426   assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
42427   assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
42428
42429   /* Check that MEMDB implies noSync. And an in-memory journal. Since 
42430   ** this means an in-memory pager performs no IO at all, it cannot encounter 
42431   ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing 
42432   ** a journal file. (although the in-memory journal implementation may 
42433   ** return SQLITE_IOERR_NOMEM while the journal file is being written). It 
42434   ** is therefore not possible for an in-memory pager to enter the ERROR 
42435   ** state.
42436   */
42437   if( MEMDB ){
42438     assert( p->noSync );
42439     assert( p->journalMode==PAGER_JOURNALMODE_OFF 
42440          || p->journalMode==PAGER_JOURNALMODE_MEMORY 
42441     );
42442     assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
42443     assert( pagerUseWal(p)==0 );
42444   }
42445
42446   /* If changeCountDone is set, a RESERVED lock or greater must be held
42447   ** on the file.
42448   */
42449   assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
42450   assert( p->eLock!=PENDING_LOCK );
42451
42452   switch( p->eState ){
42453     case PAGER_OPEN:
42454       assert( !MEMDB );
42455       assert( pPager->errCode==SQLITE_OK );
42456       assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
42457       break;
42458
42459     case PAGER_READER:
42460       assert( pPager->errCode==SQLITE_OK );
42461       assert( p->eLock!=UNKNOWN_LOCK );
42462       assert( p->eLock>=SHARED_LOCK );
42463       break;
42464
42465     case PAGER_WRITER_LOCKED:
42466       assert( p->eLock!=UNKNOWN_LOCK );
42467       assert( pPager->errCode==SQLITE_OK );
42468       if( !pagerUseWal(pPager) ){
42469         assert( p->eLock>=RESERVED_LOCK );
42470       }
42471       assert( pPager->dbSize==pPager->dbOrigSize );
42472       assert( pPager->dbOrigSize==pPager->dbFileSize );
42473       assert( pPager->dbOrigSize==pPager->dbHintSize );
42474       assert( pPager->setMaster==0 );
42475       break;
42476
42477     case PAGER_WRITER_CACHEMOD:
42478       assert( p->eLock!=UNKNOWN_LOCK );
42479       assert( pPager->errCode==SQLITE_OK );
42480       if( !pagerUseWal(pPager) ){
42481         /* It is possible that if journal_mode=wal here that neither the
42482         ** journal file nor the WAL file are open. This happens during
42483         ** a rollback transaction that switches from journal_mode=off
42484         ** to journal_mode=wal.
42485         */
42486         assert( p->eLock>=RESERVED_LOCK );
42487         assert( isOpen(p->jfd) 
42488              || p->journalMode==PAGER_JOURNALMODE_OFF 
42489              || p->journalMode==PAGER_JOURNALMODE_WAL 
42490         );
42491       }
42492       assert( pPager->dbOrigSize==pPager->dbFileSize );
42493       assert( pPager->dbOrigSize==pPager->dbHintSize );
42494       break;
42495
42496     case PAGER_WRITER_DBMOD:
42497       assert( p->eLock==EXCLUSIVE_LOCK );
42498       assert( pPager->errCode==SQLITE_OK );
42499       assert( !pagerUseWal(pPager) );
42500       assert( p->eLock>=EXCLUSIVE_LOCK );
42501       assert( isOpen(p->jfd) 
42502            || p->journalMode==PAGER_JOURNALMODE_OFF 
42503            || p->journalMode==PAGER_JOURNALMODE_WAL 
42504       );
42505       assert( pPager->dbOrigSize<=pPager->dbHintSize );
42506       break;
42507
42508     case PAGER_WRITER_FINISHED:
42509       assert( p->eLock==EXCLUSIVE_LOCK );
42510       assert( pPager->errCode==SQLITE_OK );
42511       assert( !pagerUseWal(pPager) );
42512       assert( isOpen(p->jfd) 
42513            || p->journalMode==PAGER_JOURNALMODE_OFF 
42514            || p->journalMode==PAGER_JOURNALMODE_WAL 
42515       );
42516       break;
42517
42518     case PAGER_ERROR:
42519       /* There must be at least one outstanding reference to the pager if
42520       ** in ERROR state. Otherwise the pager should have already dropped
42521       ** back to OPEN state.
42522       */
42523       assert( pPager->errCode!=SQLITE_OK );
42524       assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
42525       break;
42526   }
42527
42528   return 1;
42529 }
42530 #endif /* ifndef NDEBUG */
42531
42532 #ifdef SQLITE_DEBUG 
42533 /*
42534 ** Return a pointer to a human readable string in a static buffer
42535 ** containing the state of the Pager object passed as an argument. This
42536 ** is intended to be used within debuggers. For example, as an alternative
42537 ** to "print *pPager" in gdb:
42538 **
42539 ** (gdb) printf "%s", print_pager_state(pPager)
42540 */
42541 static char *print_pager_state(Pager *p){
42542   static char zRet[1024];
42543
42544   sqlite3_snprintf(1024, zRet,
42545       "Filename:      %s\n"
42546       "State:         %s errCode=%d\n"
42547       "Lock:          %s\n"
42548       "Locking mode:  locking_mode=%s\n"
42549       "Journal mode:  journal_mode=%s\n"
42550       "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
42551       "Journal:       journalOff=%lld journalHdr=%lld\n"
42552       "Size:          dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
42553       , p->zFilename
42554       , p->eState==PAGER_OPEN            ? "OPEN" :
42555         p->eState==PAGER_READER          ? "READER" :
42556         p->eState==PAGER_WRITER_LOCKED   ? "WRITER_LOCKED" :
42557         p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
42558         p->eState==PAGER_WRITER_DBMOD    ? "WRITER_DBMOD" :
42559         p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
42560         p->eState==PAGER_ERROR           ? "ERROR" : "?error?"
42561       , (int)p->errCode
42562       , p->eLock==NO_LOCK         ? "NO_LOCK" :
42563         p->eLock==RESERVED_LOCK   ? "RESERVED" :
42564         p->eLock==EXCLUSIVE_LOCK  ? "EXCLUSIVE" :
42565         p->eLock==SHARED_LOCK     ? "SHARED" :
42566         p->eLock==UNKNOWN_LOCK    ? "UNKNOWN" : "?error?"
42567       , p->exclusiveMode ? "exclusive" : "normal"
42568       , p->journalMode==PAGER_JOURNALMODE_MEMORY   ? "memory" :
42569         p->journalMode==PAGER_JOURNALMODE_OFF      ? "off" :
42570         p->journalMode==PAGER_JOURNALMODE_DELETE   ? "delete" :
42571         p->journalMode==PAGER_JOURNALMODE_PERSIST  ? "persist" :
42572         p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
42573         p->journalMode==PAGER_JOURNALMODE_WAL      ? "wal" : "?error?"
42574       , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
42575       , p->journalOff, p->journalHdr
42576       , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
42577   );
42578
42579   return zRet;
42580 }
42581 #endif
42582
42583 /*
42584 ** Return true if it is necessary to write page *pPg into the sub-journal.
42585 ** A page needs to be written into the sub-journal if there exists one
42586 ** or more open savepoints for which:
42587 **
42588 **   * The page-number is less than or equal to PagerSavepoint.nOrig, and
42589 **   * The bit corresponding to the page-number is not set in
42590 **     PagerSavepoint.pInSavepoint.
42591 */
42592 static int subjRequiresPage(PgHdr *pPg){
42593   Pager *pPager = pPg->pPager;
42594   PagerSavepoint *p;
42595   Pgno pgno = pPg->pgno;
42596   int i;
42597   for(i=0; i<pPager->nSavepoint; i++){
42598     p = &pPager->aSavepoint[i];
42599     if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
42600       return 1;
42601     }
42602   }
42603   return 0;
42604 }
42605
42606 /*
42607 ** Return true if the page is already in the journal file.
42608 */
42609 static int pageInJournal(Pager *pPager, PgHdr *pPg){
42610   return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
42611 }
42612
42613 /*
42614 ** Read a 32-bit integer from the given file descriptor.  Store the integer
42615 ** that is read in *pRes.  Return SQLITE_OK if everything worked, or an
42616 ** error code is something goes wrong.
42617 **
42618 ** All values are stored on disk as big-endian.
42619 */
42620 static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
42621   unsigned char ac[4];
42622   int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
42623   if( rc==SQLITE_OK ){
42624     *pRes = sqlite3Get4byte(ac);
42625   }
42626   return rc;
42627 }
42628
42629 /*
42630 ** Write a 32-bit integer into a string buffer in big-endian byte order.
42631 */
42632 #define put32bits(A,B)  sqlite3Put4byte((u8*)A,B)
42633
42634
42635 /*
42636 ** Write a 32-bit integer into the given file descriptor.  Return SQLITE_OK
42637 ** on success or an error code is something goes wrong.
42638 */
42639 static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
42640   char ac[4];
42641   put32bits(ac, val);
42642   return sqlite3OsWrite(fd, ac, 4, offset);
42643 }
42644
42645 /*
42646 ** Unlock the database file to level eLock, which must be either NO_LOCK
42647 ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
42648 ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
42649 **
42650 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
42651 ** called, do not modify it. See the comment above the #define of 
42652 ** UNKNOWN_LOCK for an explanation of this.
42653 */
42654 static int pagerUnlockDb(Pager *pPager, int eLock){
42655   int rc = SQLITE_OK;
42656
42657   assert( !pPager->exclusiveMode || pPager->eLock==eLock );
42658   assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
42659   assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
42660   if( isOpen(pPager->fd) ){
42661     assert( pPager->eLock>=eLock );
42662     rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
42663     if( pPager->eLock!=UNKNOWN_LOCK ){
42664       pPager->eLock = (u8)eLock;
42665     }
42666     IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
42667   }
42668   return rc;
42669 }
42670
42671 /*
42672 ** Lock the database file to level eLock, which must be either SHARED_LOCK,
42673 ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
42674 ** Pager.eLock variable to the new locking state. 
42675 **
42676 ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is 
42677 ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK. 
42678 ** See the comment above the #define of UNKNOWN_LOCK for an explanation 
42679 ** of this.
42680 */
42681 static int pagerLockDb(Pager *pPager, int eLock){
42682   int rc = SQLITE_OK;
42683
42684   assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
42685   if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
42686     rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
42687     if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
42688       pPager->eLock = (u8)eLock;
42689       IOTRACE(("LOCK %p %d\n", pPager, eLock))
42690     }
42691   }
42692   return rc;
42693 }
42694
42695 /*
42696 ** This function determines whether or not the atomic-write optimization
42697 ** can be used with this pager. The optimization can be used if:
42698 **
42699 **  (a) the value returned by OsDeviceCharacteristics() indicates that
42700 **      a database page may be written atomically, and
42701 **  (b) the value returned by OsSectorSize() is less than or equal
42702 **      to the page size.
42703 **
42704 ** The optimization is also always enabled for temporary files. It is
42705 ** an error to call this function if pPager is opened on an in-memory
42706 ** database.
42707 **
42708 ** If the optimization cannot be used, 0 is returned. If it can be used,
42709 ** then the value returned is the size of the journal file when it
42710 ** contains rollback data for exactly one page.
42711 */
42712 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
42713 static int jrnlBufferSize(Pager *pPager){
42714   assert( !MEMDB );
42715   if( !pPager->tempFile ){
42716     int dc;                           /* Device characteristics */
42717     int nSector;                      /* Sector size */
42718     int szPage;                       /* Page size */
42719
42720     assert( isOpen(pPager->fd) );
42721     dc = sqlite3OsDeviceCharacteristics(pPager->fd);
42722     nSector = pPager->sectorSize;
42723     szPage = pPager->pageSize;
42724
42725     assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
42726     assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
42727     if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
42728       return 0;
42729     }
42730   }
42731
42732   return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
42733 }
42734 #endif
42735
42736 /*
42737 ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
42738 ** on the cache using a hash function.  This is used for testing
42739 ** and debugging only.
42740 */
42741 #ifdef SQLITE_CHECK_PAGES
42742 /*
42743 ** Return a 32-bit hash of the page data for pPage.
42744 */
42745 static u32 pager_datahash(int nByte, unsigned char *pData){
42746   u32 hash = 0;
42747   int i;
42748   for(i=0; i<nByte; i++){
42749     hash = (hash*1039) + pData[i];
42750   }
42751   return hash;
42752 }
42753 static u32 pager_pagehash(PgHdr *pPage){
42754   return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
42755 }
42756 static void pager_set_pagehash(PgHdr *pPage){
42757   pPage->pageHash = pager_pagehash(pPage);
42758 }
42759
42760 /*
42761 ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
42762 ** is defined, and NDEBUG is not defined, an assert() statement checks
42763 ** that the page is either dirty or still matches the calculated page-hash.
42764 */
42765 #define CHECK_PAGE(x) checkPage(x)
42766 static void checkPage(PgHdr *pPg){
42767   Pager *pPager = pPg->pPager;
42768   assert( pPager->eState!=PAGER_ERROR );
42769   assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
42770 }
42771
42772 #else
42773 #define pager_datahash(X,Y)  0
42774 #define pager_pagehash(X)  0
42775 #define pager_set_pagehash(X)
42776 #define CHECK_PAGE(x)
42777 #endif  /* SQLITE_CHECK_PAGES */
42778
42779 /*
42780 ** When this is called the journal file for pager pPager must be open.
42781 ** This function attempts to read a master journal file name from the 
42782 ** end of the file and, if successful, copies it into memory supplied 
42783 ** by the caller. See comments above writeMasterJournal() for the format
42784 ** used to store a master journal file name at the end of a journal file.
42785 **
42786 ** zMaster must point to a buffer of at least nMaster bytes allocated by
42787 ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
42788 ** enough space to write the master journal name). If the master journal
42789 ** name in the journal is longer than nMaster bytes (including a
42790 ** nul-terminator), then this is handled as if no master journal name
42791 ** were present in the journal.
42792 **
42793 ** If a master journal file name is present at the end of the journal
42794 ** file, then it is copied into the buffer pointed to by zMaster. A
42795 ** nul-terminator byte is appended to the buffer following the master
42796 ** journal file name.
42797 **
42798 ** If it is determined that no master journal file name is present 
42799 ** zMaster[0] is set to 0 and SQLITE_OK returned.
42800 **
42801 ** If an error occurs while reading from the journal file, an SQLite
42802 ** error code is returned.
42803 */
42804 static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
42805   int rc;                    /* Return code */
42806   u32 len;                   /* Length in bytes of master journal name */
42807   i64 szJ;                   /* Total size in bytes of journal file pJrnl */
42808   u32 cksum;                 /* MJ checksum value read from journal */
42809   u32 u;                     /* Unsigned loop counter */
42810   unsigned char aMagic[8];   /* A buffer to hold the magic header */
42811   zMaster[0] = '\0';
42812
42813   if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
42814    || szJ<16
42815    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
42816    || len>=nMaster 
42817    || len==0 
42818    || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
42819    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
42820    || memcmp(aMagic, aJournalMagic, 8)
42821    || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
42822   ){
42823     return rc;
42824   }
42825
42826   /* See if the checksum matches the master journal name */
42827   for(u=0; u<len; u++){
42828     cksum -= zMaster[u];
42829   }
42830   if( cksum ){
42831     /* If the checksum doesn't add up, then one or more of the disk sectors
42832     ** containing the master journal filename is corrupted. This means
42833     ** definitely roll back, so just return SQLITE_OK and report a (nul)
42834     ** master-journal filename.
42835     */
42836     len = 0;
42837   }
42838   zMaster[len] = '\0';
42839    
42840   return SQLITE_OK;
42841 }
42842
42843 /*
42844 ** Return the offset of the sector boundary at or immediately 
42845 ** following the value in pPager->journalOff, assuming a sector 
42846 ** size of pPager->sectorSize bytes.
42847 **
42848 ** i.e for a sector size of 512:
42849 **
42850 **   Pager.journalOff          Return value
42851 **   ---------------------------------------
42852 **   0                         0
42853 **   512                       512
42854 **   100                       512
42855 **   2000                      2048
42856 ** 
42857 */
42858 static i64 journalHdrOffset(Pager *pPager){
42859   i64 offset = 0;
42860   i64 c = pPager->journalOff;
42861   if( c ){
42862     offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
42863   }
42864   assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
42865   assert( offset>=c );
42866   assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
42867   return offset;
42868 }
42869
42870 /*
42871 ** The journal file must be open when this function is called.
42872 **
42873 ** This function is a no-op if the journal file has not been written to
42874 ** within the current transaction (i.e. if Pager.journalOff==0).
42875 **
42876 ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
42877 ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
42878 ** zero the 28-byte header at the start of the journal file. In either case, 
42879 ** if the pager is not in no-sync mode, sync the journal file immediately 
42880 ** after writing or truncating it.
42881 **
42882 ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
42883 ** following the truncation or zeroing described above the size of the 
42884 ** journal file in bytes is larger than this value, then truncate the
42885 ** journal file to Pager.journalSizeLimit bytes. The journal file does
42886 ** not need to be synced following this operation.
42887 **
42888 ** If an IO error occurs, abandon processing and return the IO error code.
42889 ** Otherwise, return SQLITE_OK.
42890 */
42891 static int zeroJournalHdr(Pager *pPager, int doTruncate){
42892   int rc = SQLITE_OK;                               /* Return code */
42893   assert( isOpen(pPager->jfd) );
42894   if( pPager->journalOff ){
42895     const i64 iLimit = pPager->journalSizeLimit;    /* Local cache of jsl */
42896
42897     IOTRACE(("JZEROHDR %p\n", pPager))
42898     if( doTruncate || iLimit==0 ){
42899       rc = sqlite3OsTruncate(pPager->jfd, 0);
42900     }else{
42901       static const char zeroHdr[28] = {0};
42902       rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
42903     }
42904     if( rc==SQLITE_OK && !pPager->noSync ){
42905       rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
42906     }
42907
42908     /* At this point the transaction is committed but the write lock 
42909     ** is still held on the file. If there is a size limit configured for 
42910     ** the persistent journal and the journal file currently consumes more
42911     ** space than that limit allows for, truncate it now. There is no need
42912     ** to sync the file following this operation.
42913     */
42914     if( rc==SQLITE_OK && iLimit>0 ){
42915       i64 sz;
42916       rc = sqlite3OsFileSize(pPager->jfd, &sz);
42917       if( rc==SQLITE_OK && sz>iLimit ){
42918         rc = sqlite3OsTruncate(pPager->jfd, iLimit);
42919       }
42920     }
42921   }
42922   return rc;
42923 }
42924
42925 /*
42926 ** The journal file must be open when this routine is called. A journal
42927 ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
42928 ** current location.
42929 **
42930 ** The format for the journal header is as follows:
42931 ** - 8 bytes: Magic identifying journal format.
42932 ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
42933 ** - 4 bytes: Random number used for page hash.
42934 ** - 4 bytes: Initial database page count.
42935 ** - 4 bytes: Sector size used by the process that wrote this journal.
42936 ** - 4 bytes: Database page size.
42937 ** 
42938 ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
42939 */
42940 static int writeJournalHdr(Pager *pPager){
42941   int rc = SQLITE_OK;                 /* Return code */
42942   char *zHeader = pPager->pTmpSpace;  /* Temporary space used to build header */
42943   u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
42944   u32 nWrite;                         /* Bytes of header sector written */
42945   int ii;                             /* Loop counter */
42946
42947   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
42948
42949   if( nHeader>JOURNAL_HDR_SZ(pPager) ){
42950     nHeader = JOURNAL_HDR_SZ(pPager);
42951   }
42952
42953   /* If there are active savepoints and any of them were created 
42954   ** since the most recent journal header was written, update the 
42955   ** PagerSavepoint.iHdrOffset fields now.
42956   */
42957   for(ii=0; ii<pPager->nSavepoint; ii++){
42958     if( pPager->aSavepoint[ii].iHdrOffset==0 ){
42959       pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
42960     }
42961   }
42962
42963   pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
42964
42965   /* 
42966   ** Write the nRec Field - the number of page records that follow this
42967   ** journal header. Normally, zero is written to this value at this time.
42968   ** After the records are added to the journal (and the journal synced, 
42969   ** if in full-sync mode), the zero is overwritten with the true number
42970   ** of records (see syncJournal()).
42971   **
42972   ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
42973   ** reading the journal this value tells SQLite to assume that the
42974   ** rest of the journal file contains valid page records. This assumption
42975   ** is dangerous, as if a failure occurred whilst writing to the journal
42976   ** file it may contain some garbage data. There are two scenarios
42977   ** where this risk can be ignored:
42978   **
42979   **   * When the pager is in no-sync mode. Corruption can follow a
42980   **     power failure in this case anyway.
42981   **
42982   **   * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
42983   **     that garbage data is never appended to the journal file.
42984   */
42985   assert( isOpen(pPager->fd) || pPager->noSync );
42986   if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
42987    || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND) 
42988   ){
42989     memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
42990     put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
42991   }else{
42992     memset(zHeader, 0, sizeof(aJournalMagic)+4);
42993   }
42994
42995   /* The random check-hash initializer */ 
42996   sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
42997   put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
42998   /* The initial database size */
42999   put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
43000   /* The assumed sector size for this process */
43001   put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
43002
43003   /* The page size */
43004   put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
43005
43006   /* Initializing the tail of the buffer is not necessary.  Everything
43007   ** works find if the following memset() is omitted.  But initializing
43008   ** the memory prevents valgrind from complaining, so we are willing to
43009   ** take the performance hit.
43010   */
43011   memset(&zHeader[sizeof(aJournalMagic)+20], 0,
43012          nHeader-(sizeof(aJournalMagic)+20));
43013
43014   /* In theory, it is only necessary to write the 28 bytes that the 
43015   ** journal header consumes to the journal file here. Then increment the 
43016   ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next 
43017   ** record is written to the following sector (leaving a gap in the file
43018   ** that will be implicitly filled in by the OS).
43019   **
43020   ** However it has been discovered that on some systems this pattern can 
43021   ** be significantly slower than contiguously writing data to the file,
43022   ** even if that means explicitly writing data to the block of 
43023   ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
43024   ** is done. 
43025   **
43026   ** The loop is required here in case the sector-size is larger than the 
43027   ** database page size. Since the zHeader buffer is only Pager.pageSize
43028   ** bytes in size, more than one call to sqlite3OsWrite() may be required
43029   ** to populate the entire journal header sector.
43030   */ 
43031   for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
43032     IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
43033     rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
43034     assert( pPager->journalHdr <= pPager->journalOff );
43035     pPager->journalOff += nHeader;
43036   }
43037
43038   return rc;
43039 }
43040
43041 /*
43042 ** The journal file must be open when this is called. A journal header file
43043 ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
43044 ** file. The current location in the journal file is given by
43045 ** pPager->journalOff. See comments above function writeJournalHdr() for
43046 ** a description of the journal header format.
43047 **
43048 ** If the header is read successfully, *pNRec is set to the number of
43049 ** page records following this header and *pDbSize is set to the size of the
43050 ** database before the transaction began, in pages. Also, pPager->cksumInit
43051 ** is set to the value read from the journal header. SQLITE_OK is returned
43052 ** in this case.
43053 **
43054 ** If the journal header file appears to be corrupted, SQLITE_DONE is
43055 ** returned and *pNRec and *PDbSize are undefined.  If JOURNAL_HDR_SZ bytes
43056 ** cannot be read from the journal file an error code is returned.
43057 */
43058 static int readJournalHdr(
43059   Pager *pPager,               /* Pager object */
43060   int isHot,
43061   i64 journalSize,             /* Size of the open journal file in bytes */
43062   u32 *pNRec,                  /* OUT: Value read from the nRec field */
43063   u32 *pDbSize                 /* OUT: Value of original database size field */
43064 ){
43065   int rc;                      /* Return code */
43066   unsigned char aMagic[8];     /* A buffer to hold the magic header */
43067   i64 iHdrOff;                 /* Offset of journal header being read */
43068
43069   assert( isOpen(pPager->jfd) );      /* Journal file must be open. */
43070
43071   /* Advance Pager.journalOff to the start of the next sector. If the
43072   ** journal file is too small for there to be a header stored at this
43073   ** point, return SQLITE_DONE.
43074   */
43075   pPager->journalOff = journalHdrOffset(pPager);
43076   if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
43077     return SQLITE_DONE;
43078   }
43079   iHdrOff = pPager->journalOff;
43080
43081   /* Read in the first 8 bytes of the journal header. If they do not match
43082   ** the  magic string found at the start of each journal header, return
43083   ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
43084   ** proceed.
43085   */
43086   if( isHot || iHdrOff!=pPager->journalHdr ){
43087     rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
43088     if( rc ){
43089       return rc;
43090     }
43091     if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
43092       return SQLITE_DONE;
43093     }
43094   }
43095
43096   /* Read the first three 32-bit fields of the journal header: The nRec
43097   ** field, the checksum-initializer and the database size at the start
43098   ** of the transaction. Return an error code if anything goes wrong.
43099   */
43100   if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
43101    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
43102    || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
43103   ){
43104     return rc;
43105   }
43106
43107   if( pPager->journalOff==0 ){
43108     u32 iPageSize;               /* Page-size field of journal header */
43109     u32 iSectorSize;             /* Sector-size field of journal header */
43110
43111     /* Read the page-size and sector-size journal header fields. */
43112     if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
43113      || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
43114     ){
43115       return rc;
43116     }
43117
43118     /* Versions of SQLite prior to 3.5.8 set the page-size field of the
43119     ** journal header to zero. In this case, assume that the Pager.pageSize
43120     ** variable is already set to the correct page size.
43121     */
43122     if( iPageSize==0 ){
43123       iPageSize = pPager->pageSize;
43124     }
43125
43126     /* Check that the values read from the page-size and sector-size fields
43127     ** are within range. To be 'in range', both values need to be a power
43128     ** of two greater than or equal to 512 or 32, and not greater than their 
43129     ** respective compile time maximum limits.
43130     */
43131     if( iPageSize<512                  || iSectorSize<32
43132      || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
43133      || ((iPageSize-1)&iPageSize)!=0   || ((iSectorSize-1)&iSectorSize)!=0 
43134     ){
43135       /* If the either the page-size or sector-size in the journal-header is 
43136       ** invalid, then the process that wrote the journal-header must have 
43137       ** crashed before the header was synced. In this case stop reading 
43138       ** the journal file here.
43139       */
43140       return SQLITE_DONE;
43141     }
43142
43143     /* Update the page-size to match the value read from the journal. 
43144     ** Use a testcase() macro to make sure that malloc failure within 
43145     ** PagerSetPagesize() is tested.
43146     */
43147     rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
43148     testcase( rc!=SQLITE_OK );
43149
43150     /* Update the assumed sector-size to match the value used by 
43151     ** the process that created this journal. If this journal was
43152     ** created by a process other than this one, then this routine
43153     ** is being called from within pager_playback(). The local value
43154     ** of Pager.sectorSize is restored at the end of that routine.
43155     */
43156     pPager->sectorSize = iSectorSize;
43157   }
43158
43159   pPager->journalOff += JOURNAL_HDR_SZ(pPager);
43160   return rc;
43161 }
43162
43163
43164 /*
43165 ** Write the supplied master journal name into the journal file for pager
43166 ** pPager at the current location. The master journal name must be the last
43167 ** thing written to a journal file. If the pager is in full-sync mode, the
43168 ** journal file descriptor is advanced to the next sector boundary before
43169 ** anything is written. The format is:
43170 **
43171 **   + 4 bytes: PAGER_MJ_PGNO.
43172 **   + N bytes: Master journal filename in utf-8.
43173 **   + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
43174 **   + 4 bytes: Master journal name checksum.
43175 **   + 8 bytes: aJournalMagic[].
43176 **
43177 ** The master journal page checksum is the sum of the bytes in the master
43178 ** journal name, where each byte is interpreted as a signed 8-bit integer.
43179 **
43180 ** If zMaster is a NULL pointer (occurs for a single database transaction), 
43181 ** this call is a no-op.
43182 */
43183 static int writeMasterJournal(Pager *pPager, const char *zMaster){
43184   int rc;                          /* Return code */
43185   int nMaster;                     /* Length of string zMaster */
43186   i64 iHdrOff;                     /* Offset of header in journal file */
43187   i64 jrnlSize;                    /* Size of journal file on disk */
43188   u32 cksum = 0;                   /* Checksum of string zMaster */
43189
43190   assert( pPager->setMaster==0 );
43191   assert( !pagerUseWal(pPager) );
43192
43193   if( !zMaster 
43194    || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
43195    || !isOpen(pPager->jfd)
43196   ){
43197     return SQLITE_OK;
43198   }
43199   pPager->setMaster = 1;
43200   assert( pPager->journalHdr <= pPager->journalOff );
43201
43202   /* Calculate the length in bytes and the checksum of zMaster */
43203   for(nMaster=0; zMaster[nMaster]; nMaster++){
43204     cksum += zMaster[nMaster];
43205   }
43206
43207   /* If in full-sync mode, advance to the next disk sector before writing
43208   ** the master journal name. This is in case the previous page written to
43209   ** the journal has already been synced.
43210   */
43211   if( pPager->fullSync ){
43212     pPager->journalOff = journalHdrOffset(pPager);
43213   }
43214   iHdrOff = pPager->journalOff;
43215
43216   /* Write the master journal data to the end of the journal file. If
43217   ** an error occurs, return the error code to the caller.
43218   */
43219   if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
43220    || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
43221    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
43222    || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
43223    || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
43224   ){
43225     return rc;
43226   }
43227   pPager->journalOff += (nMaster+20);
43228
43229   /* If the pager is in peristent-journal mode, then the physical 
43230   ** journal-file may extend past the end of the master-journal name
43231   ** and 8 bytes of magic data just written to the file. This is 
43232   ** dangerous because the code to rollback a hot-journal file
43233   ** will not be able to find the master-journal name to determine 
43234   ** whether or not the journal is hot. 
43235   **
43236   ** Easiest thing to do in this scenario is to truncate the journal 
43237   ** file to the required size.
43238   */ 
43239   if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
43240    && jrnlSize>pPager->journalOff
43241   ){
43242     rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
43243   }
43244   return rc;
43245 }
43246
43247 /*
43248 ** Discard the entire contents of the in-memory page-cache.
43249 */
43250 static void pager_reset(Pager *pPager){
43251   pPager->iDataVersion++;
43252   sqlite3BackupRestart(pPager->pBackup);
43253   sqlite3PcacheClear(pPager->pPCache);
43254 }
43255
43256 /*
43257 ** Return the pPager->iDataVersion value
43258 */
43259 SQLITE_PRIVATE u32 sqlite3PagerDataVersion(Pager *pPager){
43260   assert( pPager->eState>PAGER_OPEN );
43261   return pPager->iDataVersion;
43262 }
43263
43264 /*
43265 ** Free all structures in the Pager.aSavepoint[] array and set both
43266 ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
43267 ** if it is open and the pager is not in exclusive mode.
43268 */
43269 static void releaseAllSavepoints(Pager *pPager){
43270   int ii;               /* Iterator for looping through Pager.aSavepoint */
43271   for(ii=0; ii<pPager->nSavepoint; ii++){
43272     sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
43273   }
43274   if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
43275     sqlite3OsClose(pPager->sjfd);
43276   }
43277   sqlite3_free(pPager->aSavepoint);
43278   pPager->aSavepoint = 0;
43279   pPager->nSavepoint = 0;
43280   pPager->nSubRec = 0;
43281 }
43282
43283 /*
43284 ** Set the bit number pgno in the PagerSavepoint.pInSavepoint 
43285 ** bitvecs of all open savepoints. Return SQLITE_OK if successful
43286 ** or SQLITE_NOMEM if a malloc failure occurs.
43287 */
43288 static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
43289   int ii;                   /* Loop counter */
43290   int rc = SQLITE_OK;       /* Result code */
43291
43292   for(ii=0; ii<pPager->nSavepoint; ii++){
43293     PagerSavepoint *p = &pPager->aSavepoint[ii];
43294     if( pgno<=p->nOrig ){
43295       rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
43296       testcase( rc==SQLITE_NOMEM );
43297       assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
43298     }
43299   }
43300   return rc;
43301 }
43302
43303 /*
43304 ** This function is a no-op if the pager is in exclusive mode and not
43305 ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
43306 ** state.
43307 **
43308 ** If the pager is not in exclusive-access mode, the database file is
43309 ** completely unlocked. If the file is unlocked and the file-system does
43310 ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
43311 ** closed (if it is open).
43312 **
43313 ** If the pager is in ERROR state when this function is called, the 
43314 ** contents of the pager cache are discarded before switching back to 
43315 ** the OPEN state. Regardless of whether the pager is in exclusive-mode
43316 ** or not, any journal file left in the file-system will be treated
43317 ** as a hot-journal and rolled back the next time a read-transaction
43318 ** is opened (by this or by any other connection).
43319 */
43320 static void pager_unlock(Pager *pPager){
43321
43322   assert( pPager->eState==PAGER_READER 
43323        || pPager->eState==PAGER_OPEN 
43324        || pPager->eState==PAGER_ERROR 
43325   );
43326
43327   sqlite3BitvecDestroy(pPager->pInJournal);
43328   pPager->pInJournal = 0;
43329   releaseAllSavepoints(pPager);
43330
43331   if( pagerUseWal(pPager) ){
43332     assert( !isOpen(pPager->jfd) );
43333     sqlite3WalEndReadTransaction(pPager->pWal);
43334     pPager->eState = PAGER_OPEN;
43335   }else if( !pPager->exclusiveMode ){
43336     int rc;                       /* Error code returned by pagerUnlockDb() */
43337     int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
43338
43339     /* If the operating system support deletion of open files, then
43340     ** close the journal file when dropping the database lock.  Otherwise
43341     ** another connection with journal_mode=delete might delete the file
43342     ** out from under us.
43343     */
43344     assert( (PAGER_JOURNALMODE_MEMORY   & 5)!=1 );
43345     assert( (PAGER_JOURNALMODE_OFF      & 5)!=1 );
43346     assert( (PAGER_JOURNALMODE_WAL      & 5)!=1 );
43347     assert( (PAGER_JOURNALMODE_DELETE   & 5)!=1 );
43348     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
43349     assert( (PAGER_JOURNALMODE_PERSIST  & 5)==1 );
43350     if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
43351      || 1!=(pPager->journalMode & 5)
43352     ){
43353       sqlite3OsClose(pPager->jfd);
43354     }
43355
43356     /* If the pager is in the ERROR state and the call to unlock the database
43357     ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
43358     ** above the #define for UNKNOWN_LOCK for an explanation of why this
43359     ** is necessary.
43360     */
43361     rc = pagerUnlockDb(pPager, NO_LOCK);
43362     if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
43363       pPager->eLock = UNKNOWN_LOCK;
43364     }
43365
43366     /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
43367     ** without clearing the error code. This is intentional - the error
43368     ** code is cleared and the cache reset in the block below.
43369     */
43370     assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
43371     pPager->changeCountDone = 0;
43372     pPager->eState = PAGER_OPEN;
43373   }
43374
43375   /* If Pager.errCode is set, the contents of the pager cache cannot be
43376   ** trusted. Now that there are no outstanding references to the pager,
43377   ** it can safely move back to PAGER_OPEN state. This happens in both
43378   ** normal and exclusive-locking mode.
43379   */
43380   if( pPager->errCode ){
43381     assert( !MEMDB );
43382     pager_reset(pPager);
43383     pPager->changeCountDone = pPager->tempFile;
43384     pPager->eState = PAGER_OPEN;
43385     pPager->errCode = SQLITE_OK;
43386     if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
43387   }
43388
43389   pPager->journalOff = 0;
43390   pPager->journalHdr = 0;
43391   pPager->setMaster = 0;
43392 }
43393
43394 /*
43395 ** This function is called whenever an IOERR or FULL error that requires
43396 ** the pager to transition into the ERROR state may ahve occurred.
43397 ** The first argument is a pointer to the pager structure, the second 
43398 ** the error-code about to be returned by a pager API function. The 
43399 ** value returned is a copy of the second argument to this function. 
43400 **
43401 ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
43402 ** IOERR sub-codes, the pager enters the ERROR state and the error code
43403 ** is stored in Pager.errCode. While the pager remains in the ERROR state,
43404 ** all major API calls on the Pager will immediately return Pager.errCode.
43405 **
43406 ** The ERROR state indicates that the contents of the pager-cache 
43407 ** cannot be trusted. This state can be cleared by completely discarding 
43408 ** the contents of the pager-cache. If a transaction was active when
43409 ** the persistent error occurred, then the rollback journal may need
43410 ** to be replayed to restore the contents of the database file (as if
43411 ** it were a hot-journal).
43412 */
43413 static int pager_error(Pager *pPager, int rc){
43414   int rc2 = rc & 0xff;
43415   assert( rc==SQLITE_OK || !MEMDB );
43416   assert(
43417        pPager->errCode==SQLITE_FULL ||
43418        pPager->errCode==SQLITE_OK ||
43419        (pPager->errCode & 0xff)==SQLITE_IOERR
43420   );
43421   if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
43422     pPager->errCode = rc;
43423     pPager->eState = PAGER_ERROR;
43424   }
43425   return rc;
43426 }
43427
43428 static int pager_truncate(Pager *pPager, Pgno nPage);
43429
43430 /*
43431 ** This routine ends a transaction. A transaction is usually ended by 
43432 ** either a COMMIT or a ROLLBACK operation. This routine may be called 
43433 ** after rollback of a hot-journal, or if an error occurs while opening
43434 ** the journal file or writing the very first journal-header of a
43435 ** database transaction.
43436 ** 
43437 ** This routine is never called in PAGER_ERROR state. If it is called
43438 ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
43439 ** exclusive than a RESERVED lock, it is a no-op.
43440 **
43441 ** Otherwise, any active savepoints are released.
43442 **
43443 ** If the journal file is open, then it is "finalized". Once a journal 
43444 ** file has been finalized it is not possible to use it to roll back a 
43445 ** transaction. Nor will it be considered to be a hot-journal by this
43446 ** or any other database connection. Exactly how a journal is finalized
43447 ** depends on whether or not the pager is running in exclusive mode and
43448 ** the current journal-mode (Pager.journalMode value), as follows:
43449 **
43450 **   journalMode==MEMORY
43451 **     Journal file descriptor is simply closed. This destroys an 
43452 **     in-memory journal.
43453 **
43454 **   journalMode==TRUNCATE
43455 **     Journal file is truncated to zero bytes in size.
43456 **
43457 **   journalMode==PERSIST
43458 **     The first 28 bytes of the journal file are zeroed. This invalidates
43459 **     the first journal header in the file, and hence the entire journal
43460 **     file. An invalid journal file cannot be rolled back.
43461 **
43462 **   journalMode==DELETE
43463 **     The journal file is closed and deleted using sqlite3OsDelete().
43464 **
43465 **     If the pager is running in exclusive mode, this method of finalizing
43466 **     the journal file is never used. Instead, if the journalMode is
43467 **     DELETE and the pager is in exclusive mode, the method described under
43468 **     journalMode==PERSIST is used instead.
43469 **
43470 ** After the journal is finalized, the pager moves to PAGER_READER state.
43471 ** If running in non-exclusive rollback mode, the lock on the file is 
43472 ** downgraded to a SHARED_LOCK.
43473 **
43474 ** SQLITE_OK is returned if no error occurs. If an error occurs during
43475 ** any of the IO operations to finalize the journal file or unlock the
43476 ** database then the IO error code is returned to the user. If the 
43477 ** operation to finalize the journal file fails, then the code still
43478 ** tries to unlock the database file if not in exclusive mode. If the
43479 ** unlock operation fails as well, then the first error code related
43480 ** to the first error encountered (the journal finalization one) is
43481 ** returned.
43482 */
43483 static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
43484   int rc = SQLITE_OK;      /* Error code from journal finalization operation */
43485   int rc2 = SQLITE_OK;     /* Error code from db file unlock operation */
43486
43487   /* Do nothing if the pager does not have an open write transaction
43488   ** or at least a RESERVED lock. This function may be called when there
43489   ** is no write-transaction active but a RESERVED or greater lock is
43490   ** held under two circumstances:
43491   **
43492   **   1. After a successful hot-journal rollback, it is called with
43493   **      eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
43494   **
43495   **   2. If a connection with locking_mode=exclusive holding an EXCLUSIVE 
43496   **      lock switches back to locking_mode=normal and then executes a
43497   **      read-transaction, this function is called with eState==PAGER_READER 
43498   **      and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
43499   */
43500   assert( assert_pager_state(pPager) );
43501   assert( pPager->eState!=PAGER_ERROR );
43502   if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
43503     return SQLITE_OK;
43504   }
43505
43506   releaseAllSavepoints(pPager);
43507   assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
43508   if( isOpen(pPager->jfd) ){
43509     assert( !pagerUseWal(pPager) );
43510
43511     /* Finalize the journal file. */
43512     if( sqlite3IsMemJournal(pPager->jfd) ){
43513       assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
43514       sqlite3OsClose(pPager->jfd);
43515     }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
43516       if( pPager->journalOff==0 ){
43517         rc = SQLITE_OK;
43518       }else{
43519         rc = sqlite3OsTruncate(pPager->jfd, 0);
43520         if( rc==SQLITE_OK && pPager->fullSync ){
43521           /* Make sure the new file size is written into the inode right away.
43522           ** Otherwise the journal might resurrect following a power loss and
43523           ** cause the last transaction to roll back.  See
43524           ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
43525           */
43526           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
43527         }
43528       }
43529       pPager->journalOff = 0;
43530     }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
43531       || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
43532     ){
43533       rc = zeroJournalHdr(pPager, hasMaster);
43534       pPager->journalOff = 0;
43535     }else{
43536       /* This branch may be executed with Pager.journalMode==MEMORY if
43537       ** a hot-journal was just rolled back. In this case the journal
43538       ** file should be closed and deleted. If this connection writes to
43539       ** the database file, it will do so using an in-memory journal. 
43540       */
43541       int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
43542       assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE 
43543            || pPager->journalMode==PAGER_JOURNALMODE_MEMORY 
43544            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
43545       );
43546       sqlite3OsClose(pPager->jfd);
43547       if( bDelete ){
43548         rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
43549       }
43550     }
43551   }
43552
43553 #ifdef SQLITE_CHECK_PAGES
43554   sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
43555   if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
43556     PgHdr *p = sqlite3PagerLookup(pPager, 1);
43557     if( p ){
43558       p->pageHash = 0;
43559       sqlite3PagerUnrefNotNull(p);
43560     }
43561   }
43562 #endif
43563
43564   sqlite3BitvecDestroy(pPager->pInJournal);
43565   pPager->pInJournal = 0;
43566   pPager->nRec = 0;
43567   sqlite3PcacheCleanAll(pPager->pPCache);
43568   sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
43569
43570   if( pagerUseWal(pPager) ){
43571     /* Drop the WAL write-lock, if any. Also, if the connection was in 
43572     ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE 
43573     ** lock held on the database file.
43574     */
43575     rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
43576     assert( rc2==SQLITE_OK );
43577   }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
43578     /* This branch is taken when committing a transaction in rollback-journal
43579     ** mode if the database file on disk is larger than the database image.
43580     ** At this point the journal has been finalized and the transaction 
43581     ** successfully committed, but the EXCLUSIVE lock is still held on the
43582     ** file. So it is safe to truncate the database file to its minimum
43583     ** required size.  */
43584     assert( pPager->eLock==EXCLUSIVE_LOCK );
43585     rc = pager_truncate(pPager, pPager->dbSize);
43586   }
43587
43588   if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
43589     rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
43590     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
43591   }
43592
43593   if( !pPager->exclusiveMode 
43594    && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
43595   ){
43596     rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
43597     pPager->changeCountDone = 0;
43598   }
43599   pPager->eState = PAGER_READER;
43600   pPager->setMaster = 0;
43601
43602   return (rc==SQLITE_OK?rc2:rc);
43603 }
43604
43605 /*
43606 ** Execute a rollback if a transaction is active and unlock the 
43607 ** database file. 
43608 **
43609 ** If the pager has already entered the ERROR state, do not attempt 
43610 ** the rollback at this time. Instead, pager_unlock() is called. The
43611 ** call to pager_unlock() will discard all in-memory pages, unlock
43612 ** the database file and move the pager back to OPEN state. If this 
43613 ** means that there is a hot-journal left in the file-system, the next 
43614 ** connection to obtain a shared lock on the pager (which may be this one) 
43615 ** will roll it back.
43616 **
43617 ** If the pager has not already entered the ERROR state, but an IO or
43618 ** malloc error occurs during a rollback, then this will itself cause 
43619 ** the pager to enter the ERROR state. Which will be cleared by the
43620 ** call to pager_unlock(), as described above.
43621 */
43622 static void pagerUnlockAndRollback(Pager *pPager){
43623   if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
43624     assert( assert_pager_state(pPager) );
43625     if( pPager->eState>=PAGER_WRITER_LOCKED ){
43626       sqlite3BeginBenignMalloc();
43627       sqlite3PagerRollback(pPager);
43628       sqlite3EndBenignMalloc();
43629     }else if( !pPager->exclusiveMode ){
43630       assert( pPager->eState==PAGER_READER );
43631       pager_end_transaction(pPager, 0, 0);
43632     }
43633   }
43634   pager_unlock(pPager);
43635 }
43636
43637 /*
43638 ** Parameter aData must point to a buffer of pPager->pageSize bytes
43639 ** of data. Compute and return a checksum based ont the contents of the 
43640 ** page of data and the current value of pPager->cksumInit.
43641 **
43642 ** This is not a real checksum. It is really just the sum of the 
43643 ** random initial value (pPager->cksumInit) and every 200th byte
43644 ** of the page data, starting with byte offset (pPager->pageSize%200).
43645 ** Each byte is interpreted as an 8-bit unsigned integer.
43646 **
43647 ** Changing the formula used to compute this checksum results in an
43648 ** incompatible journal file format.
43649 **
43650 ** If journal corruption occurs due to a power failure, the most likely 
43651 ** scenario is that one end or the other of the record will be changed. 
43652 ** It is much less likely that the two ends of the journal record will be
43653 ** correct and the middle be corrupt.  Thus, this "checksum" scheme,
43654 ** though fast and simple, catches the mostly likely kind of corruption.
43655 */
43656 static u32 pager_cksum(Pager *pPager, const u8 *aData){
43657   u32 cksum = pPager->cksumInit;         /* Checksum value to return */
43658   int i = pPager->pageSize-200;          /* Loop counter */
43659   while( i>0 ){
43660     cksum += aData[i];
43661     i -= 200;
43662   }
43663   return cksum;
43664 }
43665
43666 /*
43667 ** Report the current page size and number of reserved bytes back
43668 ** to the codec.
43669 */
43670 #ifdef SQLITE_HAS_CODEC
43671 static void pagerReportSize(Pager *pPager){
43672   if( pPager->xCodecSizeChng ){
43673     pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
43674                            (int)pPager->nReserve);
43675   }
43676 }
43677 #else
43678 # define pagerReportSize(X)     /* No-op if we do not support a codec */
43679 #endif
43680
43681 /*
43682 ** Read a single page from either the journal file (if isMainJrnl==1) or
43683 ** from the sub-journal (if isMainJrnl==0) and playback that page.
43684 ** The page begins at offset *pOffset into the file. The *pOffset
43685 ** value is increased to the start of the next page in the journal.
43686 **
43687 ** The main rollback journal uses checksums - the statement journal does 
43688 ** not.
43689 **
43690 ** If the page number of the page record read from the (sub-)journal file
43691 ** is greater than the current value of Pager.dbSize, then playback is
43692 ** skipped and SQLITE_OK is returned.
43693 **
43694 ** If pDone is not NULL, then it is a record of pages that have already
43695 ** been played back.  If the page at *pOffset has already been played back
43696 ** (if the corresponding pDone bit is set) then skip the playback.
43697 ** Make sure the pDone bit corresponding to the *pOffset page is set
43698 ** prior to returning.
43699 **
43700 ** If the page record is successfully read from the (sub-)journal file
43701 ** and played back, then SQLITE_OK is returned. If an IO error occurs
43702 ** while reading the record from the (sub-)journal file or while writing
43703 ** to the database file, then the IO error code is returned. If data
43704 ** is successfully read from the (sub-)journal file but appears to be
43705 ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
43706 ** two circumstances:
43707 ** 
43708 **   * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
43709 **   * If the record is being rolled back from the main journal file
43710 **     and the checksum field does not match the record content.
43711 **
43712 ** Neither of these two scenarios are possible during a savepoint rollback.
43713 **
43714 ** If this is a savepoint rollback, then memory may have to be dynamically
43715 ** allocated by this function. If this is the case and an allocation fails,
43716 ** SQLITE_NOMEM is returned.
43717 */
43718 static int pager_playback_one_page(
43719   Pager *pPager,                /* The pager being played back */
43720   i64 *pOffset,                 /* Offset of record to playback */
43721   Bitvec *pDone,                /* Bitvec of pages already played back */
43722   int isMainJrnl,               /* 1 -> main journal. 0 -> sub-journal. */
43723   int isSavepnt                 /* True for a savepoint rollback */
43724 ){
43725   int rc;
43726   PgHdr *pPg;                   /* An existing page in the cache */
43727   Pgno pgno;                    /* The page number of a page in journal */
43728   u32 cksum;                    /* Checksum used for sanity checking */
43729   char *aData;                  /* Temporary storage for the page */
43730   sqlite3_file *jfd;            /* The file descriptor for the journal file */
43731   int isSynced;                 /* True if journal page is synced */
43732
43733   assert( (isMainJrnl&~1)==0 );      /* isMainJrnl is 0 or 1 */
43734   assert( (isSavepnt&~1)==0 );       /* isSavepnt is 0 or 1 */
43735   assert( isMainJrnl || pDone );     /* pDone always used on sub-journals */
43736   assert( isSavepnt || pDone==0 );   /* pDone never used on non-savepoint */
43737
43738   aData = pPager->pTmpSpace;
43739   assert( aData );         /* Temp storage must have already been allocated */
43740   assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
43741
43742   /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction 
43743   ** or savepoint rollback done at the request of the caller) or this is
43744   ** a hot-journal rollback. If it is a hot-journal rollback, the pager
43745   ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
43746   ** only reads from the main journal, not the sub-journal.
43747   */
43748   assert( pPager->eState>=PAGER_WRITER_CACHEMOD
43749        || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
43750   );
43751   assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
43752
43753   /* Read the page number and page data from the journal or sub-journal
43754   ** file. Return an error code to the caller if an IO error occurs.
43755   */
43756   jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
43757   rc = read32bits(jfd, *pOffset, &pgno);
43758   if( rc!=SQLITE_OK ) return rc;
43759   rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
43760   if( rc!=SQLITE_OK ) return rc;
43761   *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
43762
43763   /* Sanity checking on the page.  This is more important that I originally
43764   ** thought.  If a power failure occurs while the journal is being written,
43765   ** it could cause invalid data to be written into the journal.  We need to
43766   ** detect this invalid data (with high probability) and ignore it.
43767   */
43768   if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
43769     assert( !isSavepnt );
43770     return SQLITE_DONE;
43771   }
43772   if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
43773     return SQLITE_OK;
43774   }
43775   if( isMainJrnl ){
43776     rc = read32bits(jfd, (*pOffset)-4, &cksum);
43777     if( rc ) return rc;
43778     if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
43779       return SQLITE_DONE;
43780     }
43781   }
43782
43783   /* If this page has already been played by before during the current
43784   ** rollback, then don't bother to play it back again.
43785   */
43786   if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
43787     return rc;
43788   }
43789
43790   /* When playing back page 1, restore the nReserve setting
43791   */
43792   if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
43793     pPager->nReserve = ((u8*)aData)[20];
43794     pagerReportSize(pPager);
43795   }
43796
43797   /* If the pager is in CACHEMOD state, then there must be a copy of this
43798   ** page in the pager cache. In this case just update the pager cache,
43799   ** not the database file. The page is left marked dirty in this case.
43800   **
43801   ** An exception to the above rule: If the database is in no-sync mode
43802   ** and a page is moved during an incremental vacuum then the page may
43803   ** not be in the pager cache. Later: if a malloc() or IO error occurs
43804   ** during a Movepage() call, then the page may not be in the cache
43805   ** either. So the condition described in the above paragraph is not
43806   ** assert()able.
43807   **
43808   ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
43809   ** pager cache if it exists and the main file. The page is then marked 
43810   ** not dirty. Since this code is only executed in PAGER_OPEN state for
43811   ** a hot-journal rollback, it is guaranteed that the page-cache is empty
43812   ** if the pager is in OPEN state.
43813   **
43814   ** Ticket #1171:  The statement journal might contain page content that is
43815   ** different from the page content at the start of the transaction.
43816   ** This occurs when a page is changed prior to the start of a statement
43817   ** then changed again within the statement.  When rolling back such a
43818   ** statement we must not write to the original database unless we know
43819   ** for certain that original page contents are synced into the main rollback
43820   ** journal.  Otherwise, a power loss might leave modified data in the
43821   ** database file without an entry in the rollback journal that can
43822   ** restore the database to its original form.  Two conditions must be
43823   ** met before writing to the database files. (1) the database must be
43824   ** locked.  (2) we know that the original page content is fully synced
43825   ** in the main journal either because the page is not in cache or else
43826   ** the page is marked as needSync==0.
43827   **
43828   ** 2008-04-14:  When attempting to vacuum a corrupt database file, it
43829   ** is possible to fail a statement on a database that does not yet exist.
43830   ** Do not attempt to write if database file has never been opened.
43831   */
43832   if( pagerUseWal(pPager) ){
43833     pPg = 0;
43834   }else{
43835     pPg = sqlite3PagerLookup(pPager, pgno);
43836   }
43837   assert( pPg || !MEMDB );
43838   assert( pPager->eState!=PAGER_OPEN || pPg==0 );
43839   PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
43840            PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
43841            (isMainJrnl?"main-journal":"sub-journal")
43842   ));
43843   if( isMainJrnl ){
43844     isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
43845   }else{
43846     isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
43847   }
43848   if( isOpen(pPager->fd)
43849    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
43850    && isSynced
43851   ){
43852     i64 ofst = (pgno-1)*(i64)pPager->pageSize;
43853     testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
43854     assert( !pagerUseWal(pPager) );
43855     rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
43856     if( pgno>pPager->dbFileSize ){
43857       pPager->dbFileSize = pgno;
43858     }
43859     if( pPager->pBackup ){
43860       CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
43861       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
43862       CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
43863     }
43864   }else if( !isMainJrnl && pPg==0 ){
43865     /* If this is a rollback of a savepoint and data was not written to
43866     ** the database and the page is not in-memory, there is a potential
43867     ** problem. When the page is next fetched by the b-tree layer, it 
43868     ** will be read from the database file, which may or may not be 
43869     ** current. 
43870     **
43871     ** There are a couple of different ways this can happen. All are quite
43872     ** obscure. When running in synchronous mode, this can only happen 
43873     ** if the page is on the free-list at the start of the transaction, then
43874     ** populated, then moved using sqlite3PagerMovepage().
43875     **
43876     ** The solution is to add an in-memory page to the cache containing
43877     ** the data just read from the sub-journal. Mark the page as dirty 
43878     ** and if the pager requires a journal-sync, then mark the page as 
43879     ** requiring a journal-sync before it is written.
43880     */
43881     assert( isSavepnt );
43882     assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
43883     pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
43884     rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
43885     assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
43886     pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
43887     if( rc!=SQLITE_OK ) return rc;
43888     pPg->flags &= ~PGHDR_NEED_READ;
43889     sqlite3PcacheMakeDirty(pPg);
43890   }
43891   if( pPg ){
43892     /* No page should ever be explicitly rolled back that is in use, except
43893     ** for page 1 which is held in use in order to keep the lock on the
43894     ** database active. However such a page may be rolled back as a result
43895     ** of an internal error resulting in an automatic call to
43896     ** sqlite3PagerRollback().
43897     */
43898     void *pData;
43899     pData = pPg->pData;
43900     memcpy(pData, (u8*)aData, pPager->pageSize);
43901     pPager->xReiniter(pPg);
43902     if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
43903       /* If the contents of this page were just restored from the main 
43904       ** journal file, then its content must be as they were when the 
43905       ** transaction was first opened. In this case we can mark the page
43906       ** as clean, since there will be no need to write it out to the
43907       ** database.
43908       **
43909       ** There is one exception to this rule. If the page is being rolled
43910       ** back as part of a savepoint (or statement) rollback from an 
43911       ** unsynced portion of the main journal file, then it is not safe
43912       ** to mark the page as clean. This is because marking the page as
43913       ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
43914       ** already in the journal file (recorded in Pager.pInJournal) and
43915       ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
43916       ** again within this transaction, it will be marked as dirty but
43917       ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
43918       ** be written out into the database file before its journal file
43919       ** segment is synced. If a crash occurs during or following this,
43920       ** database corruption may ensue.
43921       */
43922       assert( !pagerUseWal(pPager) );
43923       sqlite3PcacheMakeClean(pPg);
43924     }
43925     pager_set_pagehash(pPg);
43926
43927     /* If this was page 1, then restore the value of Pager.dbFileVers.
43928     ** Do this before any decoding. */
43929     if( pgno==1 ){
43930       memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
43931     }
43932
43933     /* Decode the page just read from disk */
43934     CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
43935     sqlite3PcacheRelease(pPg);
43936   }
43937   return rc;
43938 }
43939
43940 /*
43941 ** Parameter zMaster is the name of a master journal file. A single journal
43942 ** file that referred to the master journal file has just been rolled back.
43943 ** This routine checks if it is possible to delete the master journal file,
43944 ** and does so if it is.
43945 **
43946 ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not 
43947 ** available for use within this function.
43948 **
43949 ** When a master journal file is created, it is populated with the names 
43950 ** of all of its child journals, one after another, formatted as utf-8 
43951 ** encoded text. The end of each child journal file is marked with a 
43952 ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
43953 ** file for a transaction involving two databases might be:
43954 **
43955 **   "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
43956 **
43957 ** A master journal file may only be deleted once all of its child 
43958 ** journals have been rolled back.
43959 **
43960 ** This function reads the contents of the master-journal file into 
43961 ** memory and loops through each of the child journal names. For
43962 ** each child journal, it checks if:
43963 **
43964 **   * if the child journal exists, and if so
43965 **   * if the child journal contains a reference to master journal 
43966 **     file zMaster
43967 **
43968 ** If a child journal can be found that matches both of the criteria
43969 ** above, this function returns without doing anything. Otherwise, if
43970 ** no such child journal can be found, file zMaster is deleted from
43971 ** the file-system using sqlite3OsDelete().
43972 **
43973 ** If an IO error within this function, an error code is returned. This
43974 ** function allocates memory by calling sqlite3Malloc(). If an allocation
43975 ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors 
43976 ** occur, SQLITE_OK is returned.
43977 **
43978 ** TODO: This function allocates a single block of memory to load
43979 ** the entire contents of the master journal file. This could be
43980 ** a couple of kilobytes or so - potentially larger than the page 
43981 ** size.
43982 */
43983 static int pager_delmaster(Pager *pPager, const char *zMaster){
43984   sqlite3_vfs *pVfs = pPager->pVfs;
43985   int rc;                   /* Return code */
43986   sqlite3_file *pMaster;    /* Malloc'd master-journal file descriptor */
43987   sqlite3_file *pJournal;   /* Malloc'd child-journal file descriptor */
43988   char *zMasterJournal = 0; /* Contents of master journal file */
43989   i64 nMasterJournal;       /* Size of master journal file */
43990   char *zJournal;           /* Pointer to one journal within MJ file */
43991   char *zMasterPtr;         /* Space to hold MJ filename from a journal file */
43992   int nMasterPtr;           /* Amount of space allocated to zMasterPtr[] */
43993
43994   /* Allocate space for both the pJournal and pMaster file descriptors.
43995   ** If successful, open the master journal file for reading.
43996   */
43997   pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
43998   pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
43999   if( !pMaster ){
44000     rc = SQLITE_NOMEM;
44001   }else{
44002     const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
44003     rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
44004   }
44005   if( rc!=SQLITE_OK ) goto delmaster_out;
44006
44007   /* Load the entire master journal file into space obtained from
44008   ** sqlite3_malloc() and pointed to by zMasterJournal.   Also obtain
44009   ** sufficient space (in zMasterPtr) to hold the names of master
44010   ** journal files extracted from regular rollback-journals.
44011   */
44012   rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
44013   if( rc!=SQLITE_OK ) goto delmaster_out;
44014   nMasterPtr = pVfs->mxPathname+1;
44015   zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
44016   if( !zMasterJournal ){
44017     rc = SQLITE_NOMEM;
44018     goto delmaster_out;
44019   }
44020   zMasterPtr = &zMasterJournal[nMasterJournal+1];
44021   rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
44022   if( rc!=SQLITE_OK ) goto delmaster_out;
44023   zMasterJournal[nMasterJournal] = 0;
44024
44025   zJournal = zMasterJournal;
44026   while( (zJournal-zMasterJournal)<nMasterJournal ){
44027     int exists;
44028     rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
44029     if( rc!=SQLITE_OK ){
44030       goto delmaster_out;
44031     }
44032     if( exists ){
44033       /* One of the journals pointed to by the master journal exists.
44034       ** Open it and check if it points at the master journal. If
44035       ** so, return without deleting the master journal file.
44036       */
44037       int c;
44038       int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
44039       rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
44040       if( rc!=SQLITE_OK ){
44041         goto delmaster_out;
44042       }
44043
44044       rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
44045       sqlite3OsClose(pJournal);
44046       if( rc!=SQLITE_OK ){
44047         goto delmaster_out;
44048       }
44049
44050       c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
44051       if( c ){
44052         /* We have a match. Do not delete the master journal file. */
44053         goto delmaster_out;
44054       }
44055     }
44056     zJournal += (sqlite3Strlen30(zJournal)+1);
44057   }
44058  
44059   sqlite3OsClose(pMaster);
44060   rc = sqlite3OsDelete(pVfs, zMaster, 0);
44061
44062 delmaster_out:
44063   sqlite3_free(zMasterJournal);
44064   if( pMaster ){
44065     sqlite3OsClose(pMaster);
44066     assert( !isOpen(pJournal) );
44067     sqlite3_free(pMaster);
44068   }
44069   return rc;
44070 }
44071
44072
44073 /*
44074 ** This function is used to change the actual size of the database 
44075 ** file in the file-system. This only happens when committing a transaction,
44076 ** or rolling back a transaction (including rolling back a hot-journal).
44077 **
44078 ** If the main database file is not open, or the pager is not in either
44079 ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size 
44080 ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes). 
44081 ** If the file on disk is currently larger than nPage pages, then use the VFS
44082 ** xTruncate() method to truncate it.
44083 **
44084 ** Or, it might be the case that the file on disk is smaller than 
44085 ** nPage pages. Some operating system implementations can get confused if 
44086 ** you try to truncate a file to some size that is larger than it 
44087 ** currently is, so detect this case and write a single zero byte to 
44088 ** the end of the new file instead.
44089 **
44090 ** If successful, return SQLITE_OK. If an IO error occurs while modifying
44091 ** the database file, return the error code to the caller.
44092 */
44093 static int pager_truncate(Pager *pPager, Pgno nPage){
44094   int rc = SQLITE_OK;
44095   assert( pPager->eState!=PAGER_ERROR );
44096   assert( pPager->eState!=PAGER_READER );
44097   
44098   if( isOpen(pPager->fd) 
44099    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN) 
44100   ){
44101     i64 currentSize, newSize;
44102     int szPage = pPager->pageSize;
44103     assert( pPager->eLock==EXCLUSIVE_LOCK );
44104     /* TODO: Is it safe to use Pager.dbFileSize here? */
44105     rc = sqlite3OsFileSize(pPager->fd, &currentSize);
44106     newSize = szPage*(i64)nPage;
44107     if( rc==SQLITE_OK && currentSize!=newSize ){
44108       if( currentSize>newSize ){
44109         rc = sqlite3OsTruncate(pPager->fd, newSize);
44110       }else if( (currentSize+szPage)<=newSize ){
44111         char *pTmp = pPager->pTmpSpace;
44112         memset(pTmp, 0, szPage);
44113         testcase( (newSize-szPage) == currentSize );
44114         testcase( (newSize-szPage) >  currentSize );
44115         rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
44116       }
44117       if( rc==SQLITE_OK ){
44118         pPager->dbFileSize = nPage;
44119       }
44120     }
44121   }
44122   return rc;
44123 }
44124
44125 /*
44126 ** Return a sanitized version of the sector-size of OS file pFile. The
44127 ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
44128 */
44129 SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
44130   int iRet = sqlite3OsSectorSize(pFile);
44131   if( iRet<32 ){
44132     iRet = 512;
44133   }else if( iRet>MAX_SECTOR_SIZE ){
44134     assert( MAX_SECTOR_SIZE>=512 );
44135     iRet = MAX_SECTOR_SIZE;
44136   }
44137   return iRet;
44138 }
44139
44140 /*
44141 ** Set the value of the Pager.sectorSize variable for the given
44142 ** pager based on the value returned by the xSectorSize method
44143 ** of the open database file. The sector size will be used 
44144 ** to determine the size and alignment of journal header and 
44145 ** master journal pointers within created journal files.
44146 **
44147 ** For temporary files the effective sector size is always 512 bytes.
44148 **
44149 ** Otherwise, for non-temporary files, the effective sector size is
44150 ** the value returned by the xSectorSize() method rounded up to 32 if
44151 ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
44152 ** is greater than MAX_SECTOR_SIZE.
44153 **
44154 ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
44155 ** the effective sector size to its minimum value (512).  The purpose of
44156 ** pPager->sectorSize is to define the "blast radius" of bytes that
44157 ** might change if a crash occurs while writing to a single byte in
44158 ** that range.  But with POWERSAFE_OVERWRITE, the blast radius is zero
44159 ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
44160 ** size.  For backwards compatibility of the rollback journal file format,
44161 ** we cannot reduce the effective sector size below 512.
44162 */
44163 static void setSectorSize(Pager *pPager){
44164   assert( isOpen(pPager->fd) || pPager->tempFile );
44165
44166   if( pPager->tempFile
44167    || (sqlite3OsDeviceCharacteristics(pPager->fd) & 
44168               SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
44169   ){
44170     /* Sector size doesn't matter for temporary files. Also, the file
44171     ** may not have been opened yet, in which case the OsSectorSize()
44172     ** call will segfault. */
44173     pPager->sectorSize = 512;
44174   }else{
44175     pPager->sectorSize = sqlite3SectorSize(pPager->fd);
44176   }
44177 }
44178
44179 /*
44180 ** Playback the journal and thus restore the database file to
44181 ** the state it was in before we started making changes.  
44182 **
44183 ** The journal file format is as follows: 
44184 **
44185 **  (1)  8 byte prefix.  A copy of aJournalMagic[].
44186 **  (2)  4 byte big-endian integer which is the number of valid page records
44187 **       in the journal.  If this value is 0xffffffff, then compute the
44188 **       number of page records from the journal size.
44189 **  (3)  4 byte big-endian integer which is the initial value for the 
44190 **       sanity checksum.
44191 **  (4)  4 byte integer which is the number of pages to truncate the
44192 **       database to during a rollback.
44193 **  (5)  4 byte big-endian integer which is the sector size.  The header
44194 **       is this many bytes in size.
44195 **  (6)  4 byte big-endian integer which is the page size.
44196 **  (7)  zero padding out to the next sector size.
44197 **  (8)  Zero or more pages instances, each as follows:
44198 **        +  4 byte page number.
44199 **        +  pPager->pageSize bytes of data.
44200 **        +  4 byte checksum
44201 **
44202 ** When we speak of the journal header, we mean the first 7 items above.
44203 ** Each entry in the journal is an instance of the 8th item.
44204 **
44205 ** Call the value from the second bullet "nRec".  nRec is the number of
44206 ** valid page entries in the journal.  In most cases, you can compute the
44207 ** value of nRec from the size of the journal file.  But if a power
44208 ** failure occurred while the journal was being written, it could be the
44209 ** case that the size of the journal file had already been increased but
44210 ** the extra entries had not yet made it safely to disk.  In such a case,
44211 ** the value of nRec computed from the file size would be too large.  For
44212 ** that reason, we always use the nRec value in the header.
44213 **
44214 ** If the nRec value is 0xffffffff it means that nRec should be computed
44215 ** from the file size.  This value is used when the user selects the
44216 ** no-sync option for the journal.  A power failure could lead to corruption
44217 ** in this case.  But for things like temporary table (which will be
44218 ** deleted when the power is restored) we don't care.  
44219 **
44220 ** If the file opened as the journal file is not a well-formed
44221 ** journal file then all pages up to the first corrupted page are rolled
44222 ** back (or no pages if the journal header is corrupted). The journal file
44223 ** is then deleted and SQLITE_OK returned, just as if no corruption had
44224 ** been encountered.
44225 **
44226 ** If an I/O or malloc() error occurs, the journal-file is not deleted
44227 ** and an error code is returned.
44228 **
44229 ** The isHot parameter indicates that we are trying to rollback a journal
44230 ** that might be a hot journal.  Or, it could be that the journal is 
44231 ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
44232 ** If the journal really is hot, reset the pager cache prior rolling
44233 ** back any content.  If the journal is merely persistent, no reset is
44234 ** needed.
44235 */
44236 static int pager_playback(Pager *pPager, int isHot){
44237   sqlite3_vfs *pVfs = pPager->pVfs;
44238   i64 szJ;                 /* Size of the journal file in bytes */
44239   u32 nRec;                /* Number of Records in the journal */
44240   u32 u;                   /* Unsigned loop counter */
44241   Pgno mxPg = 0;           /* Size of the original file in pages */
44242   int rc;                  /* Result code of a subroutine */
44243   int res = 1;             /* Value returned by sqlite3OsAccess() */
44244   char *zMaster = 0;       /* Name of master journal file if any */
44245   int needPagerReset;      /* True to reset page prior to first page rollback */
44246   int nPlayback = 0;       /* Total number of pages restored from journal */
44247
44248   /* Figure out how many records are in the journal.  Abort early if
44249   ** the journal is empty.
44250   */
44251   assert( isOpen(pPager->jfd) );
44252   rc = sqlite3OsFileSize(pPager->jfd, &szJ);
44253   if( rc!=SQLITE_OK ){
44254     goto end_playback;
44255   }
44256
44257   /* Read the master journal name from the journal, if it is present.
44258   ** If a master journal file name is specified, but the file is not
44259   ** present on disk, then the journal is not hot and does not need to be
44260   ** played back.
44261   **
44262   ** TODO: Technically the following is an error because it assumes that
44263   ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
44264   ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
44265   **  mxPathname is 512, which is the same as the minimum allowable value
44266   ** for pageSize.
44267   */
44268   zMaster = pPager->pTmpSpace;
44269   rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
44270   if( rc==SQLITE_OK && zMaster[0] ){
44271     rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
44272   }
44273   zMaster = 0;
44274   if( rc!=SQLITE_OK || !res ){
44275     goto end_playback;
44276   }
44277   pPager->journalOff = 0;
44278   needPagerReset = isHot;
44279
44280   /* This loop terminates either when a readJournalHdr() or 
44281   ** pager_playback_one_page() call returns SQLITE_DONE or an IO error 
44282   ** occurs. 
44283   */
44284   while( 1 ){
44285     /* Read the next journal header from the journal file.  If there are
44286     ** not enough bytes left in the journal file for a complete header, or
44287     ** it is corrupted, then a process must have failed while writing it.
44288     ** This indicates nothing more needs to be rolled back.
44289     */
44290     rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
44291     if( rc!=SQLITE_OK ){ 
44292       if( rc==SQLITE_DONE ){
44293         rc = SQLITE_OK;
44294       }
44295       goto end_playback;
44296     }
44297
44298     /* If nRec is 0xffffffff, then this journal was created by a process
44299     ** working in no-sync mode. This means that the rest of the journal
44300     ** file consists of pages, there are no more journal headers. Compute
44301     ** the value of nRec based on this assumption.
44302     */
44303     if( nRec==0xffffffff ){
44304       assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
44305       nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
44306     }
44307
44308     /* If nRec is 0 and this rollback is of a transaction created by this
44309     ** process and if this is the final header in the journal, then it means
44310     ** that this part of the journal was being filled but has not yet been
44311     ** synced to disk.  Compute the number of pages based on the remaining
44312     ** size of the file.
44313     **
44314     ** The third term of the test was added to fix ticket #2565.
44315     ** When rolling back a hot journal, nRec==0 always means that the next
44316     ** chunk of the journal contains zero pages to be rolled back.  But
44317     ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
44318     ** the journal, it means that the journal might contain additional
44319     ** pages that need to be rolled back and that the number of pages 
44320     ** should be computed based on the journal file size.
44321     */
44322     if( nRec==0 && !isHot &&
44323         pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
44324       nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
44325     }
44326
44327     /* If this is the first header read from the journal, truncate the
44328     ** database file back to its original size.
44329     */
44330     if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
44331       rc = pager_truncate(pPager, mxPg);
44332       if( rc!=SQLITE_OK ){
44333         goto end_playback;
44334       }
44335       pPager->dbSize = mxPg;
44336     }
44337
44338     /* Copy original pages out of the journal and back into the 
44339     ** database file and/or page cache.
44340     */
44341     for(u=0; u<nRec; u++){
44342       if( needPagerReset ){
44343         pager_reset(pPager);
44344         needPagerReset = 0;
44345       }
44346       rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
44347       if( rc==SQLITE_OK ){
44348         nPlayback++;
44349       }else{
44350         if( rc==SQLITE_DONE ){
44351           pPager->journalOff = szJ;
44352           break;
44353         }else if( rc==SQLITE_IOERR_SHORT_READ ){
44354           /* If the journal has been truncated, simply stop reading and
44355           ** processing the journal. This might happen if the journal was
44356           ** not completely written and synced prior to a crash.  In that
44357           ** case, the database should have never been written in the
44358           ** first place so it is OK to simply abandon the rollback. */
44359           rc = SQLITE_OK;
44360           goto end_playback;
44361         }else{
44362           /* If we are unable to rollback, quit and return the error
44363           ** code.  This will cause the pager to enter the error state
44364           ** so that no further harm will be done.  Perhaps the next
44365           ** process to come along will be able to rollback the database.
44366           */
44367           goto end_playback;
44368         }
44369       }
44370     }
44371   }
44372   /*NOTREACHED*/
44373   assert( 0 );
44374
44375 end_playback:
44376   /* Following a rollback, the database file should be back in its original
44377   ** state prior to the start of the transaction, so invoke the
44378   ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
44379   ** assertion that the transaction counter was modified.
44380   */
44381 #ifdef SQLITE_DEBUG
44382   if( pPager->fd->pMethods ){
44383     sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
44384   }
44385 #endif
44386
44387   /* If this playback is happening automatically as a result of an IO or 
44388   ** malloc error that occurred after the change-counter was updated but 
44389   ** before the transaction was committed, then the change-counter 
44390   ** modification may just have been reverted. If this happens in exclusive 
44391   ** mode, then subsequent transactions performed by the connection will not
44392   ** update the change-counter at all. This may lead to cache inconsistency
44393   ** problems for other processes at some point in the future. So, just
44394   ** in case this has happened, clear the changeCountDone flag now.
44395   */
44396   pPager->changeCountDone = pPager->tempFile;
44397
44398   if( rc==SQLITE_OK ){
44399     zMaster = pPager->pTmpSpace;
44400     rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
44401     testcase( rc!=SQLITE_OK );
44402   }
44403   if( rc==SQLITE_OK
44404    && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
44405   ){
44406     rc = sqlite3PagerSync(pPager, 0);
44407   }
44408   if( rc==SQLITE_OK ){
44409     rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
44410     testcase( rc!=SQLITE_OK );
44411   }
44412   if( rc==SQLITE_OK && zMaster[0] && res ){
44413     /* If there was a master journal and this routine will return success,
44414     ** see if it is possible to delete the master journal.
44415     */
44416     rc = pager_delmaster(pPager, zMaster);
44417     testcase( rc!=SQLITE_OK );
44418   }
44419   if( isHot && nPlayback ){
44420     sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
44421                 nPlayback, pPager->zJournal);
44422   }
44423
44424   /* The Pager.sectorSize variable may have been updated while rolling
44425   ** back a journal created by a process with a different sector size
44426   ** value. Reset it to the correct value for this process.
44427   */
44428   setSectorSize(pPager);
44429   return rc;
44430 }
44431
44432
44433 /*
44434 ** Read the content for page pPg out of the database file and into 
44435 ** pPg->pData. A shared lock or greater must be held on the database
44436 ** file before this function is called.
44437 **
44438 ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
44439 ** the value read from the database file.
44440 **
44441 ** If an IO error occurs, then the IO error is returned to the caller.
44442 ** Otherwise, SQLITE_OK is returned.
44443 */
44444 static int readDbPage(PgHdr *pPg, u32 iFrame){
44445   Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
44446   Pgno pgno = pPg->pgno;       /* Page number to read */
44447   int rc = SQLITE_OK;          /* Return code */
44448   int pgsz = pPager->pageSize; /* Number of bytes to read */
44449
44450   assert( pPager->eState>=PAGER_READER && !MEMDB );
44451   assert( isOpen(pPager->fd) );
44452
44453 #ifndef SQLITE_OMIT_WAL
44454   if( iFrame ){
44455     /* Try to pull the page from the write-ahead log. */
44456     rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
44457   }else
44458 #endif
44459   {
44460     i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
44461     rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
44462     if( rc==SQLITE_IOERR_SHORT_READ ){
44463       rc = SQLITE_OK;
44464     }
44465   }
44466
44467   if( pgno==1 ){
44468     if( rc ){
44469       /* If the read is unsuccessful, set the dbFileVers[] to something
44470       ** that will never be a valid file version.  dbFileVers[] is a copy
44471       ** of bytes 24..39 of the database.  Bytes 28..31 should always be
44472       ** zero or the size of the database in page. Bytes 32..35 and 35..39
44473       ** should be page numbers which are never 0xffffffff.  So filling
44474       ** pPager->dbFileVers[] with all 0xff bytes should suffice.
44475       **
44476       ** For an encrypted database, the situation is more complex:  bytes
44477       ** 24..39 of the database are white noise.  But the probability of
44478       ** white noise equaling 16 bytes of 0xff is vanishingly small so
44479       ** we should still be ok.
44480       */
44481       memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
44482     }else{
44483       u8 *dbFileVers = &((u8*)pPg->pData)[24];
44484       memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
44485     }
44486   }
44487   CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
44488
44489   PAGER_INCR(sqlite3_pager_readdb_count);
44490   PAGER_INCR(pPager->nRead);
44491   IOTRACE(("PGIN %p %d\n", pPager, pgno));
44492   PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
44493                PAGERID(pPager), pgno, pager_pagehash(pPg)));
44494
44495   return rc;
44496 }
44497
44498 /*
44499 ** Update the value of the change-counter at offsets 24 and 92 in
44500 ** the header and the sqlite version number at offset 96.
44501 **
44502 ** This is an unconditional update.  See also the pager_incr_changecounter()
44503 ** routine which only updates the change-counter if the update is actually
44504 ** needed, as determined by the pPager->changeCountDone state variable.
44505 */
44506 static void pager_write_changecounter(PgHdr *pPg){
44507   u32 change_counter;
44508
44509   /* Increment the value just read and write it back to byte 24. */
44510   change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
44511   put32bits(((char*)pPg->pData)+24, change_counter);
44512
44513   /* Also store the SQLite version number in bytes 96..99 and in
44514   ** bytes 92..95 store the change counter for which the version number
44515   ** is valid. */
44516   put32bits(((char*)pPg->pData)+92, change_counter);
44517   put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
44518 }
44519
44520 #ifndef SQLITE_OMIT_WAL
44521 /*
44522 ** This function is invoked once for each page that has already been 
44523 ** written into the log file when a WAL transaction is rolled back.
44524 ** Parameter iPg is the page number of said page. The pCtx argument 
44525 ** is actually a pointer to the Pager structure.
44526 **
44527 ** If page iPg is present in the cache, and has no outstanding references,
44528 ** it is discarded. Otherwise, if there are one or more outstanding
44529 ** references, the page content is reloaded from the database. If the
44530 ** attempt to reload content from the database is required and fails, 
44531 ** return an SQLite error code. Otherwise, SQLITE_OK.
44532 */
44533 static int pagerUndoCallback(void *pCtx, Pgno iPg){
44534   int rc = SQLITE_OK;
44535   Pager *pPager = (Pager *)pCtx;
44536   PgHdr *pPg;
44537
44538   assert( pagerUseWal(pPager) );
44539   pPg = sqlite3PagerLookup(pPager, iPg);
44540   if( pPg ){
44541     if( sqlite3PcachePageRefcount(pPg)==1 ){
44542       sqlite3PcacheDrop(pPg);
44543     }else{
44544       u32 iFrame = 0;
44545       rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
44546       if( rc==SQLITE_OK ){
44547         rc = readDbPage(pPg, iFrame);
44548       }
44549       if( rc==SQLITE_OK ){
44550         pPager->xReiniter(pPg);
44551       }
44552       sqlite3PagerUnrefNotNull(pPg);
44553     }
44554   }
44555
44556   /* Normally, if a transaction is rolled back, any backup processes are
44557   ** updated as data is copied out of the rollback journal and into the
44558   ** database. This is not generally possible with a WAL database, as
44559   ** rollback involves simply truncating the log file. Therefore, if one
44560   ** or more frames have already been written to the log (and therefore 
44561   ** also copied into the backup databases) as part of this transaction,
44562   ** the backups must be restarted.
44563   */
44564   sqlite3BackupRestart(pPager->pBackup);
44565
44566   return rc;
44567 }
44568
44569 /*
44570 ** This function is called to rollback a transaction on a WAL database.
44571 */
44572 static int pagerRollbackWal(Pager *pPager){
44573   int rc;                         /* Return Code */
44574   PgHdr *pList;                   /* List of dirty pages to revert */
44575
44576   /* For all pages in the cache that are currently dirty or have already
44577   ** been written (but not committed) to the log file, do one of the 
44578   ** following:
44579   **
44580   **   + Discard the cached page (if refcount==0), or
44581   **   + Reload page content from the database (if refcount>0).
44582   */
44583   pPager->dbSize = pPager->dbOrigSize;
44584   rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
44585   pList = sqlite3PcacheDirtyList(pPager->pPCache);
44586   while( pList && rc==SQLITE_OK ){
44587     PgHdr *pNext = pList->pDirty;
44588     rc = pagerUndoCallback((void *)pPager, pList->pgno);
44589     pList = pNext;
44590   }
44591
44592   return rc;
44593 }
44594
44595 /*
44596 ** This function is a wrapper around sqlite3WalFrames(). As well as logging
44597 ** the contents of the list of pages headed by pList (connected by pDirty),
44598 ** this function notifies any active backup processes that the pages have
44599 ** changed. 
44600 **
44601 ** The list of pages passed into this routine is always sorted by page number.
44602 ** Hence, if page 1 appears anywhere on the list, it will be the first page.
44603 */ 
44604 static int pagerWalFrames(
44605   Pager *pPager,                  /* Pager object */
44606   PgHdr *pList,                   /* List of frames to log */
44607   Pgno nTruncate,                 /* Database size after this commit */
44608   int isCommit                    /* True if this is a commit */
44609 ){
44610   int rc;                         /* Return code */
44611   int nList;                      /* Number of pages in pList */
44612 #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
44613   PgHdr *p;                       /* For looping over pages */
44614 #endif
44615
44616   assert( pPager->pWal );
44617   assert( pList );
44618 #ifdef SQLITE_DEBUG
44619   /* Verify that the page list is in accending order */
44620   for(p=pList; p && p->pDirty; p=p->pDirty){
44621     assert( p->pgno < p->pDirty->pgno );
44622   }
44623 #endif
44624
44625   assert( pList->pDirty==0 || isCommit );
44626   if( isCommit ){
44627     /* If a WAL transaction is being committed, there is no point in writing
44628     ** any pages with page numbers greater than nTruncate into the WAL file.
44629     ** They will never be read by any client. So remove them from the pDirty
44630     ** list here. */
44631     PgHdr *p;
44632     PgHdr **ppNext = &pList;
44633     nList = 0;
44634     for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
44635       if( p->pgno<=nTruncate ){
44636         ppNext = &p->pDirty;
44637         nList++;
44638       }
44639     }
44640     assert( pList );
44641   }else{
44642     nList = 1;
44643   }
44644   pPager->aStat[PAGER_STAT_WRITE] += nList;
44645
44646   if( pList->pgno==1 ) pager_write_changecounter(pList);
44647   rc = sqlite3WalFrames(pPager->pWal, 
44648       pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
44649   );
44650   if( rc==SQLITE_OK && pPager->pBackup ){
44651     PgHdr *p;
44652     for(p=pList; p; p=p->pDirty){
44653       sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
44654     }
44655   }
44656
44657 #ifdef SQLITE_CHECK_PAGES
44658   pList = sqlite3PcacheDirtyList(pPager->pPCache);
44659   for(p=pList; p; p=p->pDirty){
44660     pager_set_pagehash(p);
44661   }
44662 #endif
44663
44664   return rc;
44665 }
44666
44667 /*
44668 ** Begin a read transaction on the WAL.
44669 **
44670 ** This routine used to be called "pagerOpenSnapshot()" because it essentially
44671 ** makes a snapshot of the database at the current point in time and preserves
44672 ** that snapshot for use by the reader in spite of concurrently changes by
44673 ** other writers or checkpointers.
44674 */
44675 static int pagerBeginReadTransaction(Pager *pPager){
44676   int rc;                         /* Return code */
44677   int changed = 0;                /* True if cache must be reset */
44678
44679   assert( pagerUseWal(pPager) );
44680   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
44681
44682   /* sqlite3WalEndReadTransaction() was not called for the previous
44683   ** transaction in locking_mode=EXCLUSIVE.  So call it now.  If we
44684   ** are in locking_mode=NORMAL and EndRead() was previously called,
44685   ** the duplicate call is harmless.
44686   */
44687   sqlite3WalEndReadTransaction(pPager->pWal);
44688
44689   rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
44690   if( rc!=SQLITE_OK || changed ){
44691     pager_reset(pPager);
44692     if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
44693   }
44694
44695   return rc;
44696 }
44697 #endif
44698
44699 /*
44700 ** This function is called as part of the transition from PAGER_OPEN
44701 ** to PAGER_READER state to determine the size of the database file
44702 ** in pages (assuming the page size currently stored in Pager.pageSize).
44703 **
44704 ** If no error occurs, SQLITE_OK is returned and the size of the database
44705 ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
44706 ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
44707 */
44708 static int pagerPagecount(Pager *pPager, Pgno *pnPage){
44709   Pgno nPage;                     /* Value to return via *pnPage */
44710
44711   /* Query the WAL sub-system for the database size. The WalDbsize()
44712   ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
44713   ** if the database size is not available. The database size is not
44714   ** available from the WAL sub-system if the log file is empty or
44715   ** contains no valid committed transactions.
44716   */
44717   assert( pPager->eState==PAGER_OPEN );
44718   assert( pPager->eLock>=SHARED_LOCK );
44719   nPage = sqlite3WalDbsize(pPager->pWal);
44720
44721   /* If the database size was not available from the WAL sub-system,
44722   ** determine it based on the size of the database file. If the size
44723   ** of the database file is not an integer multiple of the page-size,
44724   ** round down to the nearest page. Except, any file larger than 0
44725   ** bytes in size is considered to contain at least one page.
44726   */
44727   if( nPage==0 ){
44728     i64 n = 0;                    /* Size of db file in bytes */
44729     assert( isOpen(pPager->fd) || pPager->tempFile );
44730     if( isOpen(pPager->fd) ){
44731       int rc = sqlite3OsFileSize(pPager->fd, &n);
44732       if( rc!=SQLITE_OK ){
44733         return rc;
44734       }
44735     }
44736     nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
44737   }
44738
44739   /* If the current number of pages in the file is greater than the
44740   ** configured maximum pager number, increase the allowed limit so
44741   ** that the file can be read.
44742   */
44743   if( nPage>pPager->mxPgno ){
44744     pPager->mxPgno = (Pgno)nPage;
44745   }
44746
44747   *pnPage = nPage;
44748   return SQLITE_OK;
44749 }
44750
44751 #ifndef SQLITE_OMIT_WAL
44752 /*
44753 ** Check if the *-wal file that corresponds to the database opened by pPager
44754 ** exists if the database is not empy, or verify that the *-wal file does
44755 ** not exist (by deleting it) if the database file is empty.
44756 **
44757 ** If the database is not empty and the *-wal file exists, open the pager
44758 ** in WAL mode.  If the database is empty or if no *-wal file exists and
44759 ** if no error occurs, make sure Pager.journalMode is not set to
44760 ** PAGER_JOURNALMODE_WAL.
44761 **
44762 ** Return SQLITE_OK or an error code.
44763 **
44764 ** The caller must hold a SHARED lock on the database file to call this
44765 ** function. Because an EXCLUSIVE lock on the db file is required to delete 
44766 ** a WAL on a none-empty database, this ensures there is no race condition 
44767 ** between the xAccess() below and an xDelete() being executed by some 
44768 ** other connection.
44769 */
44770 static int pagerOpenWalIfPresent(Pager *pPager){
44771   int rc = SQLITE_OK;
44772   assert( pPager->eState==PAGER_OPEN );
44773   assert( pPager->eLock>=SHARED_LOCK );
44774
44775   if( !pPager->tempFile ){
44776     int isWal;                    /* True if WAL file exists */
44777     Pgno nPage;                   /* Size of the database file */
44778
44779     rc = pagerPagecount(pPager, &nPage);
44780     if( rc ) return rc;
44781     if( nPage==0 ){
44782       rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
44783       if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
44784       isWal = 0;
44785     }else{
44786       rc = sqlite3OsAccess(
44787           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
44788       );
44789     }
44790     if( rc==SQLITE_OK ){
44791       if( isWal ){
44792         testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
44793         rc = sqlite3PagerOpenWal(pPager, 0);
44794       }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
44795         pPager->journalMode = PAGER_JOURNALMODE_DELETE;
44796       }
44797     }
44798   }
44799   return rc;
44800 }
44801 #endif
44802
44803 /*
44804 ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
44805 ** the entire master journal file. The case pSavepoint==NULL occurs when 
44806 ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction 
44807 ** savepoint.
44808 **
44809 ** When pSavepoint is not NULL (meaning a non-transaction savepoint is 
44810 ** being rolled back), then the rollback consists of up to three stages,
44811 ** performed in the order specified:
44812 **
44813 **   * Pages are played back from the main journal starting at byte
44814 **     offset PagerSavepoint.iOffset and continuing to 
44815 **     PagerSavepoint.iHdrOffset, or to the end of the main journal
44816 **     file if PagerSavepoint.iHdrOffset is zero.
44817 **
44818 **   * If PagerSavepoint.iHdrOffset is not zero, then pages are played
44819 **     back starting from the journal header immediately following 
44820 **     PagerSavepoint.iHdrOffset to the end of the main journal file.
44821 **
44822 **   * Pages are then played back from the sub-journal file, starting
44823 **     with the PagerSavepoint.iSubRec and continuing to the end of
44824 **     the journal file.
44825 **
44826 ** Throughout the rollback process, each time a page is rolled back, the
44827 ** corresponding bit is set in a bitvec structure (variable pDone in the
44828 ** implementation below). This is used to ensure that a page is only
44829 ** rolled back the first time it is encountered in either journal.
44830 **
44831 ** If pSavepoint is NULL, then pages are only played back from the main
44832 ** journal file. There is no need for a bitvec in this case.
44833 **
44834 ** In either case, before playback commences the Pager.dbSize variable
44835 ** is reset to the value that it held at the start of the savepoint 
44836 ** (or transaction). No page with a page-number greater than this value
44837 ** is played back. If one is encountered it is simply skipped.
44838 */
44839 static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
44840   i64 szJ;                 /* Effective size of the main journal */
44841   i64 iHdrOff;             /* End of first segment of main-journal records */
44842   int rc = SQLITE_OK;      /* Return code */
44843   Bitvec *pDone = 0;       /* Bitvec to ensure pages played back only once */
44844
44845   assert( pPager->eState!=PAGER_ERROR );
44846   assert( pPager->eState>=PAGER_WRITER_LOCKED );
44847
44848   /* Allocate a bitvec to use to store the set of pages rolled back */
44849   if( pSavepoint ){
44850     pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
44851     if( !pDone ){
44852       return SQLITE_NOMEM;
44853     }
44854   }
44855
44856   /* Set the database size back to the value it was before the savepoint 
44857   ** being reverted was opened.
44858   */
44859   pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
44860   pPager->changeCountDone = pPager->tempFile;
44861
44862   if( !pSavepoint && pagerUseWal(pPager) ){
44863     return pagerRollbackWal(pPager);
44864   }
44865
44866   /* Use pPager->journalOff as the effective size of the main rollback
44867   ** journal.  The actual file might be larger than this in
44868   ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST.  But anything
44869   ** past pPager->journalOff is off-limits to us.
44870   */
44871   szJ = pPager->journalOff;
44872   assert( pagerUseWal(pPager)==0 || szJ==0 );
44873
44874   /* Begin by rolling back records from the main journal starting at
44875   ** PagerSavepoint.iOffset and continuing to the next journal header.
44876   ** There might be records in the main journal that have a page number
44877   ** greater than the current database size (pPager->dbSize) but those
44878   ** will be skipped automatically.  Pages are added to pDone as they
44879   ** are played back.
44880   */
44881   if( pSavepoint && !pagerUseWal(pPager) ){
44882     iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
44883     pPager->journalOff = pSavepoint->iOffset;
44884     while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
44885       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
44886     }
44887     assert( rc!=SQLITE_DONE );
44888   }else{
44889     pPager->journalOff = 0;
44890   }
44891
44892   /* Continue rolling back records out of the main journal starting at
44893   ** the first journal header seen and continuing until the effective end
44894   ** of the main journal file.  Continue to skip out-of-range pages and
44895   ** continue adding pages rolled back to pDone.
44896   */
44897   while( rc==SQLITE_OK && pPager->journalOff<szJ ){
44898     u32 ii;            /* Loop counter */
44899     u32 nJRec = 0;     /* Number of Journal Records */
44900     u32 dummy;
44901     rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
44902     assert( rc!=SQLITE_DONE );
44903
44904     /*
44905     ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
44906     ** test is related to ticket #2565.  See the discussion in the
44907     ** pager_playback() function for additional information.
44908     */
44909     if( nJRec==0 
44910      && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
44911     ){
44912       nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
44913     }
44914     for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
44915       rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
44916     }
44917     assert( rc!=SQLITE_DONE );
44918   }
44919   assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
44920
44921   /* Finally,  rollback pages from the sub-journal.  Page that were
44922   ** previously rolled back out of the main journal (and are hence in pDone)
44923   ** will be skipped.  Out-of-range pages are also skipped.
44924   */
44925   if( pSavepoint ){
44926     u32 ii;            /* Loop counter */
44927     i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
44928
44929     if( pagerUseWal(pPager) ){
44930       rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
44931     }
44932     for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
44933       assert( offset==(i64)ii*(4+pPager->pageSize) );
44934       rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
44935     }
44936     assert( rc!=SQLITE_DONE );
44937   }
44938
44939   sqlite3BitvecDestroy(pDone);
44940   if( rc==SQLITE_OK ){
44941     pPager->journalOff = szJ;
44942   }
44943
44944   return rc;
44945 }
44946
44947 /*
44948 ** Change the maximum number of in-memory pages that are allowed.
44949 */
44950 SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
44951   sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
44952 }
44953
44954 /*
44955 ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
44956 */
44957 static void pagerFixMaplimit(Pager *pPager){
44958 #if SQLITE_MAX_MMAP_SIZE>0
44959   sqlite3_file *fd = pPager->fd;
44960   if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
44961     sqlite3_int64 sz;
44962     sz = pPager->szMmap;
44963     pPager->bUseFetch = (sz>0);
44964     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
44965   }
44966 #endif
44967 }
44968
44969 /*
44970 ** Change the maximum size of any memory mapping made of the database file.
44971 */
44972 SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
44973   pPager->szMmap = szMmap;
44974   pagerFixMaplimit(pPager);
44975 }
44976
44977 /*
44978 ** Free as much memory as possible from the pager.
44979 */
44980 SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
44981   sqlite3PcacheShrink(pPager->pPCache);
44982 }
44983
44984 /*
44985 ** Adjust settings of the pager to those specified in the pgFlags parameter.
44986 **
44987 ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
44988 ** of the database to damage due to OS crashes or power failures by
44989 ** changing the number of syncs()s when writing the journals.
44990 ** There are three levels:
44991 **
44992 **    OFF       sqlite3OsSync() is never called.  This is the default
44993 **              for temporary and transient files.
44994 **
44995 **    NORMAL    The journal is synced once before writes begin on the
44996 **              database.  This is normally adequate protection, but
44997 **              it is theoretically possible, though very unlikely,
44998 **              that an inopertune power failure could leave the journal
44999 **              in a state which would cause damage to the database
45000 **              when it is rolled back.
45001 **
45002 **    FULL      The journal is synced twice before writes begin on the
45003 **              database (with some additional information - the nRec field
45004 **              of the journal header - being written in between the two
45005 **              syncs).  If we assume that writing a
45006 **              single disk sector is atomic, then this mode provides
45007 **              assurance that the journal will not be corrupted to the
45008 **              point of causing damage to the database during rollback.
45009 **
45010 ** The above is for a rollback-journal mode.  For WAL mode, OFF continues
45011 ** to mean that no syncs ever occur.  NORMAL means that the WAL is synced
45012 ** prior to the start of checkpoint and that the database file is synced
45013 ** at the conclusion of the checkpoint if the entire content of the WAL
45014 ** was written back into the database.  But no sync operations occur for
45015 ** an ordinary commit in NORMAL mode with WAL.  FULL means that the WAL
45016 ** file is synced following each commit operation, in addition to the
45017 ** syncs associated with NORMAL.
45018 **
45019 ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL.  The
45020 ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
45021 ** using fcntl(F_FULLFSYNC).  SQLITE_SYNC_NORMAL means to do an
45022 ** ordinary fsync() call.  There is no difference between SQLITE_SYNC_FULL
45023 ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX.  But the
45024 ** synchronous=FULL versus synchronous=NORMAL setting determines when
45025 ** the xSync primitive is called and is relevant to all platforms.
45026 **
45027 ** Numeric values associated with these states are OFF==1, NORMAL=2,
45028 ** and FULL=3.
45029 */
45030 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
45031 SQLITE_PRIVATE void sqlite3PagerSetFlags(
45032   Pager *pPager,        /* The pager to set safety level for */
45033   unsigned pgFlags      /* Various flags */
45034 ){
45035   unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
45036   assert( level>=1 && level<=3 );
45037   pPager->noSync =  (level==1 || pPager->tempFile) ?1:0;
45038   pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
45039   if( pPager->noSync ){
45040     pPager->syncFlags = 0;
45041     pPager->ckptSyncFlags = 0;
45042   }else if( pgFlags & PAGER_FULLFSYNC ){
45043     pPager->syncFlags = SQLITE_SYNC_FULL;
45044     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
45045   }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
45046     pPager->syncFlags = SQLITE_SYNC_NORMAL;
45047     pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
45048   }else{
45049     pPager->syncFlags = SQLITE_SYNC_NORMAL;
45050     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
45051   }
45052   pPager->walSyncFlags = pPager->syncFlags;
45053   if( pPager->fullSync ){
45054     pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
45055   }
45056   if( pgFlags & PAGER_CACHESPILL ){
45057     pPager->doNotSpill &= ~SPILLFLAG_OFF;
45058   }else{
45059     pPager->doNotSpill |= SPILLFLAG_OFF;
45060   }
45061 }
45062 #endif
45063
45064 /*
45065 ** The following global variable is incremented whenever the library
45066 ** attempts to open a temporary file.  This information is used for
45067 ** testing and analysis only.  
45068 */
45069 #ifdef SQLITE_TEST
45070 SQLITE_API int sqlite3_opentemp_count = 0;
45071 #endif
45072
45073 /*
45074 ** Open a temporary file.
45075 **
45076 ** Write the file descriptor into *pFile. Return SQLITE_OK on success 
45077 ** or some other error code if we fail. The OS will automatically 
45078 ** delete the temporary file when it is closed.
45079 **
45080 ** The flags passed to the VFS layer xOpen() call are those specified
45081 ** by parameter vfsFlags ORed with the following:
45082 **
45083 **     SQLITE_OPEN_READWRITE
45084 **     SQLITE_OPEN_CREATE
45085 **     SQLITE_OPEN_EXCLUSIVE
45086 **     SQLITE_OPEN_DELETEONCLOSE
45087 */
45088 static int pagerOpentemp(
45089   Pager *pPager,        /* The pager object */
45090   sqlite3_file *pFile,  /* Write the file descriptor here */
45091   int vfsFlags          /* Flags passed through to the VFS */
45092 ){
45093   int rc;               /* Return code */
45094
45095 #ifdef SQLITE_TEST
45096   sqlite3_opentemp_count++;  /* Used for testing and analysis only */
45097 #endif
45098
45099   vfsFlags |=  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
45100             SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
45101   rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
45102   assert( rc!=SQLITE_OK || isOpen(pFile) );
45103   return rc;
45104 }
45105
45106 /*
45107 ** Set the busy handler function.
45108 **
45109 ** The pager invokes the busy-handler if sqlite3OsLock() returns 
45110 ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
45111 ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE 
45112 ** lock. It does *not* invoke the busy handler when upgrading from
45113 ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
45114 ** (which occurs during hot-journal rollback). Summary:
45115 **
45116 **   Transition                        | Invokes xBusyHandler
45117 **   --------------------------------------------------------
45118 **   NO_LOCK       -> SHARED_LOCK      | Yes
45119 **   SHARED_LOCK   -> RESERVED_LOCK    | No
45120 **   SHARED_LOCK   -> EXCLUSIVE_LOCK   | No
45121 **   RESERVED_LOCK -> EXCLUSIVE_LOCK   | Yes
45122 **
45123 ** If the busy-handler callback returns non-zero, the lock is 
45124 ** retried. If it returns zero, then the SQLITE_BUSY error is
45125 ** returned to the caller of the pager API function.
45126 */
45127 SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
45128   Pager *pPager,                       /* Pager object */
45129   int (*xBusyHandler)(void *),         /* Pointer to busy-handler function */
45130   void *pBusyHandlerArg                /* Argument to pass to xBusyHandler */
45131 ){
45132   pPager->xBusyHandler = xBusyHandler;
45133   pPager->pBusyHandlerArg = pBusyHandlerArg;
45134
45135   if( isOpen(pPager->fd) ){
45136     void **ap = (void **)&pPager->xBusyHandler;
45137     assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
45138     assert( ap[1]==pBusyHandlerArg );
45139     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
45140   }
45141 }
45142
45143 /*
45144 ** Change the page size used by the Pager object. The new page size 
45145 ** is passed in *pPageSize.
45146 **
45147 ** If the pager is in the error state when this function is called, it
45148 ** is a no-op. The value returned is the error state error code (i.e. 
45149 ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
45150 **
45151 ** Otherwise, if all of the following are true:
45152 **
45153 **   * the new page size (value of *pPageSize) is valid (a power 
45154 **     of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
45155 **
45156 **   * there are no outstanding page references, and
45157 **
45158 **   * the database is either not an in-memory database or it is
45159 **     an in-memory database that currently consists of zero pages.
45160 **
45161 ** then the pager object page size is set to *pPageSize.
45162 **
45163 ** If the page size is changed, then this function uses sqlite3PagerMalloc() 
45164 ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt 
45165 ** fails, SQLITE_NOMEM is returned and the page size remains unchanged. 
45166 ** In all other cases, SQLITE_OK is returned.
45167 **
45168 ** If the page size is not changed, either because one of the enumerated
45169 ** conditions above is not true, the pager was in error state when this
45170 ** function was called, or because the memory allocation attempt failed, 
45171 ** then *pPageSize is set to the old, retained page size before returning.
45172 */
45173 SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
45174   int rc = SQLITE_OK;
45175
45176   /* It is not possible to do a full assert_pager_state() here, as this
45177   ** function may be called from within PagerOpen(), before the state
45178   ** of the Pager object is internally consistent.
45179   **
45180   ** At one point this function returned an error if the pager was in 
45181   ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
45182   ** there is at least one outstanding page reference, this function
45183   ** is a no-op for that case anyhow.
45184   */
45185
45186   u32 pageSize = *pPageSize;
45187   assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
45188   if( (pPager->memDb==0 || pPager->dbSize==0)
45189    && sqlite3PcacheRefCount(pPager->pPCache)==0 
45190    && pageSize && pageSize!=(u32)pPager->pageSize 
45191   ){
45192     char *pNew = NULL;             /* New temp space */
45193     i64 nByte = 0;
45194
45195     if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
45196       rc = sqlite3OsFileSize(pPager->fd, &nByte);
45197     }
45198     if( rc==SQLITE_OK ){
45199       pNew = (char *)sqlite3PageMalloc(pageSize);
45200       if( !pNew ) rc = SQLITE_NOMEM;
45201     }
45202
45203     if( rc==SQLITE_OK ){
45204       pager_reset(pPager);
45205       rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
45206     }
45207     if( rc==SQLITE_OK ){
45208       sqlite3PageFree(pPager->pTmpSpace);
45209       pPager->pTmpSpace = pNew;
45210       pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
45211       pPager->pageSize = pageSize;
45212     }else{
45213       sqlite3PageFree(pNew);
45214     }
45215   }
45216
45217   *pPageSize = pPager->pageSize;
45218   if( rc==SQLITE_OK ){
45219     if( nReserve<0 ) nReserve = pPager->nReserve;
45220     assert( nReserve>=0 && nReserve<1000 );
45221     pPager->nReserve = (i16)nReserve;
45222     pagerReportSize(pPager);
45223     pagerFixMaplimit(pPager);
45224   }
45225   return rc;
45226 }
45227
45228 /*
45229 ** Return a pointer to the "temporary page" buffer held internally
45230 ** by the pager.  This is a buffer that is big enough to hold the
45231 ** entire content of a database page.  This buffer is used internally
45232 ** during rollback and will be overwritten whenever a rollback
45233 ** occurs.  But other modules are free to use it too, as long as
45234 ** no rollbacks are happening.
45235 */
45236 SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
45237   return pPager->pTmpSpace;
45238 }
45239
45240 /*
45241 ** Attempt to set the maximum database page count if mxPage is positive. 
45242 ** Make no changes if mxPage is zero or negative.  And never reduce the
45243 ** maximum page count below the current size of the database.
45244 **
45245 ** Regardless of mxPage, return the current maximum page count.
45246 */
45247 SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
45248   if( mxPage>0 ){
45249     pPager->mxPgno = mxPage;
45250   }
45251   assert( pPager->eState!=PAGER_OPEN );      /* Called only by OP_MaxPgcnt */
45252   assert( pPager->mxPgno>=pPager->dbSize );  /* OP_MaxPgcnt enforces this */
45253   return pPager->mxPgno;
45254 }
45255
45256 /*
45257 ** The following set of routines are used to disable the simulated
45258 ** I/O error mechanism.  These routines are used to avoid simulated
45259 ** errors in places where we do not care about errors.
45260 **
45261 ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
45262 ** and generate no code.
45263 */
45264 #ifdef SQLITE_TEST
45265 SQLITE_API extern int sqlite3_io_error_pending;
45266 SQLITE_API extern int sqlite3_io_error_hit;
45267 static int saved_cnt;
45268 void disable_simulated_io_errors(void){
45269   saved_cnt = sqlite3_io_error_pending;
45270   sqlite3_io_error_pending = -1;
45271 }
45272 void enable_simulated_io_errors(void){
45273   sqlite3_io_error_pending = saved_cnt;
45274 }
45275 #else
45276 # define disable_simulated_io_errors()
45277 # define enable_simulated_io_errors()
45278 #endif
45279
45280 /*
45281 ** Read the first N bytes from the beginning of the file into memory
45282 ** that pDest points to. 
45283 **
45284 ** If the pager was opened on a transient file (zFilename==""), or
45285 ** opened on a file less than N bytes in size, the output buffer is
45286 ** zeroed and SQLITE_OK returned. The rationale for this is that this 
45287 ** function is used to read database headers, and a new transient or
45288 ** zero sized database has a header than consists entirely of zeroes.
45289 **
45290 ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
45291 ** the error code is returned to the caller and the contents of the
45292 ** output buffer undefined.
45293 */
45294 SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
45295   int rc = SQLITE_OK;
45296   memset(pDest, 0, N);
45297   assert( isOpen(pPager->fd) || pPager->tempFile );
45298
45299   /* This routine is only called by btree immediately after creating
45300   ** the Pager object.  There has not been an opportunity to transition
45301   ** to WAL mode yet.
45302   */
45303   assert( !pagerUseWal(pPager) );
45304
45305   if( isOpen(pPager->fd) ){
45306     IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
45307     rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
45308     if( rc==SQLITE_IOERR_SHORT_READ ){
45309       rc = SQLITE_OK;
45310     }
45311   }
45312   return rc;
45313 }
45314
45315 /*
45316 ** This function may only be called when a read-transaction is open on
45317 ** the pager. It returns the total number of pages in the database.
45318 **
45319 ** However, if the file is between 1 and <page-size> bytes in size, then 
45320 ** this is considered a 1 page file.
45321 */
45322 SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
45323   assert( pPager->eState>=PAGER_READER );
45324   assert( pPager->eState!=PAGER_WRITER_FINISHED );
45325   *pnPage = (int)pPager->dbSize;
45326 }
45327
45328
45329 /*
45330 ** Try to obtain a lock of type locktype on the database file. If
45331 ** a similar or greater lock is already held, this function is a no-op
45332 ** (returning SQLITE_OK immediately).
45333 **
45334 ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke 
45335 ** the busy callback if the lock is currently not available. Repeat 
45336 ** until the busy callback returns false or until the attempt to 
45337 ** obtain the lock succeeds.
45338 **
45339 ** Return SQLITE_OK on success and an error code if we cannot obtain
45340 ** the lock. If the lock is obtained successfully, set the Pager.state 
45341 ** variable to locktype before returning.
45342 */
45343 static int pager_wait_on_lock(Pager *pPager, int locktype){
45344   int rc;                              /* Return code */
45345
45346   /* Check that this is either a no-op (because the requested lock is 
45347   ** already held), or one of the transitions that the busy-handler
45348   ** may be invoked during, according to the comment above
45349   ** sqlite3PagerSetBusyhandler().
45350   */
45351   assert( (pPager->eLock>=locktype)
45352        || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
45353        || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
45354   );
45355
45356   do {
45357     rc = pagerLockDb(pPager, locktype);
45358   }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
45359   return rc;
45360 }
45361
45362 /*
45363 ** Function assertTruncateConstraint(pPager) checks that one of the 
45364 ** following is true for all dirty pages currently in the page-cache:
45365 **
45366 **   a) The page number is less than or equal to the size of the 
45367 **      current database image, in pages, OR
45368 **
45369 **   b) if the page content were written at this time, it would not
45370 **      be necessary to write the current content out to the sub-journal
45371 **      (as determined by function subjRequiresPage()).
45372 **
45373 ** If the condition asserted by this function were not true, and the
45374 ** dirty page were to be discarded from the cache via the pagerStress()
45375 ** routine, pagerStress() would not write the current page content to
45376 ** the database file. If a savepoint transaction were rolled back after
45377 ** this happened, the correct behavior would be to restore the current
45378 ** content of the page. However, since this content is not present in either
45379 ** the database file or the portion of the rollback journal and 
45380 ** sub-journal rolled back the content could not be restored and the
45381 ** database image would become corrupt. It is therefore fortunate that 
45382 ** this circumstance cannot arise.
45383 */
45384 #if defined(SQLITE_DEBUG)
45385 static void assertTruncateConstraintCb(PgHdr *pPg){
45386   assert( pPg->flags&PGHDR_DIRTY );
45387   assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
45388 }
45389 static void assertTruncateConstraint(Pager *pPager){
45390   sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
45391 }
45392 #else
45393 # define assertTruncateConstraint(pPager)
45394 #endif
45395
45396 /*
45397 ** Truncate the in-memory database file image to nPage pages. This 
45398 ** function does not actually modify the database file on disk. It 
45399 ** just sets the internal state of the pager object so that the 
45400 ** truncation will be done when the current transaction is committed.
45401 **
45402 ** This function is only called right before committing a transaction.
45403 ** Once this function has been called, the transaction must either be
45404 ** rolled back or committed. It is not safe to call this function and
45405 ** then continue writing to the database.
45406 */
45407 SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
45408   assert( pPager->dbSize>=nPage );
45409   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
45410   pPager->dbSize = nPage;
45411
45412   /* At one point the code here called assertTruncateConstraint() to
45413   ** ensure that all pages being truncated away by this operation are,
45414   ** if one or more savepoints are open, present in the savepoint 
45415   ** journal so that they can be restored if the savepoint is rolled
45416   ** back. This is no longer necessary as this function is now only
45417   ** called right before committing a transaction. So although the 
45418   ** Pager object may still have open savepoints (Pager.nSavepoint!=0), 
45419   ** they cannot be rolled back. So the assertTruncateConstraint() call
45420   ** is no longer correct. */
45421 }
45422
45423
45424 /*
45425 ** This function is called before attempting a hot-journal rollback. It
45426 ** syncs the journal file to disk, then sets pPager->journalHdr to the
45427 ** size of the journal file so that the pager_playback() routine knows
45428 ** that the entire journal file has been synced.
45429 **
45430 ** Syncing a hot-journal to disk before attempting to roll it back ensures 
45431 ** that if a power-failure occurs during the rollback, the process that
45432 ** attempts rollback following system recovery sees the same journal
45433 ** content as this process.
45434 **
45435 ** If everything goes as planned, SQLITE_OK is returned. Otherwise, 
45436 ** an SQLite error code.
45437 */
45438 static int pagerSyncHotJournal(Pager *pPager){
45439   int rc = SQLITE_OK;
45440   if( !pPager->noSync ){
45441     rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
45442   }
45443   if( rc==SQLITE_OK ){
45444     rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
45445   }
45446   return rc;
45447 }
45448
45449 /*
45450 ** Obtain a reference to a memory mapped page object for page number pgno. 
45451 ** The new object will use the pointer pData, obtained from xFetch().
45452 ** If successful, set *ppPage to point to the new page reference
45453 ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
45454 ** *ppPage to zero.
45455 **
45456 ** Page references obtained by calling this function should be released
45457 ** by calling pagerReleaseMapPage().
45458 */
45459 static int pagerAcquireMapPage(
45460   Pager *pPager,                  /* Pager object */
45461   Pgno pgno,                      /* Page number */
45462   void *pData,                    /* xFetch()'d data for this page */
45463   PgHdr **ppPage                  /* OUT: Acquired page object */
45464 ){
45465   PgHdr *p;                       /* Memory mapped page to return */
45466   
45467   if( pPager->pMmapFreelist ){
45468     *ppPage = p = pPager->pMmapFreelist;
45469     pPager->pMmapFreelist = p->pDirty;
45470     p->pDirty = 0;
45471     memset(p->pExtra, 0, pPager->nExtra);
45472   }else{
45473     *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
45474     if( p==0 ){
45475       sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
45476       return SQLITE_NOMEM;
45477     }
45478     p->pExtra = (void *)&p[1];
45479     p->flags = PGHDR_MMAP;
45480     p->nRef = 1;
45481     p->pPager = pPager;
45482   }
45483
45484   assert( p->pExtra==(void *)&p[1] );
45485   assert( p->pPage==0 );
45486   assert( p->flags==PGHDR_MMAP );
45487   assert( p->pPager==pPager );
45488   assert( p->nRef==1 );
45489
45490   p->pgno = pgno;
45491   p->pData = pData;
45492   pPager->nMmapOut++;
45493
45494   return SQLITE_OK;
45495 }
45496
45497 /*
45498 ** Release a reference to page pPg. pPg must have been returned by an 
45499 ** earlier call to pagerAcquireMapPage().
45500 */
45501 static void pagerReleaseMapPage(PgHdr *pPg){
45502   Pager *pPager = pPg->pPager;
45503   pPager->nMmapOut--;
45504   pPg->pDirty = pPager->pMmapFreelist;
45505   pPager->pMmapFreelist = pPg;
45506
45507   assert( pPager->fd->pMethods->iVersion>=3 );
45508   sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
45509 }
45510
45511 /*
45512 ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
45513 */
45514 static void pagerFreeMapHdrs(Pager *pPager){
45515   PgHdr *p;
45516   PgHdr *pNext;
45517   for(p=pPager->pMmapFreelist; p; p=pNext){
45518     pNext = p->pDirty;
45519     sqlite3_free(p);
45520   }
45521 }
45522
45523
45524 /*
45525 ** Shutdown the page cache.  Free all memory and close all files.
45526 **
45527 ** If a transaction was in progress when this routine is called, that
45528 ** transaction is rolled back.  All outstanding pages are invalidated
45529 ** and their memory is freed.  Any attempt to use a page associated
45530 ** with this page cache after this function returns will likely
45531 ** result in a coredump.
45532 **
45533 ** This function always succeeds. If a transaction is active an attempt
45534 ** is made to roll it back. If an error occurs during the rollback 
45535 ** a hot journal may be left in the filesystem but no error is returned
45536 ** to the caller.
45537 */
45538 SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
45539   u8 *pTmp = (u8 *)pPager->pTmpSpace;
45540
45541   assert( assert_pager_state(pPager) );
45542   disable_simulated_io_errors();
45543   sqlite3BeginBenignMalloc();
45544   pagerFreeMapHdrs(pPager);
45545   /* pPager->errCode = 0; */
45546   pPager->exclusiveMode = 0;
45547 #ifndef SQLITE_OMIT_WAL
45548   sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
45549   pPager->pWal = 0;
45550 #endif
45551   pager_reset(pPager);
45552   if( MEMDB ){
45553     pager_unlock(pPager);
45554   }else{
45555     /* If it is open, sync the journal file before calling UnlockAndRollback.
45556     ** If this is not done, then an unsynced portion of the open journal 
45557     ** file may be played back into the database. If a power failure occurs 
45558     ** while this is happening, the database could become corrupt.
45559     **
45560     ** If an error occurs while trying to sync the journal, shift the pager
45561     ** into the ERROR state. This causes UnlockAndRollback to unlock the
45562     ** database and close the journal file without attempting to roll it
45563     ** back or finalize it. The next database user will have to do hot-journal
45564     ** rollback before accessing the database file.
45565     */
45566     if( isOpen(pPager->jfd) ){
45567       pager_error(pPager, pagerSyncHotJournal(pPager));
45568     }
45569     pagerUnlockAndRollback(pPager);
45570   }
45571   sqlite3EndBenignMalloc();
45572   enable_simulated_io_errors();
45573   PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
45574   IOTRACE(("CLOSE %p\n", pPager))
45575   sqlite3OsClose(pPager->jfd);
45576   sqlite3OsClose(pPager->fd);
45577   sqlite3PageFree(pTmp);
45578   sqlite3PcacheClose(pPager->pPCache);
45579
45580 #ifdef SQLITE_HAS_CODEC
45581   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
45582 #endif
45583
45584   assert( !pPager->aSavepoint && !pPager->pInJournal );
45585   assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
45586
45587   sqlite3_free(pPager);
45588   return SQLITE_OK;
45589 }
45590
45591 #if !defined(NDEBUG) || defined(SQLITE_TEST)
45592 /*
45593 ** Return the page number for page pPg.
45594 */
45595 SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
45596   return pPg->pgno;
45597 }
45598 #endif
45599
45600 /*
45601 ** Increment the reference count for page pPg.
45602 */
45603 SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
45604   sqlite3PcacheRef(pPg);
45605 }
45606
45607 /*
45608 ** Sync the journal. In other words, make sure all the pages that have
45609 ** been written to the journal have actually reached the surface of the
45610 ** disk and can be restored in the event of a hot-journal rollback.
45611 **
45612 ** If the Pager.noSync flag is set, then this function is a no-op.
45613 ** Otherwise, the actions required depend on the journal-mode and the 
45614 ** device characteristics of the file-system, as follows:
45615 **
45616 **   * If the journal file is an in-memory journal file, no action need
45617 **     be taken.
45618 **
45619 **   * Otherwise, if the device does not support the SAFE_APPEND property,
45620 **     then the nRec field of the most recently written journal header
45621 **     is updated to contain the number of journal records that have
45622 **     been written following it. If the pager is operating in full-sync
45623 **     mode, then the journal file is synced before this field is updated.
45624 **
45625 **   * If the device does not support the SEQUENTIAL property, then 
45626 **     journal file is synced.
45627 **
45628 ** Or, in pseudo-code:
45629 **
45630 **   if( NOT <in-memory journal> ){
45631 **     if( NOT SAFE_APPEND ){
45632 **       if( <full-sync mode> ) xSync(<journal file>);
45633 **       <update nRec field>
45634 **     } 
45635 **     if( NOT SEQUENTIAL ) xSync(<journal file>);
45636 **   }
45637 **
45638 ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every 
45639 ** page currently held in memory before returning SQLITE_OK. If an IO
45640 ** error is encountered, then the IO error code is returned to the caller.
45641 */
45642 static int syncJournal(Pager *pPager, int newHdr){
45643   int rc;                         /* Return code */
45644
45645   assert( pPager->eState==PAGER_WRITER_CACHEMOD
45646        || pPager->eState==PAGER_WRITER_DBMOD
45647   );
45648   assert( assert_pager_state(pPager) );
45649   assert( !pagerUseWal(pPager) );
45650
45651   rc = sqlite3PagerExclusiveLock(pPager);
45652   if( rc!=SQLITE_OK ) return rc;
45653
45654   if( !pPager->noSync ){
45655     assert( !pPager->tempFile );
45656     if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
45657       const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
45658       assert( isOpen(pPager->jfd) );
45659
45660       if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
45661         /* This block deals with an obscure problem. If the last connection
45662         ** that wrote to this database was operating in persistent-journal
45663         ** mode, then the journal file may at this point actually be larger
45664         ** than Pager.journalOff bytes. If the next thing in the journal
45665         ** file happens to be a journal-header (written as part of the
45666         ** previous connection's transaction), and a crash or power-failure 
45667         ** occurs after nRec is updated but before this connection writes 
45668         ** anything else to the journal file (or commits/rolls back its 
45669         ** transaction), then SQLite may become confused when doing the 
45670         ** hot-journal rollback following recovery. It may roll back all
45671         ** of this connections data, then proceed to rolling back the old,
45672         ** out-of-date data that follows it. Database corruption.
45673         **
45674         ** To work around this, if the journal file does appear to contain
45675         ** a valid header following Pager.journalOff, then write a 0x00
45676         ** byte to the start of it to prevent it from being recognized.
45677         **
45678         ** Variable iNextHdrOffset is set to the offset at which this
45679         ** problematic header will occur, if it exists. aMagic is used 
45680         ** as a temporary buffer to inspect the first couple of bytes of
45681         ** the potential journal header.
45682         */
45683         i64 iNextHdrOffset;
45684         u8 aMagic[8];
45685         u8 zHeader[sizeof(aJournalMagic)+4];
45686
45687         memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
45688         put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
45689
45690         iNextHdrOffset = journalHdrOffset(pPager);
45691         rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
45692         if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
45693           static const u8 zerobyte = 0;
45694           rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
45695         }
45696         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
45697           return rc;
45698         }
45699
45700         /* Write the nRec value into the journal file header. If in
45701         ** full-synchronous mode, sync the journal first. This ensures that
45702         ** all data has really hit the disk before nRec is updated to mark
45703         ** it as a candidate for rollback.
45704         **
45705         ** This is not required if the persistent media supports the
45706         ** SAFE_APPEND property. Because in this case it is not possible 
45707         ** for garbage data to be appended to the file, the nRec field
45708         ** is populated with 0xFFFFFFFF when the journal header is written
45709         ** and never needs to be updated.
45710         */
45711         if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
45712           PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
45713           IOTRACE(("JSYNC %p\n", pPager))
45714           rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
45715           if( rc!=SQLITE_OK ) return rc;
45716         }
45717         IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
45718         rc = sqlite3OsWrite(
45719             pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
45720         );
45721         if( rc!=SQLITE_OK ) return rc;
45722       }
45723       if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
45724         PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
45725         IOTRACE(("JSYNC %p\n", pPager))
45726         rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags| 
45727           (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
45728         );
45729         if( rc!=SQLITE_OK ) return rc;
45730       }
45731
45732       pPager->journalHdr = pPager->journalOff;
45733       if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
45734         pPager->nRec = 0;
45735         rc = writeJournalHdr(pPager);
45736         if( rc!=SQLITE_OK ) return rc;
45737       }
45738     }else{
45739       pPager->journalHdr = pPager->journalOff;
45740     }
45741   }
45742
45743   /* Unless the pager is in noSync mode, the journal file was just 
45744   ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on 
45745   ** all pages.
45746   */
45747   sqlite3PcacheClearSyncFlags(pPager->pPCache);
45748   pPager->eState = PAGER_WRITER_DBMOD;
45749   assert( assert_pager_state(pPager) );
45750   return SQLITE_OK;
45751 }
45752
45753 /*
45754 ** The argument is the first in a linked list of dirty pages connected
45755 ** by the PgHdr.pDirty pointer. This function writes each one of the
45756 ** in-memory pages in the list to the database file. The argument may
45757 ** be NULL, representing an empty list. In this case this function is
45758 ** a no-op.
45759 **
45760 ** The pager must hold at least a RESERVED lock when this function
45761 ** is called. Before writing anything to the database file, this lock
45762 ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
45763 ** SQLITE_BUSY is returned and no data is written to the database file.
45764 ** 
45765 ** If the pager is a temp-file pager and the actual file-system file
45766 ** is not yet open, it is created and opened before any data is 
45767 ** written out.
45768 **
45769 ** Once the lock has been upgraded and, if necessary, the file opened,
45770 ** the pages are written out to the database file in list order. Writing
45771 ** a page is skipped if it meets either of the following criteria:
45772 **
45773 **   * The page number is greater than Pager.dbSize, or
45774 **   * The PGHDR_DONT_WRITE flag is set on the page.
45775 **
45776 ** If writing out a page causes the database file to grow, Pager.dbFileSize
45777 ** is updated accordingly. If page 1 is written out, then the value cached
45778 ** in Pager.dbFileVers[] is updated to match the new value stored in
45779 ** the database file.
45780 **
45781 ** If everything is successful, SQLITE_OK is returned. If an IO error 
45782 ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
45783 ** be obtained, SQLITE_BUSY is returned.
45784 */
45785 static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
45786   int rc = SQLITE_OK;                  /* Return code */
45787
45788   /* This function is only called for rollback pagers in WRITER_DBMOD state. */
45789   assert( !pagerUseWal(pPager) );
45790   assert( pPager->eState==PAGER_WRITER_DBMOD );
45791   assert( pPager->eLock==EXCLUSIVE_LOCK );
45792
45793   /* If the file is a temp-file has not yet been opened, open it now. It
45794   ** is not possible for rc to be other than SQLITE_OK if this branch
45795   ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
45796   */
45797   if( !isOpen(pPager->fd) ){
45798     assert( pPager->tempFile && rc==SQLITE_OK );
45799     rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
45800   }
45801
45802   /* Before the first write, give the VFS a hint of what the final
45803   ** file size will be.
45804   */
45805   assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
45806   if( rc==SQLITE_OK 
45807    && pPager->dbHintSize<pPager->dbSize
45808    && (pList->pDirty || pList->pgno>pPager->dbHintSize)
45809   ){
45810     sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
45811     sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
45812     pPager->dbHintSize = pPager->dbSize;
45813   }
45814
45815   while( rc==SQLITE_OK && pList ){
45816     Pgno pgno = pList->pgno;
45817
45818     /* If there are dirty pages in the page cache with page numbers greater
45819     ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
45820     ** make the file smaller (presumably by auto-vacuum code). Do not write
45821     ** any such pages to the file.
45822     **
45823     ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
45824     ** set (set by sqlite3PagerDontWrite()).
45825     */
45826     if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
45827       i64 offset = (pgno-1)*(i64)pPager->pageSize;   /* Offset to write */
45828       char *pData;                                   /* Data to write */    
45829
45830       assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
45831       if( pList->pgno==1 ) pager_write_changecounter(pList);
45832
45833       /* Encode the database */
45834       CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
45835
45836       /* Write out the page data. */
45837       rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
45838
45839       /* If page 1 was just written, update Pager.dbFileVers to match
45840       ** the value now stored in the database file. If writing this 
45841       ** page caused the database file to grow, update dbFileSize. 
45842       */
45843       if( pgno==1 ){
45844         memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
45845       }
45846       if( pgno>pPager->dbFileSize ){
45847         pPager->dbFileSize = pgno;
45848       }
45849       pPager->aStat[PAGER_STAT_WRITE]++;
45850
45851       /* Update any backup objects copying the contents of this pager. */
45852       sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
45853
45854       PAGERTRACE(("STORE %d page %d hash(%08x)\n",
45855                    PAGERID(pPager), pgno, pager_pagehash(pList)));
45856       IOTRACE(("PGOUT %p %d\n", pPager, pgno));
45857       PAGER_INCR(sqlite3_pager_writedb_count);
45858     }else{
45859       PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
45860     }
45861     pager_set_pagehash(pList);
45862     pList = pList->pDirty;
45863   }
45864
45865   return rc;
45866 }
45867
45868 /*
45869 ** Ensure that the sub-journal file is open. If it is already open, this 
45870 ** function is a no-op.
45871 **
45872 ** SQLITE_OK is returned if everything goes according to plan. An 
45873 ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen() 
45874 ** fails.
45875 */
45876 static int openSubJournal(Pager *pPager){
45877   int rc = SQLITE_OK;
45878   if( !isOpen(pPager->sjfd) ){
45879     if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
45880       sqlite3MemJournalOpen(pPager->sjfd);
45881     }else{
45882       rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
45883     }
45884   }
45885   return rc;
45886 }
45887
45888 /*
45889 ** Append a record of the current state of page pPg to the sub-journal. 
45890 ** It is the callers responsibility to use subjRequiresPage() to check 
45891 ** that it is really required before calling this function.
45892 **
45893 ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
45894 ** for all open savepoints before returning.
45895 **
45896 ** This function returns SQLITE_OK if everything is successful, an IO
45897 ** error code if the attempt to write to the sub-journal fails, or 
45898 ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
45899 ** bitvec.
45900 */
45901 static int subjournalPage(PgHdr *pPg){
45902   int rc = SQLITE_OK;
45903   Pager *pPager = pPg->pPager;
45904   if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
45905
45906     /* Open the sub-journal, if it has not already been opened */
45907     assert( pPager->useJournal );
45908     assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
45909     assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
45910     assert( pagerUseWal(pPager) 
45911          || pageInJournal(pPager, pPg) 
45912          || pPg->pgno>pPager->dbOrigSize 
45913     );
45914     rc = openSubJournal(pPager);
45915
45916     /* If the sub-journal was opened successfully (or was already open),
45917     ** write the journal record into the file.  */
45918     if( rc==SQLITE_OK ){
45919       void *pData = pPg->pData;
45920       i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
45921       char *pData2;
45922   
45923       CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
45924       PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
45925       rc = write32bits(pPager->sjfd, offset, pPg->pgno);
45926       if( rc==SQLITE_OK ){
45927         rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
45928       }
45929     }
45930   }
45931   if( rc==SQLITE_OK ){
45932     pPager->nSubRec++;
45933     assert( pPager->nSavepoint>0 );
45934     rc = addToSavepointBitvecs(pPager, pPg->pgno);
45935   }
45936   return rc;
45937 }
45938
45939 /*
45940 ** This function is called by the pcache layer when it has reached some
45941 ** soft memory limit. The first argument is a pointer to a Pager object
45942 ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
45943 ** database). The second argument is a reference to a page that is 
45944 ** currently dirty but has no outstanding references. The page
45945 ** is always associated with the Pager object passed as the first 
45946 ** argument.
45947 **
45948 ** The job of this function is to make pPg clean by writing its contents
45949 ** out to the database file, if possible. This may involve syncing the
45950 ** journal file. 
45951 **
45952 ** If successful, sqlite3PcacheMakeClean() is called on the page and
45953 ** SQLITE_OK returned. If an IO error occurs while trying to make the
45954 ** page clean, the IO error code is returned. If the page cannot be
45955 ** made clean for some other reason, but no error occurs, then SQLITE_OK
45956 ** is returned by sqlite3PcacheMakeClean() is not called.
45957 */
45958 static int pagerStress(void *p, PgHdr *pPg){
45959   Pager *pPager = (Pager *)p;
45960   int rc = SQLITE_OK;
45961
45962   assert( pPg->pPager==pPager );
45963   assert( pPg->flags&PGHDR_DIRTY );
45964
45965   /* The doNotSpill NOSYNC bit is set during times when doing a sync of
45966   ** journal (and adding a new header) is not allowed.  This occurs
45967   ** during calls to sqlite3PagerWrite() while trying to journal multiple
45968   ** pages belonging to the same sector.
45969   **
45970   ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
45971   ** regardless of whether or not a sync is required.  This is set during
45972   ** a rollback or by user request, respectively.
45973   **
45974   ** Spilling is also prohibited when in an error state since that could
45975   ** lead to database corruption.   In the current implementation it 
45976   ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
45977   ** while in the error state, hence it is impossible for this routine to
45978   ** be called in the error state.  Nevertheless, we include a NEVER()
45979   ** test for the error state as a safeguard against future changes.
45980   */
45981   if( NEVER(pPager->errCode) ) return SQLITE_OK;
45982   testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
45983   testcase( pPager->doNotSpill & SPILLFLAG_OFF );
45984   testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
45985   if( pPager->doNotSpill
45986    && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
45987       || (pPg->flags & PGHDR_NEED_SYNC)!=0)
45988   ){
45989     return SQLITE_OK;
45990   }
45991
45992   pPg->pDirty = 0;
45993   if( pagerUseWal(pPager) ){
45994     /* Write a single frame for this page to the log. */
45995     if( subjRequiresPage(pPg) ){ 
45996       rc = subjournalPage(pPg); 
45997     }
45998     if( rc==SQLITE_OK ){
45999       rc = pagerWalFrames(pPager, pPg, 0, 0);
46000     }
46001   }else{
46002   
46003     /* Sync the journal file if required. */
46004     if( pPg->flags&PGHDR_NEED_SYNC 
46005      || pPager->eState==PAGER_WRITER_CACHEMOD
46006     ){
46007       rc = syncJournal(pPager, 1);
46008     }
46009   
46010     /* If the page number of this page is larger than the current size of
46011     ** the database image, it may need to be written to the sub-journal.
46012     ** This is because the call to pager_write_pagelist() below will not
46013     ** actually write data to the file in this case.
46014     **
46015     ** Consider the following sequence of events:
46016     **
46017     **   BEGIN;
46018     **     <journal page X>
46019     **     <modify page X>
46020     **     SAVEPOINT sp;
46021     **       <shrink database file to Y pages>
46022     **       pagerStress(page X)
46023     **     ROLLBACK TO sp;
46024     **
46025     ** If (X>Y), then when pagerStress is called page X will not be written
46026     ** out to the database file, but will be dropped from the cache. Then,
46027     ** following the "ROLLBACK TO sp" statement, reading page X will read
46028     ** data from the database file. This will be the copy of page X as it
46029     ** was when the transaction started, not as it was when "SAVEPOINT sp"
46030     ** was executed.
46031     **
46032     ** The solution is to write the current data for page X into the 
46033     ** sub-journal file now (if it is not already there), so that it will
46034     ** be restored to its current value when the "ROLLBACK TO sp" is 
46035     ** executed.
46036     */
46037     if( NEVER(
46038         rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
46039     ) ){
46040       rc = subjournalPage(pPg);
46041     }
46042   
46043     /* Write the contents of the page out to the database file. */
46044     if( rc==SQLITE_OK ){
46045       assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
46046       rc = pager_write_pagelist(pPager, pPg);
46047     }
46048   }
46049
46050   /* Mark the page as clean. */
46051   if( rc==SQLITE_OK ){
46052     PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
46053     sqlite3PcacheMakeClean(pPg);
46054   }
46055
46056   return pager_error(pPager, rc); 
46057 }
46058
46059
46060 /*
46061 ** Allocate and initialize a new Pager object and put a pointer to it
46062 ** in *ppPager. The pager should eventually be freed by passing it
46063 ** to sqlite3PagerClose().
46064 **
46065 ** The zFilename argument is the path to the database file to open.
46066 ** If zFilename is NULL then a randomly-named temporary file is created
46067 ** and used as the file to be cached. Temporary files are be deleted
46068 ** automatically when they are closed. If zFilename is ":memory:" then 
46069 ** all information is held in cache. It is never written to disk. 
46070 ** This can be used to implement an in-memory database.
46071 **
46072 ** The nExtra parameter specifies the number of bytes of space allocated
46073 ** along with each page reference. This space is available to the user
46074 ** via the sqlite3PagerGetExtra() API.
46075 **
46076 ** The flags argument is used to specify properties that affect the
46077 ** operation of the pager. It should be passed some bitwise combination
46078 ** of the PAGER_* flags.
46079 **
46080 ** The vfsFlags parameter is a bitmask to pass to the flags parameter
46081 ** of the xOpen() method of the supplied VFS when opening files. 
46082 **
46083 ** If the pager object is allocated and the specified file opened 
46084 ** successfully, SQLITE_OK is returned and *ppPager set to point to
46085 ** the new pager object. If an error occurs, *ppPager is set to NULL
46086 ** and error code returned. This function may return SQLITE_NOMEM
46087 ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or 
46088 ** various SQLITE_IO_XXX errors.
46089 */
46090 SQLITE_PRIVATE int sqlite3PagerOpen(
46091   sqlite3_vfs *pVfs,       /* The virtual file system to use */
46092   Pager **ppPager,         /* OUT: Return the Pager structure here */
46093   const char *zFilename,   /* Name of the database file to open */
46094   int nExtra,              /* Extra bytes append to each in-memory page */
46095   int flags,               /* flags controlling this file */
46096   int vfsFlags,            /* flags passed through to sqlite3_vfs.xOpen() */
46097   void (*xReinit)(DbPage*) /* Function to reinitialize pages */
46098 ){
46099   u8 *pPtr;
46100   Pager *pPager = 0;       /* Pager object to allocate and return */
46101   int rc = SQLITE_OK;      /* Return code */
46102   int tempFile = 0;        /* True for temp files (incl. in-memory files) */
46103   int memDb = 0;           /* True if this is an in-memory file */
46104   int readOnly = 0;        /* True if this is a read-only file */
46105   int journalFileSize;     /* Bytes to allocate for each journal fd */
46106   char *zPathname = 0;     /* Full path to database file */
46107   int nPathname = 0;       /* Number of bytes in zPathname */
46108   int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
46109   int pcacheSize = sqlite3PcacheSize();       /* Bytes to allocate for PCache */
46110   u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE;  /* Default page size */
46111   const char *zUri = 0;    /* URI args to copy */
46112   int nUri = 0;            /* Number of bytes of URI args at *zUri */
46113
46114   /* Figure out how much space is required for each journal file-handle
46115   ** (there are two of them, the main journal and the sub-journal). This
46116   ** is the maximum space required for an in-memory journal file handle 
46117   ** and a regular journal file-handle. Note that a "regular journal-handle"
46118   ** may be a wrapper capable of caching the first portion of the journal
46119   ** file in memory to implement the atomic-write optimization (see 
46120   ** source file journal.c).
46121   */
46122   if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
46123     journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
46124   }else{
46125     journalFileSize = ROUND8(sqlite3MemJournalSize());
46126   }
46127
46128   /* Set the output variable to NULL in case an error occurs. */
46129   *ppPager = 0;
46130
46131 #ifndef SQLITE_OMIT_MEMORYDB
46132   if( flags & PAGER_MEMORY ){
46133     memDb = 1;
46134     if( zFilename && zFilename[0] ){
46135       zPathname = sqlite3DbStrDup(0, zFilename);
46136       if( zPathname==0  ) return SQLITE_NOMEM;
46137       nPathname = sqlite3Strlen30(zPathname);
46138       zFilename = 0;
46139     }
46140   }
46141 #endif
46142
46143   /* Compute and store the full pathname in an allocated buffer pointed
46144   ** to by zPathname, length nPathname. Or, if this is a temporary file,
46145   ** leave both nPathname and zPathname set to 0.
46146   */
46147   if( zFilename && zFilename[0] ){
46148     const char *z;
46149     nPathname = pVfs->mxPathname+1;
46150     zPathname = sqlite3DbMallocRaw(0, nPathname*2);
46151     if( zPathname==0 ){
46152       return SQLITE_NOMEM;
46153     }
46154     zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
46155     rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
46156     nPathname = sqlite3Strlen30(zPathname);
46157     z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
46158     while( *z ){
46159       z += sqlite3Strlen30(z)+1;
46160       z += sqlite3Strlen30(z)+1;
46161     }
46162     nUri = (int)(&z[1] - zUri);
46163     assert( nUri>=0 );
46164     if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
46165       /* This branch is taken when the journal path required by
46166       ** the database being opened will be more than pVfs->mxPathname
46167       ** bytes in length. This means the database cannot be opened,
46168       ** as it will not be possible to open the journal file or even
46169       ** check for a hot-journal before reading.
46170       */
46171       rc = SQLITE_CANTOPEN_BKPT;
46172     }
46173     if( rc!=SQLITE_OK ){
46174       sqlite3DbFree(0, zPathname);
46175       return rc;
46176     }
46177   }
46178
46179   /* Allocate memory for the Pager structure, PCache object, the
46180   ** three file descriptors, the database file name and the journal 
46181   ** file name. The layout in memory is as follows:
46182   **
46183   **     Pager object                    (sizeof(Pager) bytes)
46184   **     PCache object                   (sqlite3PcacheSize() bytes)
46185   **     Database file handle            (pVfs->szOsFile bytes)
46186   **     Sub-journal file handle         (journalFileSize bytes)
46187   **     Main journal file handle        (journalFileSize bytes)
46188   **     Database file name              (nPathname+1 bytes)
46189   **     Journal file name               (nPathname+8+1 bytes)
46190   */
46191   pPtr = (u8 *)sqlite3MallocZero(
46192     ROUND8(sizeof(*pPager)) +      /* Pager structure */
46193     ROUND8(pcacheSize) +           /* PCache object */
46194     ROUND8(pVfs->szOsFile) +       /* The main db file */
46195     journalFileSize * 2 +          /* The two journal files */ 
46196     nPathname + 1 + nUri +         /* zFilename */
46197     nPathname + 8 + 2              /* zJournal */
46198 #ifndef SQLITE_OMIT_WAL
46199     + nPathname + 4 + 2            /* zWal */
46200 #endif
46201   );
46202   assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
46203   if( !pPtr ){
46204     sqlite3DbFree(0, zPathname);
46205     return SQLITE_NOMEM;
46206   }
46207   pPager =              (Pager*)(pPtr);
46208   pPager->pPCache =    (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
46209   pPager->fd =   (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
46210   pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
46211   pPager->jfd =  (sqlite3_file*)(pPtr += journalFileSize);
46212   pPager->zFilename =    (char*)(pPtr += journalFileSize);
46213   assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
46214
46215   /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
46216   if( zPathname ){
46217     assert( nPathname>0 );
46218     pPager->zJournal =   (char*)(pPtr += nPathname + 1 + nUri);
46219     memcpy(pPager->zFilename, zPathname, nPathname);
46220     if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
46221     memcpy(pPager->zJournal, zPathname, nPathname);
46222     memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
46223     sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
46224 #ifndef SQLITE_OMIT_WAL
46225     pPager->zWal = &pPager->zJournal[nPathname+8+1];
46226     memcpy(pPager->zWal, zPathname, nPathname);
46227     memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
46228     sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
46229 #endif
46230     sqlite3DbFree(0, zPathname);
46231   }
46232   pPager->pVfs = pVfs;
46233   pPager->vfsFlags = vfsFlags;
46234
46235   /* Open the pager file.
46236   */
46237   if( zFilename && zFilename[0] ){
46238     int fout = 0;                    /* VFS flags returned by xOpen() */
46239     rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
46240     assert( !memDb );
46241     readOnly = (fout&SQLITE_OPEN_READONLY);
46242
46243     /* If the file was successfully opened for read/write access,
46244     ** choose a default page size in case we have to create the
46245     ** database file. The default page size is the maximum of:
46246     **
46247     **    + SQLITE_DEFAULT_PAGE_SIZE,
46248     **    + The value returned by sqlite3OsSectorSize()
46249     **    + The largest page size that can be written atomically.
46250     */
46251     if( rc==SQLITE_OK ){
46252       int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
46253       if( !readOnly ){
46254         setSectorSize(pPager);
46255         assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
46256         if( szPageDflt<pPager->sectorSize ){
46257           if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
46258             szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
46259           }else{
46260             szPageDflt = (u32)pPager->sectorSize;
46261           }
46262         }
46263 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
46264         {
46265           int ii;
46266           assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
46267           assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
46268           assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
46269           for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
46270             if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
46271               szPageDflt = ii;
46272             }
46273           }
46274         }
46275 #endif
46276       }
46277       pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
46278       if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
46279        || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
46280           vfsFlags |= SQLITE_OPEN_READONLY;
46281           goto act_like_temp_file;
46282       }
46283     }
46284   }else{
46285     /* If a temporary file is requested, it is not opened immediately.
46286     ** In this case we accept the default page size and delay actually
46287     ** opening the file until the first call to OsWrite().
46288     **
46289     ** This branch is also run for an in-memory database. An in-memory
46290     ** database is the same as a temp-file that is never written out to
46291     ** disk and uses an in-memory rollback journal.
46292     **
46293     ** This branch also runs for files marked as immutable.
46294     */ 
46295 act_like_temp_file:
46296     tempFile = 1;
46297     pPager->eState = PAGER_READER;     /* Pretend we already have a lock */
46298     pPager->eLock = EXCLUSIVE_LOCK;    /* Pretend we are in EXCLUSIVE locking mode */
46299     pPager->noLock = 1;                /* Do no locking */
46300     readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
46301   }
46302
46303   /* The following call to PagerSetPagesize() serves to set the value of 
46304   ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
46305   */
46306   if( rc==SQLITE_OK ){
46307     assert( pPager->memDb==0 );
46308     rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
46309     testcase( rc!=SQLITE_OK );
46310   }
46311
46312   /* Initialize the PCache object. */
46313   if( rc==SQLITE_OK ){
46314     assert( nExtra<1000 );
46315     nExtra = ROUND8(nExtra);
46316     rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
46317                            !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
46318   }
46319
46320   /* If an error occurred above, free the  Pager structure and close the file.
46321   */
46322   if( rc!=SQLITE_OK ){
46323     sqlite3OsClose(pPager->fd);
46324     sqlite3PageFree(pPager->pTmpSpace);
46325     sqlite3_free(pPager);
46326     return rc;
46327   }
46328
46329   PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
46330   IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
46331
46332   pPager->useJournal = (u8)useJournal;
46333   /* pPager->stmtOpen = 0; */
46334   /* pPager->stmtInUse = 0; */
46335   /* pPager->nRef = 0; */
46336   /* pPager->stmtSize = 0; */
46337   /* pPager->stmtJSize = 0; */
46338   /* pPager->nPage = 0; */
46339   pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
46340   /* pPager->state = PAGER_UNLOCK; */
46341   /* pPager->errMask = 0; */
46342   pPager->tempFile = (u8)tempFile;
46343   assert( tempFile==PAGER_LOCKINGMODE_NORMAL 
46344           || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
46345   assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
46346   pPager->exclusiveMode = (u8)tempFile; 
46347   pPager->changeCountDone = pPager->tempFile;
46348   pPager->memDb = (u8)memDb;
46349   pPager->readOnly = (u8)readOnly;
46350   assert( useJournal || pPager->tempFile );
46351   pPager->noSync = pPager->tempFile;
46352   if( pPager->noSync ){
46353     assert( pPager->fullSync==0 );
46354     assert( pPager->syncFlags==0 );
46355     assert( pPager->walSyncFlags==0 );
46356     assert( pPager->ckptSyncFlags==0 );
46357   }else{
46358     pPager->fullSync = 1;
46359     pPager->syncFlags = SQLITE_SYNC_NORMAL;
46360     pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
46361     pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
46362   }
46363   /* pPager->pFirst = 0; */
46364   /* pPager->pFirstSynced = 0; */
46365   /* pPager->pLast = 0; */
46366   pPager->nExtra = (u16)nExtra;
46367   pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
46368   assert( isOpen(pPager->fd) || tempFile );
46369   setSectorSize(pPager);
46370   if( !useJournal ){
46371     pPager->journalMode = PAGER_JOURNALMODE_OFF;
46372   }else if( memDb ){
46373     pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
46374   }
46375   /* pPager->xBusyHandler = 0; */
46376   /* pPager->pBusyHandlerArg = 0; */
46377   pPager->xReiniter = xReinit;
46378   /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
46379   /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
46380
46381   *ppPager = pPager;
46382   return SQLITE_OK;
46383 }
46384
46385
46386 /* Verify that the database file has not be deleted or renamed out from
46387 ** under the pager.  Return SQLITE_OK if the database is still were it ought
46388 ** to be on disk.  Return non-zero (SQLITE_READONLY_DBMOVED or some other error
46389 ** code from sqlite3OsAccess()) if the database has gone missing.
46390 */
46391 static int databaseIsUnmoved(Pager *pPager){
46392   int bHasMoved = 0;
46393   int rc;
46394
46395   if( pPager->tempFile ) return SQLITE_OK;
46396   if( pPager->dbSize==0 ) return SQLITE_OK;
46397   assert( pPager->zFilename && pPager->zFilename[0] );
46398   rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
46399   if( rc==SQLITE_NOTFOUND ){
46400     /* If the HAS_MOVED file-control is unimplemented, assume that the file
46401     ** has not been moved.  That is the historical behavior of SQLite: prior to
46402     ** version 3.8.3, it never checked */
46403     rc = SQLITE_OK;
46404   }else if( rc==SQLITE_OK && bHasMoved ){
46405     rc = SQLITE_READONLY_DBMOVED;
46406   }
46407   return rc;
46408 }
46409
46410
46411 /*
46412 ** This function is called after transitioning from PAGER_UNLOCK to
46413 ** PAGER_SHARED state. It tests if there is a hot journal present in
46414 ** the file-system for the given pager. A hot journal is one that 
46415 ** needs to be played back. According to this function, a hot-journal
46416 ** file exists if the following criteria are met:
46417 **
46418 **   * The journal file exists in the file system, and
46419 **   * No process holds a RESERVED or greater lock on the database file, and
46420 **   * The database file itself is greater than 0 bytes in size, and
46421 **   * The first byte of the journal file exists and is not 0x00.
46422 **
46423 ** If the current size of the database file is 0 but a journal file
46424 ** exists, that is probably an old journal left over from a prior
46425 ** database with the same name. In this case the journal file is
46426 ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
46427 ** is returned.
46428 **
46429 ** This routine does not check if there is a master journal filename
46430 ** at the end of the file. If there is, and that master journal file
46431 ** does not exist, then the journal file is not really hot. In this
46432 ** case this routine will return a false-positive. The pager_playback()
46433 ** routine will discover that the journal file is not really hot and 
46434 ** will not roll it back. 
46435 **
46436 ** If a hot-journal file is found to exist, *pExists is set to 1 and 
46437 ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
46438 ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
46439 ** to determine whether or not a hot-journal file exists, the IO error
46440 ** code is returned and the value of *pExists is undefined.
46441 */
46442 static int hasHotJournal(Pager *pPager, int *pExists){
46443   sqlite3_vfs * const pVfs = pPager->pVfs;
46444   int rc = SQLITE_OK;           /* Return code */
46445   int exists = 1;               /* True if a journal file is present */
46446   int jrnlOpen = !!isOpen(pPager->jfd);
46447
46448   assert( pPager->useJournal );
46449   assert( isOpen(pPager->fd) );
46450   assert( pPager->eState==PAGER_OPEN );
46451
46452   assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
46453     SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
46454   ));
46455
46456   *pExists = 0;
46457   if( !jrnlOpen ){
46458     rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
46459   }
46460   if( rc==SQLITE_OK && exists ){
46461     int locked = 0;             /* True if some process holds a RESERVED lock */
46462
46463     /* Race condition here:  Another process might have been holding the
46464     ** the RESERVED lock and have a journal open at the sqlite3OsAccess() 
46465     ** call above, but then delete the journal and drop the lock before
46466     ** we get to the following sqlite3OsCheckReservedLock() call.  If that
46467     ** is the case, this routine might think there is a hot journal when
46468     ** in fact there is none.  This results in a false-positive which will
46469     ** be dealt with by the playback routine.  Ticket #3883.
46470     */
46471     rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
46472     if( rc==SQLITE_OK && !locked ){
46473       Pgno nPage;                 /* Number of pages in database file */
46474
46475       rc = pagerPagecount(pPager, &nPage);
46476       if( rc==SQLITE_OK ){
46477         /* If the database is zero pages in size, that means that either (1) the
46478         ** journal is a remnant from a prior database with the same name where
46479         ** the database file but not the journal was deleted, or (2) the initial
46480         ** transaction that populates a new database is being rolled back.
46481         ** In either case, the journal file can be deleted.  However, take care
46482         ** not to delete the journal file if it is already open due to
46483         ** journal_mode=PERSIST.
46484         */
46485         if( nPage==0 && !jrnlOpen ){
46486           sqlite3BeginBenignMalloc();
46487           if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
46488             sqlite3OsDelete(pVfs, pPager->zJournal, 0);
46489             if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
46490           }
46491           sqlite3EndBenignMalloc();
46492         }else{
46493           /* The journal file exists and no other connection has a reserved
46494           ** or greater lock on the database file. Now check that there is
46495           ** at least one non-zero bytes at the start of the journal file.
46496           ** If there is, then we consider this journal to be hot. If not, 
46497           ** it can be ignored.
46498           */
46499           if( !jrnlOpen ){
46500             int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
46501             rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
46502           }
46503           if( rc==SQLITE_OK ){
46504             u8 first = 0;
46505             rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
46506             if( rc==SQLITE_IOERR_SHORT_READ ){
46507               rc = SQLITE_OK;
46508             }
46509             if( !jrnlOpen ){
46510               sqlite3OsClose(pPager->jfd);
46511             }
46512             *pExists = (first!=0);
46513           }else if( rc==SQLITE_CANTOPEN ){
46514             /* If we cannot open the rollback journal file in order to see if
46515             ** it has a zero header, that might be due to an I/O error, or
46516             ** it might be due to the race condition described above and in
46517             ** ticket #3883.  Either way, assume that the journal is hot.
46518             ** This might be a false positive.  But if it is, then the
46519             ** automatic journal playback and recovery mechanism will deal
46520             ** with it under an EXCLUSIVE lock where we do not need to
46521             ** worry so much with race conditions.
46522             */
46523             *pExists = 1;
46524             rc = SQLITE_OK;
46525           }
46526         }
46527       }
46528     }
46529   }
46530
46531   return rc;
46532 }
46533
46534 /*
46535 ** This function is called to obtain a shared lock on the database file.
46536 ** It is illegal to call sqlite3PagerAcquire() until after this function
46537 ** has been successfully called. If a shared-lock is already held when
46538 ** this function is called, it is a no-op.
46539 **
46540 ** The following operations are also performed by this function.
46541 **
46542 **   1) If the pager is currently in PAGER_OPEN state (no lock held
46543 **      on the database file), then an attempt is made to obtain a
46544 **      SHARED lock on the database file. Immediately after obtaining
46545 **      the SHARED lock, the file-system is checked for a hot-journal,
46546 **      which is played back if present. Following any hot-journal 
46547 **      rollback, the contents of the cache are validated by checking
46548 **      the 'change-counter' field of the database file header and
46549 **      discarded if they are found to be invalid.
46550 **
46551 **   2) If the pager is running in exclusive-mode, and there are currently
46552 **      no outstanding references to any pages, and is in the error state,
46553 **      then an attempt is made to clear the error state by discarding
46554 **      the contents of the page cache and rolling back any open journal
46555 **      file.
46556 **
46557 ** If everything is successful, SQLITE_OK is returned. If an IO error 
46558 ** occurs while locking the database, checking for a hot-journal file or 
46559 ** rolling back a journal file, the IO error code is returned.
46560 */
46561 SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
46562   int rc = SQLITE_OK;                /* Return code */
46563
46564   /* This routine is only called from b-tree and only when there are no
46565   ** outstanding pages. This implies that the pager state should either
46566   ** be OPEN or READER. READER is only possible if the pager is or was in 
46567   ** exclusive access mode.
46568   */
46569   assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
46570   assert( assert_pager_state(pPager) );
46571   assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
46572   if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
46573
46574   if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
46575     int bHotJournal = 1;          /* True if there exists a hot journal-file */
46576
46577     assert( !MEMDB );
46578
46579     rc = pager_wait_on_lock(pPager, SHARED_LOCK);
46580     if( rc!=SQLITE_OK ){
46581       assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
46582       goto failed;
46583     }
46584
46585     /* If a journal file exists, and there is no RESERVED lock on the
46586     ** database file, then it either needs to be played back or deleted.
46587     */
46588     if( pPager->eLock<=SHARED_LOCK ){
46589       rc = hasHotJournal(pPager, &bHotJournal);
46590     }
46591     if( rc!=SQLITE_OK ){
46592       goto failed;
46593     }
46594     if( bHotJournal ){
46595       if( pPager->readOnly ){
46596         rc = SQLITE_READONLY_ROLLBACK;
46597         goto failed;
46598       }
46599
46600       /* Get an EXCLUSIVE lock on the database file. At this point it is
46601       ** important that a RESERVED lock is not obtained on the way to the
46602       ** EXCLUSIVE lock. If it were, another process might open the
46603       ** database file, detect the RESERVED lock, and conclude that the
46604       ** database is safe to read while this process is still rolling the 
46605       ** hot-journal back.
46606       ** 
46607       ** Because the intermediate RESERVED lock is not requested, any
46608       ** other process attempting to access the database file will get to 
46609       ** this point in the code and fail to obtain its own EXCLUSIVE lock 
46610       ** on the database file.
46611       **
46612       ** Unless the pager is in locking_mode=exclusive mode, the lock is
46613       ** downgraded to SHARED_LOCK before this function returns.
46614       */
46615       rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
46616       if( rc!=SQLITE_OK ){
46617         goto failed;
46618       }
46619  
46620       /* If it is not already open and the file exists on disk, open the 
46621       ** journal for read/write access. Write access is required because 
46622       ** in exclusive-access mode the file descriptor will be kept open 
46623       ** and possibly used for a transaction later on. Also, write-access 
46624       ** is usually required to finalize the journal in journal_mode=persist 
46625       ** mode (and also for journal_mode=truncate on some systems).
46626       **
46627       ** If the journal does not exist, it usually means that some 
46628       ** other connection managed to get in and roll it back before 
46629       ** this connection obtained the exclusive lock above. Or, it 
46630       ** may mean that the pager was in the error-state when this
46631       ** function was called and the journal file does not exist.
46632       */
46633       if( !isOpen(pPager->jfd) ){
46634         sqlite3_vfs * const pVfs = pPager->pVfs;
46635         int bExists;              /* True if journal file exists */
46636         rc = sqlite3OsAccess(
46637             pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
46638         if( rc==SQLITE_OK && bExists ){
46639           int fout = 0;
46640           int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
46641           assert( !pPager->tempFile );
46642           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
46643           assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
46644           if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
46645             rc = SQLITE_CANTOPEN_BKPT;
46646             sqlite3OsClose(pPager->jfd);
46647           }
46648         }
46649       }
46650  
46651       /* Playback and delete the journal.  Drop the database write
46652       ** lock and reacquire the read lock. Purge the cache before
46653       ** playing back the hot-journal so that we don't end up with
46654       ** an inconsistent cache.  Sync the hot journal before playing
46655       ** it back since the process that crashed and left the hot journal
46656       ** probably did not sync it and we are required to always sync
46657       ** the journal before playing it back.
46658       */
46659       if( isOpen(pPager->jfd) ){
46660         assert( rc==SQLITE_OK );
46661         rc = pagerSyncHotJournal(pPager);
46662         if( rc==SQLITE_OK ){
46663           rc = pager_playback(pPager, 1);
46664           pPager->eState = PAGER_OPEN;
46665         }
46666       }else if( !pPager->exclusiveMode ){
46667         pagerUnlockDb(pPager, SHARED_LOCK);
46668       }
46669
46670       if( rc!=SQLITE_OK ){
46671         /* This branch is taken if an error occurs while trying to open
46672         ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
46673         ** pager_unlock() routine will be called before returning to unlock
46674         ** the file. If the unlock attempt fails, then Pager.eLock must be
46675         ** set to UNKNOWN_LOCK (see the comment above the #define for 
46676         ** UNKNOWN_LOCK above for an explanation). 
46677         **
46678         ** In order to get pager_unlock() to do this, set Pager.eState to
46679         ** PAGER_ERROR now. This is not actually counted as a transition
46680         ** to ERROR state in the state diagram at the top of this file,
46681         ** since we know that the same call to pager_unlock() will very
46682         ** shortly transition the pager object to the OPEN state. Calling
46683         ** assert_pager_state() would fail now, as it should not be possible
46684         ** to be in ERROR state when there are zero outstanding page 
46685         ** references.
46686         */
46687         pager_error(pPager, rc);
46688         goto failed;
46689       }
46690
46691       assert( pPager->eState==PAGER_OPEN );
46692       assert( (pPager->eLock==SHARED_LOCK)
46693            || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
46694       );
46695     }
46696
46697     if( !pPager->tempFile && pPager->hasBeenUsed ){
46698       /* The shared-lock has just been acquired then check to
46699       ** see if the database has been modified.  If the database has changed,
46700       ** flush the cache.  The pPager->hasBeenUsed flag prevents this from
46701       ** occurring on the very first access to a file, in order to save a
46702       ** single unnecessary sqlite3OsRead() call at the start-up.
46703       **
46704       ** Database changes is detected by looking at 15 bytes beginning
46705       ** at offset 24 into the file.  The first 4 of these 16 bytes are
46706       ** a 32-bit counter that is incremented with each change.  The
46707       ** other bytes change randomly with each file change when
46708       ** a codec is in use.
46709       ** 
46710       ** There is a vanishingly small chance that a change will not be 
46711       ** detected.  The chance of an undetected change is so small that
46712       ** it can be neglected.
46713       */
46714       Pgno nPage = 0;
46715       char dbFileVers[sizeof(pPager->dbFileVers)];
46716
46717       rc = pagerPagecount(pPager, &nPage);
46718       if( rc ) goto failed;
46719
46720       if( nPage>0 ){
46721         IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
46722         rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
46723         if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
46724           goto failed;
46725         }
46726       }else{
46727         memset(dbFileVers, 0, sizeof(dbFileVers));
46728       }
46729
46730       if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
46731         pager_reset(pPager);
46732
46733         /* Unmap the database file. It is possible that external processes
46734         ** may have truncated the database file and then extended it back
46735         ** to its original size while this process was not holding a lock.
46736         ** In this case there may exist a Pager.pMap mapping that appears
46737         ** to be the right size but is not actually valid. Avoid this
46738         ** possibility by unmapping the db here. */
46739         if( USEFETCH(pPager) ){
46740           sqlite3OsUnfetch(pPager->fd, 0, 0);
46741         }
46742       }
46743     }
46744
46745     /* If there is a WAL file in the file-system, open this database in WAL
46746     ** mode. Otherwise, the following function call is a no-op.
46747     */
46748     rc = pagerOpenWalIfPresent(pPager);
46749 #ifndef SQLITE_OMIT_WAL
46750     assert( pPager->pWal==0 || rc==SQLITE_OK );
46751 #endif
46752   }
46753
46754   if( pagerUseWal(pPager) ){
46755     assert( rc==SQLITE_OK );
46756     rc = pagerBeginReadTransaction(pPager);
46757   }
46758
46759   if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
46760     rc = pagerPagecount(pPager, &pPager->dbSize);
46761   }
46762
46763  failed:
46764   if( rc!=SQLITE_OK ){
46765     assert( !MEMDB );
46766     pager_unlock(pPager);
46767     assert( pPager->eState==PAGER_OPEN );
46768   }else{
46769     pPager->eState = PAGER_READER;
46770   }
46771   return rc;
46772 }
46773
46774 /*
46775 ** If the reference count has reached zero, rollback any active
46776 ** transaction and unlock the pager.
46777 **
46778 ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
46779 ** the rollback journal, the unlock is not performed and there is
46780 ** nothing to rollback, so this routine is a no-op.
46781 */ 
46782 static void pagerUnlockIfUnused(Pager *pPager){
46783   if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
46784     pagerUnlockAndRollback(pPager);
46785   }
46786 }
46787
46788 /*
46789 ** Acquire a reference to page number pgno in pager pPager (a page
46790 ** reference has type DbPage*). If the requested reference is 
46791 ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
46792 **
46793 ** If the requested page is already in the cache, it is returned. 
46794 ** Otherwise, a new page object is allocated and populated with data
46795 ** read from the database file. In some cases, the pcache module may
46796 ** choose not to allocate a new page object and may reuse an existing
46797 ** object with no outstanding references.
46798 **
46799 ** The extra data appended to a page is always initialized to zeros the 
46800 ** first time a page is loaded into memory. If the page requested is 
46801 ** already in the cache when this function is called, then the extra
46802 ** data is left as it was when the page object was last used.
46803 **
46804 ** If the database image is smaller than the requested page or if a 
46805 ** non-zero value is passed as the noContent parameter and the 
46806 ** requested page is not already stored in the cache, then no 
46807 ** actual disk read occurs. In this case the memory image of the 
46808 ** page is initialized to all zeros. 
46809 **
46810 ** If noContent is true, it means that we do not care about the contents
46811 ** of the page. This occurs in two scenarios:
46812 **
46813 **   a) When reading a free-list leaf page from the database, and
46814 **
46815 **   b) When a savepoint is being rolled back and we need to load
46816 **      a new page into the cache to be filled with the data read
46817 **      from the savepoint journal.
46818 **
46819 ** If noContent is true, then the data returned is zeroed instead of
46820 ** being read from the database. Additionally, the bits corresponding
46821 ** to pgno in Pager.pInJournal (bitvec of pages already written to the
46822 ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
46823 ** savepoints are set. This means if the page is made writable at any
46824 ** point in the future, using a call to sqlite3PagerWrite(), its contents
46825 ** will not be journaled. This saves IO.
46826 **
46827 ** The acquisition might fail for several reasons.  In all cases,
46828 ** an appropriate error code is returned and *ppPage is set to NULL.
46829 **
46830 ** See also sqlite3PagerLookup().  Both this routine and Lookup() attempt
46831 ** to find a page in the in-memory cache first.  If the page is not already
46832 ** in memory, this routine goes to disk to read it in whereas Lookup()
46833 ** just returns 0.  This routine acquires a read-lock the first time it
46834 ** has to go to disk, and could also playback an old journal if necessary.
46835 ** Since Lookup() never goes to disk, it never has to deal with locks
46836 ** or journal files.
46837 */
46838 SQLITE_PRIVATE int sqlite3PagerAcquire(
46839   Pager *pPager,      /* The pager open on the database file */
46840   Pgno pgno,          /* Page number to fetch */
46841   DbPage **ppPage,    /* Write a pointer to the page here */
46842   int flags           /* PAGER_GET_XXX flags */
46843 ){
46844   int rc = SQLITE_OK;
46845   PgHdr *pPg = 0;
46846   u32 iFrame = 0;                 /* Frame to read from WAL file */
46847   const int noContent = (flags & PAGER_GET_NOCONTENT);
46848
46849   /* It is acceptable to use a read-only (mmap) page for any page except
46850   ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
46851   ** flag was specified by the caller. And so long as the db is not a 
46852   ** temporary or in-memory database.  */
46853   const int bMmapOk = (pgno!=1 && USEFETCH(pPager)
46854    && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
46855 #ifdef SQLITE_HAS_CODEC
46856    && pPager->xCodec==0
46857 #endif
46858   );
46859
46860   assert( pPager->eState>=PAGER_READER );
46861   assert( assert_pager_state(pPager) );
46862   assert( noContent==0 || bMmapOk==0 );
46863
46864   if( pgno==0 ){
46865     return SQLITE_CORRUPT_BKPT;
46866   }
46867   pPager->hasBeenUsed = 1;
46868
46869   /* If the pager is in the error state, return an error immediately. 
46870   ** Otherwise, request the page from the PCache layer. */
46871   if( pPager->errCode!=SQLITE_OK ){
46872     rc = pPager->errCode;
46873   }else{
46874     if( bMmapOk && pagerUseWal(pPager) ){
46875       rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
46876       if( rc!=SQLITE_OK ) goto pager_acquire_err;
46877     }
46878
46879     if( bMmapOk && iFrame==0 ){
46880       void *pData = 0;
46881
46882       rc = sqlite3OsFetch(pPager->fd, 
46883           (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
46884       );
46885
46886       if( rc==SQLITE_OK && pData ){
46887         if( pPager->eState>PAGER_READER ){
46888           pPg = sqlite3PagerLookup(pPager, pgno);
46889         }
46890         if( pPg==0 ){
46891           rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
46892         }else{
46893           sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
46894         }
46895         if( pPg ){
46896           assert( rc==SQLITE_OK );
46897           *ppPage = pPg;
46898           return SQLITE_OK;
46899         }
46900       }
46901       if( rc!=SQLITE_OK ){
46902         goto pager_acquire_err;
46903       }
46904     }
46905
46906     {
46907       sqlite3_pcache_page *pBase;
46908       pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
46909       if( pBase==0 ){
46910         rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
46911         if( rc!=SQLITE_OK ) goto pager_acquire_err;
46912       }
46913       pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
46914       if( pPg==0 ) rc = SQLITE_NOMEM;
46915     }
46916   }
46917
46918   if( rc!=SQLITE_OK ){
46919     /* Either the call to sqlite3PcacheFetch() returned an error or the
46920     ** pager was already in the error-state when this function was called.
46921     ** Set pPg to 0 and jump to the exception handler.  */
46922     pPg = 0;
46923     goto pager_acquire_err;
46924   }
46925   assert( (*ppPage)->pgno==pgno );
46926   assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
46927
46928   if( (*ppPage)->pPager && !noContent ){
46929     /* In this case the pcache already contains an initialized copy of
46930     ** the page. Return without further ado.  */
46931     assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
46932     pPager->aStat[PAGER_STAT_HIT]++;
46933     return SQLITE_OK;
46934
46935   }else{
46936     /* The pager cache has created a new page. Its content needs to 
46937     ** be initialized.  */
46938
46939     pPg = *ppPage;
46940     pPg->pPager = pPager;
46941
46942     /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
46943     ** number greater than this, or the unused locking-page, is requested. */
46944     if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
46945       rc = SQLITE_CORRUPT_BKPT;
46946       goto pager_acquire_err;
46947     }
46948
46949     if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
46950       if( pgno>pPager->mxPgno ){
46951         rc = SQLITE_FULL;
46952         goto pager_acquire_err;
46953       }
46954       if( noContent ){
46955         /* Failure to set the bits in the InJournal bit-vectors is benign.
46956         ** It merely means that we might do some extra work to journal a 
46957         ** page that does not need to be journaled.  Nevertheless, be sure 
46958         ** to test the case where a malloc error occurs while trying to set 
46959         ** a bit in a bit vector.
46960         */
46961         sqlite3BeginBenignMalloc();
46962         if( pgno<=pPager->dbOrigSize ){
46963           TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
46964           testcase( rc==SQLITE_NOMEM );
46965         }
46966         TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
46967         testcase( rc==SQLITE_NOMEM );
46968         sqlite3EndBenignMalloc();
46969       }
46970       memset(pPg->pData, 0, pPager->pageSize);
46971       IOTRACE(("ZERO %p %d\n", pPager, pgno));
46972     }else{
46973       if( pagerUseWal(pPager) && bMmapOk==0 ){
46974         rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
46975         if( rc!=SQLITE_OK ) goto pager_acquire_err;
46976       }
46977       assert( pPg->pPager==pPager );
46978       pPager->aStat[PAGER_STAT_MISS]++;
46979       rc = readDbPage(pPg, iFrame);
46980       if( rc!=SQLITE_OK ){
46981         goto pager_acquire_err;
46982       }
46983     }
46984     pager_set_pagehash(pPg);
46985   }
46986
46987   return SQLITE_OK;
46988
46989 pager_acquire_err:
46990   assert( rc!=SQLITE_OK );
46991   if( pPg ){
46992     sqlite3PcacheDrop(pPg);
46993   }
46994   pagerUnlockIfUnused(pPager);
46995
46996   *ppPage = 0;
46997   return rc;
46998 }
46999
47000 /*
47001 ** Acquire a page if it is already in the in-memory cache.  Do
47002 ** not read the page from disk.  Return a pointer to the page,
47003 ** or 0 if the page is not in cache. 
47004 **
47005 ** See also sqlite3PagerGet().  The difference between this routine
47006 ** and sqlite3PagerGet() is that _get() will go to the disk and read
47007 ** in the page if the page is not already in cache.  This routine
47008 ** returns NULL if the page is not in cache or if a disk I/O error 
47009 ** has ever happened.
47010 */
47011 SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
47012   sqlite3_pcache_page *pPage;
47013   assert( pPager!=0 );
47014   assert( pgno!=0 );
47015   assert( pPager->pPCache!=0 );
47016   pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
47017   assert( pPage==0 || pPager->hasBeenUsed );
47018   return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
47019 }
47020
47021 /*
47022 ** Release a page reference.
47023 **
47024 ** If the number of references to the page drop to zero, then the
47025 ** page is added to the LRU list.  When all references to all pages
47026 ** are released, a rollback occurs and the lock on the database is
47027 ** removed.
47028 */
47029 SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
47030   Pager *pPager;
47031   assert( pPg!=0 );
47032   pPager = pPg->pPager;
47033   if( pPg->flags & PGHDR_MMAP ){
47034     pagerReleaseMapPage(pPg);
47035   }else{
47036     sqlite3PcacheRelease(pPg);
47037   }
47038   pagerUnlockIfUnused(pPager);
47039 }
47040 SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
47041   if( pPg ) sqlite3PagerUnrefNotNull(pPg);
47042 }
47043
47044 /*
47045 ** This function is called at the start of every write transaction.
47046 ** There must already be a RESERVED or EXCLUSIVE lock on the database 
47047 ** file when this routine is called.
47048 **
47049 ** Open the journal file for pager pPager and write a journal header
47050 ** to the start of it. If there are active savepoints, open the sub-journal
47051 ** as well. This function is only used when the journal file is being 
47052 ** opened to write a rollback log for a transaction. It is not used 
47053 ** when opening a hot journal file to roll it back.
47054 **
47055 ** If the journal file is already open (as it may be in exclusive mode),
47056 ** then this function just writes a journal header to the start of the
47057 ** already open file. 
47058 **
47059 ** Whether or not the journal file is opened by this function, the
47060 ** Pager.pInJournal bitvec structure is allocated.
47061 **
47062 ** Return SQLITE_OK if everything is successful. Otherwise, return 
47063 ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or 
47064 ** an IO error code if opening or writing the journal file fails.
47065 */
47066 static int pager_open_journal(Pager *pPager){
47067   int rc = SQLITE_OK;                        /* Return code */
47068   sqlite3_vfs * const pVfs = pPager->pVfs;   /* Local cache of vfs pointer */
47069
47070   assert( pPager->eState==PAGER_WRITER_LOCKED );
47071   assert( assert_pager_state(pPager) );
47072   assert( pPager->pInJournal==0 );
47073   
47074   /* If already in the error state, this function is a no-op.  But on
47075   ** the other hand, this routine is never called if we are already in
47076   ** an error state. */
47077   if( NEVER(pPager->errCode) ) return pPager->errCode;
47078
47079   if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
47080     pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
47081     if( pPager->pInJournal==0 ){
47082       return SQLITE_NOMEM;
47083     }
47084   
47085     /* Open the journal file if it is not already open. */
47086     if( !isOpen(pPager->jfd) ){
47087       if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
47088         sqlite3MemJournalOpen(pPager->jfd);
47089       }else{
47090         const int flags =                   /* VFS flags to open journal file */
47091           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
47092           (pPager->tempFile ? 
47093             (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
47094             (SQLITE_OPEN_MAIN_JOURNAL)
47095           );
47096
47097         /* Verify that the database still has the same name as it did when
47098         ** it was originally opened. */
47099         rc = databaseIsUnmoved(pPager);
47100         if( rc==SQLITE_OK ){
47101 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
47102           rc = sqlite3JournalOpen(
47103               pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
47104           );
47105 #else
47106           rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
47107 #endif
47108         }
47109       }
47110       assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
47111     }
47112   
47113   
47114     /* Write the first journal header to the journal file and open 
47115     ** the sub-journal if necessary.
47116     */
47117     if( rc==SQLITE_OK ){
47118       /* TODO: Check if all of these are really required. */
47119       pPager->nRec = 0;
47120       pPager->journalOff = 0;
47121       pPager->setMaster = 0;
47122       pPager->journalHdr = 0;
47123       rc = writeJournalHdr(pPager);
47124     }
47125   }
47126
47127   if( rc!=SQLITE_OK ){
47128     sqlite3BitvecDestroy(pPager->pInJournal);
47129     pPager->pInJournal = 0;
47130   }else{
47131     assert( pPager->eState==PAGER_WRITER_LOCKED );
47132     pPager->eState = PAGER_WRITER_CACHEMOD;
47133   }
47134
47135   return rc;
47136 }
47137
47138 /*
47139 ** Begin a write-transaction on the specified pager object. If a 
47140 ** write-transaction has already been opened, this function is a no-op.
47141 **
47142 ** If the exFlag argument is false, then acquire at least a RESERVED
47143 ** lock on the database file. If exFlag is true, then acquire at least
47144 ** an EXCLUSIVE lock. If such a lock is already held, no locking 
47145 ** functions need be called.
47146 **
47147 ** If the subjInMemory argument is non-zero, then any sub-journal opened
47148 ** within this transaction will be opened as an in-memory file. This
47149 ** has no effect if the sub-journal is already opened (as it may be when
47150 ** running in exclusive mode) or if the transaction does not require a
47151 ** sub-journal. If the subjInMemory argument is zero, then any required
47152 ** sub-journal is implemented in-memory if pPager is an in-memory database, 
47153 ** or using a temporary file otherwise.
47154 */
47155 SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
47156   int rc = SQLITE_OK;
47157
47158   if( pPager->errCode ) return pPager->errCode;
47159   assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
47160   pPager->subjInMemory = (u8)subjInMemory;
47161
47162   if( ALWAYS(pPager->eState==PAGER_READER) ){
47163     assert( pPager->pInJournal==0 );
47164
47165     if( pagerUseWal(pPager) ){
47166       /* If the pager is configured to use locking_mode=exclusive, and an
47167       ** exclusive lock on the database is not already held, obtain it now.
47168       */
47169       if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
47170         rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
47171         if( rc!=SQLITE_OK ){
47172           return rc;
47173         }
47174         sqlite3WalExclusiveMode(pPager->pWal, 1);
47175       }
47176
47177       /* Grab the write lock on the log file. If successful, upgrade to
47178       ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
47179       ** The busy-handler is not invoked if another connection already
47180       ** holds the write-lock. If possible, the upper layer will call it.
47181       */
47182       rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
47183     }else{
47184       /* Obtain a RESERVED lock on the database file. If the exFlag parameter
47185       ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
47186       ** busy-handler callback can be used when upgrading to the EXCLUSIVE
47187       ** lock, but not when obtaining the RESERVED lock.
47188       */
47189       rc = pagerLockDb(pPager, RESERVED_LOCK);
47190       if( rc==SQLITE_OK && exFlag ){
47191         rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
47192       }
47193     }
47194
47195     if( rc==SQLITE_OK ){
47196       /* Change to WRITER_LOCKED state.
47197       **
47198       ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
47199       ** when it has an open transaction, but never to DBMOD or FINISHED.
47200       ** This is because in those states the code to roll back savepoint 
47201       ** transactions may copy data from the sub-journal into the database 
47202       ** file as well as into the page cache. Which would be incorrect in 
47203       ** WAL mode.
47204       */
47205       pPager->eState = PAGER_WRITER_LOCKED;
47206       pPager->dbHintSize = pPager->dbSize;
47207       pPager->dbFileSize = pPager->dbSize;
47208       pPager->dbOrigSize = pPager->dbSize;
47209       pPager->journalOff = 0;
47210     }
47211
47212     assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
47213     assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
47214     assert( assert_pager_state(pPager) );
47215   }
47216
47217   PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
47218   return rc;
47219 }
47220
47221 /*
47222 ** Mark a single data page as writeable. The page is written into the 
47223 ** main journal or sub-journal as required. If the page is written into
47224 ** one of the journals, the corresponding bit is set in the 
47225 ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
47226 ** of any open savepoints as appropriate.
47227 */
47228 static int pager_write(PgHdr *pPg){
47229   Pager *pPager = pPg->pPager;
47230   int rc = SQLITE_OK;
47231   int inJournal;
47232
47233   /* This routine is not called unless a write-transaction has already 
47234   ** been started. The journal file may or may not be open at this point.
47235   ** It is never called in the ERROR state.
47236   */
47237   assert( pPager->eState==PAGER_WRITER_LOCKED
47238        || pPager->eState==PAGER_WRITER_CACHEMOD
47239        || pPager->eState==PAGER_WRITER_DBMOD
47240   );
47241   assert( assert_pager_state(pPager) );
47242   assert( pPager->errCode==0 );
47243   assert( pPager->readOnly==0 );
47244
47245   CHECK_PAGE(pPg);
47246
47247   /* The journal file needs to be opened. Higher level routines have already
47248   ** obtained the necessary locks to begin the write-transaction, but the
47249   ** rollback journal might not yet be open. Open it now if this is the case.
47250   **
47251   ** This is done before calling sqlite3PcacheMakeDirty() on the page. 
47252   ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
47253   ** an error might occur and the pager would end up in WRITER_LOCKED state
47254   ** with pages marked as dirty in the cache.
47255   */
47256   if( pPager->eState==PAGER_WRITER_LOCKED ){
47257     rc = pager_open_journal(pPager);
47258     if( rc!=SQLITE_OK ) return rc;
47259   }
47260   assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
47261   assert( assert_pager_state(pPager) );
47262
47263   /* Mark the page as dirty.  If the page has already been written
47264   ** to the journal then we can return right away.
47265   */
47266   sqlite3PcacheMakeDirty(pPg);
47267   inJournal = pageInJournal(pPager, pPg);
47268   if( inJournal && (pPager->nSavepoint==0 || !subjRequiresPage(pPg)) ){
47269     assert( !pagerUseWal(pPager) );
47270   }else{
47271   
47272     /* The transaction journal now exists and we have a RESERVED or an
47273     ** EXCLUSIVE lock on the main database file.  Write the current page to
47274     ** the transaction journal if it is not there already.
47275     */
47276     if( !inJournal && !pagerUseWal(pPager) ){
47277       assert( pagerUseWal(pPager)==0 );
47278       if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
47279         u32 cksum;
47280         char *pData2;
47281         i64 iOff = pPager->journalOff;
47282
47283         /* We should never write to the journal file the page that
47284         ** contains the database locks.  The following assert verifies
47285         ** that we do not. */
47286         assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
47287
47288         assert( pPager->journalHdr<=pPager->journalOff );
47289         CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
47290         cksum = pager_cksum(pPager, (u8*)pData2);
47291
47292         /* Even if an IO or diskfull error occurs while journalling the
47293         ** page in the block above, set the need-sync flag for the page.
47294         ** Otherwise, when the transaction is rolled back, the logic in
47295         ** playback_one_page() will think that the page needs to be restored
47296         ** in the database file. And if an IO error occurs while doing so,
47297         ** then corruption may follow.
47298         */
47299         pPg->flags |= PGHDR_NEED_SYNC;
47300
47301         rc = write32bits(pPager->jfd, iOff, pPg->pgno);
47302         if( rc!=SQLITE_OK ) return rc;
47303         rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
47304         if( rc!=SQLITE_OK ) return rc;
47305         rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
47306         if( rc!=SQLITE_OK ) return rc;
47307
47308         IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno, 
47309                  pPager->journalOff, pPager->pageSize));
47310         PAGER_INCR(sqlite3_pager_writej_count);
47311         PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
47312              PAGERID(pPager), pPg->pgno, 
47313              ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
47314
47315         pPager->journalOff += 8 + pPager->pageSize;
47316         pPager->nRec++;
47317         assert( pPager->pInJournal!=0 );
47318         rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
47319         testcase( rc==SQLITE_NOMEM );
47320         assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
47321         rc |= addToSavepointBitvecs(pPager, pPg->pgno);
47322         if( rc!=SQLITE_OK ){
47323           assert( rc==SQLITE_NOMEM );
47324           return rc;
47325         }
47326       }else{
47327         if( pPager->eState!=PAGER_WRITER_DBMOD ){
47328           pPg->flags |= PGHDR_NEED_SYNC;
47329         }
47330         PAGERTRACE(("APPEND %d page %d needSync=%d\n",
47331                 PAGERID(pPager), pPg->pgno,
47332                ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
47333       }
47334     }
47335   
47336     /* If the statement journal is open and the page is not in it,
47337     ** then write the current page to the statement journal.  Note that
47338     ** the statement journal format differs from the standard journal format
47339     ** in that it omits the checksums and the header.
47340     */
47341     if( pPager->nSavepoint>0 && subjRequiresPage(pPg) ){
47342       rc = subjournalPage(pPg);
47343     }
47344   }
47345
47346   /* Update the database size and return.
47347   */
47348   if( pPager->dbSize<pPg->pgno ){
47349     pPager->dbSize = pPg->pgno;
47350   }
47351   return rc;
47352 }
47353
47354 /*
47355 ** This is a variant of sqlite3PagerWrite() that runs when the sector size
47356 ** is larger than the page size.  SQLite makes the (reasonable) assumption that
47357 ** all bytes of a sector are written together by hardware.  Hence, all bytes of
47358 ** a sector need to be journalled in case of a power loss in the middle of
47359 ** a write.
47360 **
47361 ** Usually, the sector size is less than or equal to the page size, in which
47362 ** case pages can be individually written.  This routine only runs in the exceptional
47363 ** case where the page size is smaller than the sector size.
47364 */
47365 static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
47366   int rc = SQLITE_OK;            /* Return code */
47367   Pgno nPageCount;               /* Total number of pages in database file */
47368   Pgno pg1;                      /* First page of the sector pPg is located on. */
47369   int nPage = 0;                 /* Number of pages starting at pg1 to journal */
47370   int ii;                        /* Loop counter */
47371   int needSync = 0;              /* True if any page has PGHDR_NEED_SYNC */
47372   Pager *pPager = pPg->pPager;   /* The pager that owns pPg */
47373   Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
47374
47375   /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
47376   ** a journal header to be written between the pages journaled by
47377   ** this function.
47378   */
47379   assert( !MEMDB );
47380   assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
47381   pPager->doNotSpill |= SPILLFLAG_NOSYNC;
47382
47383   /* This trick assumes that both the page-size and sector-size are
47384   ** an integer power of 2. It sets variable pg1 to the identifier
47385   ** of the first page of the sector pPg is located on.
47386   */
47387   pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
47388
47389   nPageCount = pPager->dbSize;
47390   if( pPg->pgno>nPageCount ){
47391     nPage = (pPg->pgno - pg1)+1;
47392   }else if( (pg1+nPagePerSector-1)>nPageCount ){
47393     nPage = nPageCount+1-pg1;
47394   }else{
47395     nPage = nPagePerSector;
47396   }
47397   assert(nPage>0);
47398   assert(pg1<=pPg->pgno);
47399   assert((pg1+nPage)>pPg->pgno);
47400
47401   for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
47402     Pgno pg = pg1+ii;
47403     PgHdr *pPage;
47404     if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
47405       if( pg!=PAGER_MJ_PGNO(pPager) ){
47406         rc = sqlite3PagerGet(pPager, pg, &pPage);
47407         if( rc==SQLITE_OK ){
47408           rc = pager_write(pPage);
47409           if( pPage->flags&PGHDR_NEED_SYNC ){
47410             needSync = 1;
47411           }
47412           sqlite3PagerUnrefNotNull(pPage);
47413         }
47414       }
47415     }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
47416       if( pPage->flags&PGHDR_NEED_SYNC ){
47417         needSync = 1;
47418       }
47419       sqlite3PagerUnrefNotNull(pPage);
47420     }
47421   }
47422
47423   /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages 
47424   ** starting at pg1, then it needs to be set for all of them. Because
47425   ** writing to any of these nPage pages may damage the others, the
47426   ** journal file must contain sync()ed copies of all of them
47427   ** before any of them can be written out to the database file.
47428   */
47429   if( rc==SQLITE_OK && needSync ){
47430     assert( !MEMDB );
47431     for(ii=0; ii<nPage; ii++){
47432       PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
47433       if( pPage ){
47434         pPage->flags |= PGHDR_NEED_SYNC;
47435         sqlite3PagerUnrefNotNull(pPage);
47436       }
47437     }
47438   }
47439
47440   assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
47441   pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
47442   return rc;
47443 }
47444
47445 /*
47446 ** Mark a data page as writeable. This routine must be called before 
47447 ** making changes to a page. The caller must check the return value 
47448 ** of this function and be careful not to change any page data unless 
47449 ** this routine returns SQLITE_OK.
47450 **
47451 ** The difference between this function and pager_write() is that this
47452 ** function also deals with the special case where 2 or more pages
47453 ** fit on a single disk sector. In this case all co-resident pages
47454 ** must have been written to the journal file before returning.
47455 **
47456 ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
47457 ** as appropriate. Otherwise, SQLITE_OK.
47458 */
47459 SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
47460   assert( (pPg->flags & PGHDR_MMAP)==0 );
47461   assert( pPg->pPager->eState>=PAGER_WRITER_LOCKED );
47462   assert( pPg->pPager->eState!=PAGER_ERROR );
47463   assert( assert_pager_state(pPg->pPager) );
47464   if( pPg->pPager->sectorSize > (u32)pPg->pPager->pageSize ){
47465     return pagerWriteLargeSector(pPg);
47466   }else{
47467     return pager_write(pPg);
47468   }
47469 }
47470
47471 /*
47472 ** Return TRUE if the page given in the argument was previously passed
47473 ** to sqlite3PagerWrite().  In other words, return TRUE if it is ok
47474 ** to change the content of the page.
47475 */
47476 #ifndef NDEBUG
47477 SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
47478   return pPg->flags&PGHDR_DIRTY;
47479 }
47480 #endif
47481
47482 /*
47483 ** A call to this routine tells the pager that it is not necessary to
47484 ** write the information on page pPg back to the disk, even though
47485 ** that page might be marked as dirty.  This happens, for example, when
47486 ** the page has been added as a leaf of the freelist and so its
47487 ** content no longer matters.
47488 **
47489 ** The overlying software layer calls this routine when all of the data
47490 ** on the given page is unused. The pager marks the page as clean so
47491 ** that it does not get written to disk.
47492 **
47493 ** Tests show that this optimization can quadruple the speed of large 
47494 ** DELETE operations.
47495 */
47496 SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
47497   Pager *pPager = pPg->pPager;
47498   if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
47499     PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
47500     IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
47501     pPg->flags |= PGHDR_DONT_WRITE;
47502     pager_set_pagehash(pPg);
47503   }
47504 }
47505
47506 /*
47507 ** This routine is called to increment the value of the database file 
47508 ** change-counter, stored as a 4-byte big-endian integer starting at 
47509 ** byte offset 24 of the pager file.  The secondary change counter at
47510 ** 92 is also updated, as is the SQLite version number at offset 96.
47511 **
47512 ** But this only happens if the pPager->changeCountDone flag is false.
47513 ** To avoid excess churning of page 1, the update only happens once.
47514 ** See also the pager_write_changecounter() routine that does an 
47515 ** unconditional update of the change counters.
47516 **
47517 ** If the isDirectMode flag is zero, then this is done by calling 
47518 ** sqlite3PagerWrite() on page 1, then modifying the contents of the
47519 ** page data. In this case the file will be updated when the current
47520 ** transaction is committed.
47521 **
47522 ** The isDirectMode flag may only be non-zero if the library was compiled
47523 ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
47524 ** if isDirect is non-zero, then the database file is updated directly
47525 ** by writing an updated version of page 1 using a call to the 
47526 ** sqlite3OsWrite() function.
47527 */
47528 static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
47529   int rc = SQLITE_OK;
47530
47531   assert( pPager->eState==PAGER_WRITER_CACHEMOD
47532        || pPager->eState==PAGER_WRITER_DBMOD
47533   );
47534   assert( assert_pager_state(pPager) );
47535
47536   /* Declare and initialize constant integer 'isDirect'. If the
47537   ** atomic-write optimization is enabled in this build, then isDirect
47538   ** is initialized to the value passed as the isDirectMode parameter
47539   ** to this function. Otherwise, it is always set to zero.
47540   **
47541   ** The idea is that if the atomic-write optimization is not
47542   ** enabled at compile time, the compiler can omit the tests of
47543   ** 'isDirect' below, as well as the block enclosed in the
47544   ** "if( isDirect )" condition.
47545   */
47546 #ifndef SQLITE_ENABLE_ATOMIC_WRITE
47547 # define DIRECT_MODE 0
47548   assert( isDirectMode==0 );
47549   UNUSED_PARAMETER(isDirectMode);
47550 #else
47551 # define DIRECT_MODE isDirectMode
47552 #endif
47553
47554   if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
47555     PgHdr *pPgHdr;                /* Reference to page 1 */
47556
47557     assert( !pPager->tempFile && isOpen(pPager->fd) );
47558
47559     /* Open page 1 of the file for writing. */
47560     rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
47561     assert( pPgHdr==0 || rc==SQLITE_OK );
47562
47563     /* If page one was fetched successfully, and this function is not
47564     ** operating in direct-mode, make page 1 writable.  When not in 
47565     ** direct mode, page 1 is always held in cache and hence the PagerGet()
47566     ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
47567     */
47568     if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
47569       rc = sqlite3PagerWrite(pPgHdr);
47570     }
47571
47572     if( rc==SQLITE_OK ){
47573       /* Actually do the update of the change counter */
47574       pager_write_changecounter(pPgHdr);
47575
47576       /* If running in direct mode, write the contents of page 1 to the file. */
47577       if( DIRECT_MODE ){
47578         const void *zBuf;
47579         assert( pPager->dbFileSize>0 );
47580         CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
47581         if( rc==SQLITE_OK ){
47582           rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
47583           pPager->aStat[PAGER_STAT_WRITE]++;
47584         }
47585         if( rc==SQLITE_OK ){
47586           /* Update the pager's copy of the change-counter. Otherwise, the
47587           ** next time a read transaction is opened the cache will be
47588           ** flushed (as the change-counter values will not match).  */
47589           const void *pCopy = (const void *)&((const char *)zBuf)[24];
47590           memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
47591           pPager->changeCountDone = 1;
47592         }
47593       }else{
47594         pPager->changeCountDone = 1;
47595       }
47596     }
47597
47598     /* Release the page reference. */
47599     sqlite3PagerUnref(pPgHdr);
47600   }
47601   return rc;
47602 }
47603
47604 /*
47605 ** Sync the database file to disk. This is a no-op for in-memory databases
47606 ** or pages with the Pager.noSync flag set.
47607 **
47608 ** If successful, or if called on a pager for which it is a no-op, this
47609 ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
47610 */
47611 SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
47612   int rc = SQLITE_OK;
47613
47614   if( isOpen(pPager->fd) ){
47615     void *pArg = (void*)zMaster;
47616     rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
47617     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
47618   }
47619   if( rc==SQLITE_OK && !pPager->noSync ){
47620     assert( !MEMDB );
47621     rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
47622   }
47623   return rc;
47624 }
47625
47626 /*
47627 ** This function may only be called while a write-transaction is active in
47628 ** rollback. If the connection is in WAL mode, this call is a no-op. 
47629 ** Otherwise, if the connection does not already have an EXCLUSIVE lock on 
47630 ** the database file, an attempt is made to obtain one.
47631 **
47632 ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
47633 ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
47634 ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is 
47635 ** returned.
47636 */
47637 SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
47638   int rc = SQLITE_OK;
47639   assert( pPager->eState==PAGER_WRITER_CACHEMOD 
47640        || pPager->eState==PAGER_WRITER_DBMOD 
47641        || pPager->eState==PAGER_WRITER_LOCKED 
47642   );
47643   assert( assert_pager_state(pPager) );
47644   if( 0==pagerUseWal(pPager) ){
47645     rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
47646   }
47647   return rc;
47648 }
47649
47650 /*
47651 ** Sync the database file for the pager pPager. zMaster points to the name
47652 ** of a master journal file that should be written into the individual
47653 ** journal file. zMaster may be NULL, which is interpreted as no master
47654 ** journal (a single database transaction).
47655 **
47656 ** This routine ensures that:
47657 **
47658 **   * The database file change-counter is updated,
47659 **   * the journal is synced (unless the atomic-write optimization is used),
47660 **   * all dirty pages are written to the database file, 
47661 **   * the database file is truncated (if required), and
47662 **   * the database file synced. 
47663 **
47664 ** The only thing that remains to commit the transaction is to finalize 
47665 ** (delete, truncate or zero the first part of) the journal file (or 
47666 ** delete the master journal file if specified).
47667 **
47668 ** Note that if zMaster==NULL, this does not overwrite a previous value
47669 ** passed to an sqlite3PagerCommitPhaseOne() call.
47670 **
47671 ** If the final parameter - noSync - is true, then the database file itself
47672 ** is not synced. The caller must call sqlite3PagerSync() directly to
47673 ** sync the database file before calling CommitPhaseTwo() to delete the
47674 ** journal file in this case.
47675 */
47676 SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
47677   Pager *pPager,                  /* Pager object */
47678   const char *zMaster,            /* If not NULL, the master journal name */
47679   int noSync                      /* True to omit the xSync on the db file */
47680 ){
47681   int rc = SQLITE_OK;             /* Return code */
47682
47683   assert( pPager->eState==PAGER_WRITER_LOCKED
47684        || pPager->eState==PAGER_WRITER_CACHEMOD
47685        || pPager->eState==PAGER_WRITER_DBMOD
47686        || pPager->eState==PAGER_ERROR
47687   );
47688   assert( assert_pager_state(pPager) );
47689
47690   /* If a prior error occurred, report that error again. */
47691   if( NEVER(pPager->errCode) ) return pPager->errCode;
47692
47693   PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n", 
47694       pPager->zFilename, zMaster, pPager->dbSize));
47695
47696   /* If no database changes have been made, return early. */
47697   if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
47698
47699   if( MEMDB ){
47700     /* If this is an in-memory db, or no pages have been written to, or this
47701     ** function has already been called, it is mostly a no-op.  However, any
47702     ** backup in progress needs to be restarted.
47703     */
47704     sqlite3BackupRestart(pPager->pBackup);
47705   }else{
47706     if( pagerUseWal(pPager) ){
47707       PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
47708       PgHdr *pPageOne = 0;
47709       if( pList==0 ){
47710         /* Must have at least one page for the WAL commit flag.
47711         ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
47712         rc = sqlite3PagerGet(pPager, 1, &pPageOne);
47713         pList = pPageOne;
47714         pList->pDirty = 0;
47715       }
47716       assert( rc==SQLITE_OK );
47717       if( ALWAYS(pList) ){
47718         rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
47719       }
47720       sqlite3PagerUnref(pPageOne);
47721       if( rc==SQLITE_OK ){
47722         sqlite3PcacheCleanAll(pPager->pPCache);
47723       }
47724     }else{
47725       /* The following block updates the change-counter. Exactly how it
47726       ** does this depends on whether or not the atomic-update optimization
47727       ** was enabled at compile time, and if this transaction meets the 
47728       ** runtime criteria to use the operation: 
47729       **
47730       **    * The file-system supports the atomic-write property for
47731       **      blocks of size page-size, and 
47732       **    * This commit is not part of a multi-file transaction, and
47733       **    * Exactly one page has been modified and store in the journal file.
47734       **
47735       ** If the optimization was not enabled at compile time, then the
47736       ** pager_incr_changecounter() function is called to update the change
47737       ** counter in 'indirect-mode'. If the optimization is compiled in but
47738       ** is not applicable to this transaction, call sqlite3JournalCreate()
47739       ** to make sure the journal file has actually been created, then call
47740       ** pager_incr_changecounter() to update the change-counter in indirect
47741       ** mode. 
47742       **
47743       ** Otherwise, if the optimization is both enabled and applicable,
47744       ** then call pager_incr_changecounter() to update the change-counter
47745       ** in 'direct' mode. In this case the journal file will never be
47746       ** created for this transaction.
47747       */
47748   #ifdef SQLITE_ENABLE_ATOMIC_WRITE
47749       PgHdr *pPg;
47750       assert( isOpen(pPager->jfd) 
47751            || pPager->journalMode==PAGER_JOURNALMODE_OFF 
47752            || pPager->journalMode==PAGER_JOURNALMODE_WAL 
47753       );
47754       if( !zMaster && isOpen(pPager->jfd) 
47755        && pPager->journalOff==jrnlBufferSize(pPager) 
47756        && pPager->dbSize>=pPager->dbOrigSize
47757        && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
47758       ){
47759         /* Update the db file change counter via the direct-write method. The 
47760         ** following call will modify the in-memory representation of page 1 
47761         ** to include the updated change counter and then write page 1 
47762         ** directly to the database file. Because of the atomic-write 
47763         ** property of the host file-system, this is safe.
47764         */
47765         rc = pager_incr_changecounter(pPager, 1);
47766       }else{
47767         rc = sqlite3JournalCreate(pPager->jfd);
47768         if( rc==SQLITE_OK ){
47769           rc = pager_incr_changecounter(pPager, 0);
47770         }
47771       }
47772   #else
47773       rc = pager_incr_changecounter(pPager, 0);
47774   #endif
47775       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
47776   
47777       /* Write the master journal name into the journal file. If a master 
47778       ** journal file name has already been written to the journal file, 
47779       ** or if zMaster is NULL (no master journal), then this call is a no-op.
47780       */
47781       rc = writeMasterJournal(pPager, zMaster);
47782       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
47783   
47784       /* Sync the journal file and write all dirty pages to the database.
47785       ** If the atomic-update optimization is being used, this sync will not 
47786       ** create the journal file or perform any real IO.
47787       **
47788       ** Because the change-counter page was just modified, unless the
47789       ** atomic-update optimization is used it is almost certain that the
47790       ** journal requires a sync here. However, in locking_mode=exclusive
47791       ** on a system under memory pressure it is just possible that this is 
47792       ** not the case. In this case it is likely enough that the redundant
47793       ** xSync() call will be changed to a no-op by the OS anyhow. 
47794       */
47795       rc = syncJournal(pPager, 0);
47796       if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
47797   
47798       rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
47799       if( rc!=SQLITE_OK ){
47800         assert( rc!=SQLITE_IOERR_BLOCKED );
47801         goto commit_phase_one_exit;
47802       }
47803       sqlite3PcacheCleanAll(pPager->pPCache);
47804
47805       /* If the file on disk is smaller than the database image, use 
47806       ** pager_truncate to grow the file here. This can happen if the database
47807       ** image was extended as part of the current transaction and then the
47808       ** last page in the db image moved to the free-list. In this case the
47809       ** last page is never written out to disk, leaving the database file
47810       ** undersized. Fix this now if it is the case.  */
47811       if( pPager->dbSize>pPager->dbFileSize ){
47812         Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
47813         assert( pPager->eState==PAGER_WRITER_DBMOD );
47814         rc = pager_truncate(pPager, nNew);
47815         if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
47816       }
47817   
47818       /* Finally, sync the database file. */
47819       if( !noSync ){
47820         rc = sqlite3PagerSync(pPager, zMaster);
47821       }
47822       IOTRACE(("DBSYNC %p\n", pPager))
47823     }
47824   }
47825
47826 commit_phase_one_exit:
47827   if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
47828     pPager->eState = PAGER_WRITER_FINISHED;
47829   }
47830   return rc;
47831 }
47832
47833
47834 /*
47835 ** When this function is called, the database file has been completely
47836 ** updated to reflect the changes made by the current transaction and
47837 ** synced to disk. The journal file still exists in the file-system 
47838 ** though, and if a failure occurs at this point it will eventually
47839 ** be used as a hot-journal and the current transaction rolled back.
47840 **
47841 ** This function finalizes the journal file, either by deleting, 
47842 ** truncating or partially zeroing it, so that it cannot be used 
47843 ** for hot-journal rollback. Once this is done the transaction is
47844 ** irrevocably committed.
47845 **
47846 ** If an error occurs, an IO error code is returned and the pager
47847 ** moves into the error state. Otherwise, SQLITE_OK is returned.
47848 */
47849 SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
47850   int rc = SQLITE_OK;                  /* Return code */
47851
47852   /* This routine should not be called if a prior error has occurred.
47853   ** But if (due to a coding error elsewhere in the system) it does get
47854   ** called, just return the same error code without doing anything. */
47855   if( NEVER(pPager->errCode) ) return pPager->errCode;
47856
47857   assert( pPager->eState==PAGER_WRITER_LOCKED
47858        || pPager->eState==PAGER_WRITER_FINISHED
47859        || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
47860   );
47861   assert( assert_pager_state(pPager) );
47862
47863   /* An optimization. If the database was not actually modified during
47864   ** this transaction, the pager is running in exclusive-mode and is
47865   ** using persistent journals, then this function is a no-op.
47866   **
47867   ** The start of the journal file currently contains a single journal 
47868   ** header with the nRec field set to 0. If such a journal is used as
47869   ** a hot-journal during hot-journal rollback, 0 changes will be made
47870   ** to the database file. So there is no need to zero the journal 
47871   ** header. Since the pager is in exclusive mode, there is no need
47872   ** to drop any locks either.
47873   */
47874   if( pPager->eState==PAGER_WRITER_LOCKED 
47875    && pPager->exclusiveMode 
47876    && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
47877   ){
47878     assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
47879     pPager->eState = PAGER_READER;
47880     return SQLITE_OK;
47881   }
47882
47883   PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
47884   pPager->iDataVersion++;
47885   rc = pager_end_transaction(pPager, pPager->setMaster, 1);
47886   return pager_error(pPager, rc);
47887 }
47888
47889 /*
47890 ** If a write transaction is open, then all changes made within the 
47891 ** transaction are reverted and the current write-transaction is closed.
47892 ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
47893 ** state if an error occurs.
47894 **
47895 ** If the pager is already in PAGER_ERROR state when this function is called,
47896 ** it returns Pager.errCode immediately. No work is performed in this case.
47897 **
47898 ** Otherwise, in rollback mode, this function performs two functions:
47899 **
47900 **   1) It rolls back the journal file, restoring all database file and 
47901 **      in-memory cache pages to the state they were in when the transaction
47902 **      was opened, and
47903 **
47904 **   2) It finalizes the journal file, so that it is not used for hot
47905 **      rollback at any point in the future.
47906 **
47907 ** Finalization of the journal file (task 2) is only performed if the 
47908 ** rollback is successful.
47909 **
47910 ** In WAL mode, all cache-entries containing data modified within the
47911 ** current transaction are either expelled from the cache or reverted to
47912 ** their pre-transaction state by re-reading data from the database or
47913 ** WAL files. The WAL transaction is then closed.
47914 */
47915 SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
47916   int rc = SQLITE_OK;                  /* Return code */
47917   PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
47918
47919   /* PagerRollback() is a no-op if called in READER or OPEN state. If
47920   ** the pager is already in the ERROR state, the rollback is not 
47921   ** attempted here. Instead, the error code is returned to the caller.
47922   */
47923   assert( assert_pager_state(pPager) );
47924   if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
47925   if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
47926
47927   if( pagerUseWal(pPager) ){
47928     int rc2;
47929     rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
47930     rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
47931     if( rc==SQLITE_OK ) rc = rc2;
47932   }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
47933     int eState = pPager->eState;
47934     rc = pager_end_transaction(pPager, 0, 0);
47935     if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
47936       /* This can happen using journal_mode=off. Move the pager to the error 
47937       ** state to indicate that the contents of the cache may not be trusted.
47938       ** Any active readers will get SQLITE_ABORT.
47939       */
47940       pPager->errCode = SQLITE_ABORT;
47941       pPager->eState = PAGER_ERROR;
47942       return rc;
47943     }
47944   }else{
47945     rc = pager_playback(pPager, 0);
47946   }
47947
47948   assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
47949   assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
47950           || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR 
47951           || rc==SQLITE_CANTOPEN
47952   );
47953
47954   /* If an error occurs during a ROLLBACK, we can no longer trust the pager
47955   ** cache. So call pager_error() on the way out to make any error persistent.
47956   */
47957   return pager_error(pPager, rc);
47958 }
47959
47960 /*
47961 ** Return TRUE if the database file is opened read-only.  Return FALSE
47962 ** if the database is (in theory) writable.
47963 */
47964 SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
47965   return pPager->readOnly;
47966 }
47967
47968 /*
47969 ** Return the number of references to the pager.
47970 */
47971 SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
47972   return sqlite3PcacheRefCount(pPager->pPCache);
47973 }
47974
47975 /*
47976 ** Return the approximate number of bytes of memory currently
47977 ** used by the pager and its associated cache.
47978 */
47979 SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
47980   int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
47981                                      + 5*sizeof(void*);
47982   return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
47983            + sqlite3MallocSize(pPager)
47984            + pPager->pageSize;
47985 }
47986
47987 /*
47988 ** Return the number of references to the specified page.
47989 */
47990 SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
47991   return sqlite3PcachePageRefcount(pPage);
47992 }
47993
47994 #ifdef SQLITE_TEST
47995 /*
47996 ** This routine is used for testing and analysis only.
47997 */
47998 SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
47999   static int a[11];
48000   a[0] = sqlite3PcacheRefCount(pPager->pPCache);
48001   a[1] = sqlite3PcachePagecount(pPager->pPCache);
48002   a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
48003   a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
48004   a[4] = pPager->eState;
48005   a[5] = pPager->errCode;
48006   a[6] = pPager->aStat[PAGER_STAT_HIT];
48007   a[7] = pPager->aStat[PAGER_STAT_MISS];
48008   a[8] = 0;  /* Used to be pPager->nOvfl */
48009   a[9] = pPager->nRead;
48010   a[10] = pPager->aStat[PAGER_STAT_WRITE];
48011   return a;
48012 }
48013 #endif
48014
48015 /*
48016 ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
48017 ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
48018 ** current cache hit or miss count, according to the value of eStat. If the 
48019 ** reset parameter is non-zero, the cache hit or miss count is zeroed before 
48020 ** returning.
48021 */
48022 SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
48023
48024   assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
48025        || eStat==SQLITE_DBSTATUS_CACHE_MISS
48026        || eStat==SQLITE_DBSTATUS_CACHE_WRITE
48027   );
48028
48029   assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
48030   assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
48031   assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
48032
48033   *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
48034   if( reset ){
48035     pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
48036   }
48037 }
48038
48039 /*
48040 ** Return true if this is an in-memory pager.
48041 */
48042 SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
48043   return MEMDB;
48044 }
48045
48046 /*
48047 ** Check that there are at least nSavepoint savepoints open. If there are
48048 ** currently less than nSavepoints open, then open one or more savepoints
48049 ** to make up the difference. If the number of savepoints is already
48050 ** equal to nSavepoint, then this function is a no-op.
48051 **
48052 ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error 
48053 ** occurs while opening the sub-journal file, then an IO error code is
48054 ** returned. Otherwise, SQLITE_OK.
48055 */
48056 SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
48057   int rc = SQLITE_OK;                       /* Return code */
48058   int nCurrent = pPager->nSavepoint;        /* Current number of savepoints */
48059
48060   assert( pPager->eState>=PAGER_WRITER_LOCKED );
48061   assert( assert_pager_state(pPager) );
48062
48063   if( nSavepoint>nCurrent && pPager->useJournal ){
48064     int ii;                                 /* Iterator variable */
48065     PagerSavepoint *aNew;                   /* New Pager.aSavepoint array */
48066
48067     /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
48068     ** if the allocation fails. Otherwise, zero the new portion in case a 
48069     ** malloc failure occurs while populating it in the for(...) loop below.
48070     */
48071     aNew = (PagerSavepoint *)sqlite3Realloc(
48072         pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
48073     );
48074     if( !aNew ){
48075       return SQLITE_NOMEM;
48076     }
48077     memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
48078     pPager->aSavepoint = aNew;
48079
48080     /* Populate the PagerSavepoint structures just allocated. */
48081     for(ii=nCurrent; ii<nSavepoint; ii++){
48082       aNew[ii].nOrig = pPager->dbSize;
48083       if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
48084         aNew[ii].iOffset = pPager->journalOff;
48085       }else{
48086         aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
48087       }
48088       aNew[ii].iSubRec = pPager->nSubRec;
48089       aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
48090       if( !aNew[ii].pInSavepoint ){
48091         return SQLITE_NOMEM;
48092       }
48093       if( pagerUseWal(pPager) ){
48094         sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
48095       }
48096       pPager->nSavepoint = ii+1;
48097     }
48098     assert( pPager->nSavepoint==nSavepoint );
48099     assertTruncateConstraint(pPager);
48100   }
48101
48102   return rc;
48103 }
48104
48105 /*
48106 ** This function is called to rollback or release (commit) a savepoint.
48107 ** The savepoint to release or rollback need not be the most recently 
48108 ** created savepoint.
48109 **
48110 ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
48111 ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
48112 ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
48113 ** that have occurred since the specified savepoint was created.
48114 **
48115 ** The savepoint to rollback or release is identified by parameter 
48116 ** iSavepoint. A value of 0 means to operate on the outermost savepoint
48117 ** (the first created). A value of (Pager.nSavepoint-1) means operate
48118 ** on the most recently created savepoint. If iSavepoint is greater than
48119 ** (Pager.nSavepoint-1), then this function is a no-op.
48120 **
48121 ** If a negative value is passed to this function, then the current
48122 ** transaction is rolled back. This is different to calling 
48123 ** sqlite3PagerRollback() because this function does not terminate
48124 ** the transaction or unlock the database, it just restores the 
48125 ** contents of the database to its original state. 
48126 **
48127 ** In any case, all savepoints with an index greater than iSavepoint 
48128 ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
48129 ** then savepoint iSavepoint is also destroyed.
48130 **
48131 ** This function may return SQLITE_NOMEM if a memory allocation fails,
48132 ** or an IO error code if an IO error occurs while rolling back a 
48133 ** savepoint. If no errors occur, SQLITE_OK is returned.
48134 */ 
48135 SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
48136   int rc = pPager->errCode;       /* Return code */
48137
48138   assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
48139   assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
48140
48141   if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
48142     int ii;            /* Iterator variable */
48143     int nNew;          /* Number of remaining savepoints after this op. */
48144
48145     /* Figure out how many savepoints will still be active after this
48146     ** operation. Store this value in nNew. Then free resources associated 
48147     ** with any savepoints that are destroyed by this operation.
48148     */
48149     nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
48150     for(ii=nNew; ii<pPager->nSavepoint; ii++){
48151       sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
48152     }
48153     pPager->nSavepoint = nNew;
48154
48155     /* If this is a release of the outermost savepoint, truncate 
48156     ** the sub-journal to zero bytes in size. */
48157     if( op==SAVEPOINT_RELEASE ){
48158       if( nNew==0 && isOpen(pPager->sjfd) ){
48159         /* Only truncate if it is an in-memory sub-journal. */
48160         if( sqlite3IsMemJournal(pPager->sjfd) ){
48161           rc = sqlite3OsTruncate(pPager->sjfd, 0);
48162           assert( rc==SQLITE_OK );
48163         }
48164         pPager->nSubRec = 0;
48165       }
48166     }
48167     /* Else this is a rollback operation, playback the specified savepoint.
48168     ** If this is a temp-file, it is possible that the journal file has
48169     ** not yet been opened. In this case there have been no changes to
48170     ** the database file, so the playback operation can be skipped.
48171     */
48172     else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
48173       PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
48174       rc = pagerPlaybackSavepoint(pPager, pSavepoint);
48175       assert(rc!=SQLITE_DONE);
48176     }
48177   }
48178
48179   return rc;
48180 }
48181
48182 /*
48183 ** Return the full pathname of the database file.
48184 **
48185 ** Except, if the pager is in-memory only, then return an empty string if
48186 ** nullIfMemDb is true.  This routine is called with nullIfMemDb==1 when
48187 ** used to report the filename to the user, for compatibility with legacy
48188 ** behavior.  But when the Btree needs to know the filename for matching to
48189 ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
48190 ** participate in shared-cache.
48191 */
48192 SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
48193   return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
48194 }
48195
48196 /*
48197 ** Return the VFS structure for the pager.
48198 */
48199 SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
48200   return pPager->pVfs;
48201 }
48202
48203 /*
48204 ** Return the file handle for the database file associated
48205 ** with the pager.  This might return NULL if the file has
48206 ** not yet been opened.
48207 */
48208 SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
48209   return pPager->fd;
48210 }
48211
48212 /*
48213 ** Return the full pathname of the journal file.
48214 */
48215 SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
48216   return pPager->zJournal;
48217 }
48218
48219 /*
48220 ** Return true if fsync() calls are disabled for this pager.  Return FALSE
48221 ** if fsync()s are executed normally.
48222 */
48223 SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
48224   return pPager->noSync;
48225 }
48226
48227 #ifdef SQLITE_HAS_CODEC
48228 /*
48229 ** Set or retrieve the codec for this pager
48230 */
48231 SQLITE_PRIVATE void sqlite3PagerSetCodec(
48232   Pager *pPager,
48233   void *(*xCodec)(void*,void*,Pgno,int),
48234   void (*xCodecSizeChng)(void*,int,int),
48235   void (*xCodecFree)(void*),
48236   void *pCodec
48237 ){
48238   if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
48239   pPager->xCodec = pPager->memDb ? 0 : xCodec;
48240   pPager->xCodecSizeChng = xCodecSizeChng;
48241   pPager->xCodecFree = xCodecFree;
48242   pPager->pCodec = pCodec;
48243   pagerReportSize(pPager);
48244 }
48245 SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
48246   return pPager->pCodec;
48247 }
48248
48249 /*
48250 ** This function is called by the wal module when writing page content
48251 ** into the log file.
48252 **
48253 ** This function returns a pointer to a buffer containing the encrypted
48254 ** page content. If a malloc fails, this function may return NULL.
48255 */
48256 SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
48257   void *aData = 0;
48258   CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
48259   return aData;
48260 }
48261
48262 /*
48263 ** Return the current pager state
48264 */
48265 SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
48266   return pPager->eState;
48267 }
48268 #endif /* SQLITE_HAS_CODEC */
48269
48270 #ifndef SQLITE_OMIT_AUTOVACUUM
48271 /*
48272 ** Move the page pPg to location pgno in the file.
48273 **
48274 ** There must be no references to the page previously located at
48275 ** pgno (which we call pPgOld) though that page is allowed to be
48276 ** in cache.  If the page previously located at pgno is not already
48277 ** in the rollback journal, it is not put there by by this routine.
48278 **
48279 ** References to the page pPg remain valid. Updating any
48280 ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
48281 ** allocated along with the page) is the responsibility of the caller.
48282 **
48283 ** A transaction must be active when this routine is called. It used to be
48284 ** required that a statement transaction was not active, but this restriction
48285 ** has been removed (CREATE INDEX needs to move a page when a statement
48286 ** transaction is active).
48287 **
48288 ** If the fourth argument, isCommit, is non-zero, then this page is being
48289 ** moved as part of a database reorganization just before the transaction 
48290 ** is being committed. In this case, it is guaranteed that the database page 
48291 ** pPg refers to will not be written to again within this transaction.
48292 **
48293 ** This function may return SQLITE_NOMEM or an IO error code if an error
48294 ** occurs. Otherwise, it returns SQLITE_OK.
48295 */
48296 SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
48297   PgHdr *pPgOld;               /* The page being overwritten. */
48298   Pgno needSyncPgno = 0;       /* Old value of pPg->pgno, if sync is required */
48299   int rc;                      /* Return code */
48300   Pgno origPgno;               /* The original page number */
48301
48302   assert( pPg->nRef>0 );
48303   assert( pPager->eState==PAGER_WRITER_CACHEMOD
48304        || pPager->eState==PAGER_WRITER_DBMOD
48305   );
48306   assert( assert_pager_state(pPager) );
48307
48308   /* In order to be able to rollback, an in-memory database must journal
48309   ** the page we are moving from.
48310   */
48311   if( MEMDB ){
48312     rc = sqlite3PagerWrite(pPg);
48313     if( rc ) return rc;
48314   }
48315
48316   /* If the page being moved is dirty and has not been saved by the latest
48317   ** savepoint, then save the current contents of the page into the 
48318   ** sub-journal now. This is required to handle the following scenario:
48319   **
48320   **   BEGIN;
48321   **     <journal page X, then modify it in memory>
48322   **     SAVEPOINT one;
48323   **       <Move page X to location Y>
48324   **     ROLLBACK TO one;
48325   **
48326   ** If page X were not written to the sub-journal here, it would not
48327   ** be possible to restore its contents when the "ROLLBACK TO one"
48328   ** statement were is processed.
48329   **
48330   ** subjournalPage() may need to allocate space to store pPg->pgno into
48331   ** one or more savepoint bitvecs. This is the reason this function
48332   ** may return SQLITE_NOMEM.
48333   */
48334   if( pPg->flags&PGHDR_DIRTY
48335    && subjRequiresPage(pPg)
48336    && SQLITE_OK!=(rc = subjournalPage(pPg))
48337   ){
48338     return rc;
48339   }
48340
48341   PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n", 
48342       PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
48343   IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
48344
48345   /* If the journal needs to be sync()ed before page pPg->pgno can
48346   ** be written to, store pPg->pgno in local variable needSyncPgno.
48347   **
48348   ** If the isCommit flag is set, there is no need to remember that
48349   ** the journal needs to be sync()ed before database page pPg->pgno 
48350   ** can be written to. The caller has already promised not to write to it.
48351   */
48352   if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
48353     needSyncPgno = pPg->pgno;
48354     assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
48355             pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
48356     assert( pPg->flags&PGHDR_DIRTY );
48357   }
48358
48359   /* If the cache contains a page with page-number pgno, remove it
48360   ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for 
48361   ** page pgno before the 'move' operation, it needs to be retained 
48362   ** for the page moved there.
48363   */
48364   pPg->flags &= ~PGHDR_NEED_SYNC;
48365   pPgOld = sqlite3PagerLookup(pPager, pgno);
48366   assert( !pPgOld || pPgOld->nRef==1 );
48367   if( pPgOld ){
48368     pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
48369     if( MEMDB ){
48370       /* Do not discard pages from an in-memory database since we might
48371       ** need to rollback later.  Just move the page out of the way. */
48372       sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
48373     }else{
48374       sqlite3PcacheDrop(pPgOld);
48375     }
48376   }
48377
48378   origPgno = pPg->pgno;
48379   sqlite3PcacheMove(pPg, pgno);
48380   sqlite3PcacheMakeDirty(pPg);
48381
48382   /* For an in-memory database, make sure the original page continues
48383   ** to exist, in case the transaction needs to roll back.  Use pPgOld
48384   ** as the original page since it has already been allocated.
48385   */
48386   if( MEMDB ){
48387     assert( pPgOld );
48388     sqlite3PcacheMove(pPgOld, origPgno);
48389     sqlite3PagerUnrefNotNull(pPgOld);
48390   }
48391
48392   if( needSyncPgno ){
48393     /* If needSyncPgno is non-zero, then the journal file needs to be 
48394     ** sync()ed before any data is written to database file page needSyncPgno.
48395     ** Currently, no such page exists in the page-cache and the 
48396     ** "is journaled" bitvec flag has been set. This needs to be remedied by
48397     ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
48398     ** flag.
48399     **
48400     ** If the attempt to load the page into the page-cache fails, (due
48401     ** to a malloc() or IO failure), clear the bit in the pInJournal[]
48402     ** array. Otherwise, if the page is loaded and written again in
48403     ** this transaction, it may be written to the database file before
48404     ** it is synced into the journal file. This way, it may end up in
48405     ** the journal file twice, but that is not a problem.
48406     */
48407     PgHdr *pPgHdr;
48408     rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
48409     if( rc!=SQLITE_OK ){
48410       if( needSyncPgno<=pPager->dbOrigSize ){
48411         assert( pPager->pTmpSpace!=0 );
48412         sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
48413       }
48414       return rc;
48415     }
48416     pPgHdr->flags |= PGHDR_NEED_SYNC;
48417     sqlite3PcacheMakeDirty(pPgHdr);
48418     sqlite3PagerUnrefNotNull(pPgHdr);
48419   }
48420
48421   return SQLITE_OK;
48422 }
48423 #endif
48424
48425 /*
48426 ** The page handle passed as the first argument refers to a dirty page 
48427 ** with a page number other than iNew. This function changes the page's 
48428 ** page number to iNew and sets the value of the PgHdr.flags field to 
48429 ** the value passed as the third parameter.
48430 */
48431 SQLITE_PRIVATE void sqlite3PagerRekey(DbPage *pPg, Pgno iNew, u16 flags){
48432   assert( pPg->pgno!=iNew );
48433   pPg->flags = flags;
48434   sqlite3PcacheMove(pPg, iNew);
48435 }
48436
48437 /*
48438 ** Return a pointer to the data for the specified page.
48439 */
48440 SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
48441   assert( pPg->nRef>0 || pPg->pPager->memDb );
48442   return pPg->pData;
48443 }
48444
48445 /*
48446 ** Return a pointer to the Pager.nExtra bytes of "extra" space 
48447 ** allocated along with the specified page.
48448 */
48449 SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
48450   return pPg->pExtra;
48451 }
48452
48453 /*
48454 ** Get/set the locking-mode for this pager. Parameter eMode must be one
48455 ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or 
48456 ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
48457 ** the locking-mode is set to the value specified.
48458 **
48459 ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
48460 ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
48461 ** locking-mode.
48462 */
48463 SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
48464   assert( eMode==PAGER_LOCKINGMODE_QUERY
48465             || eMode==PAGER_LOCKINGMODE_NORMAL
48466             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
48467   assert( PAGER_LOCKINGMODE_QUERY<0 );
48468   assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
48469   assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
48470   if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
48471     pPager->exclusiveMode = (u8)eMode;
48472   }
48473   return (int)pPager->exclusiveMode;
48474 }
48475
48476 /*
48477 ** Set the journal-mode for this pager. Parameter eMode must be one of:
48478 **
48479 **    PAGER_JOURNALMODE_DELETE
48480 **    PAGER_JOURNALMODE_TRUNCATE
48481 **    PAGER_JOURNALMODE_PERSIST
48482 **    PAGER_JOURNALMODE_OFF
48483 **    PAGER_JOURNALMODE_MEMORY
48484 **    PAGER_JOURNALMODE_WAL
48485 **
48486 ** The journalmode is set to the value specified if the change is allowed.
48487 ** The change may be disallowed for the following reasons:
48488 **
48489 **   *  An in-memory database can only have its journal_mode set to _OFF
48490 **      or _MEMORY.
48491 **
48492 **   *  Temporary databases cannot have _WAL journalmode.
48493 **
48494 ** The returned indicate the current (possibly updated) journal-mode.
48495 */
48496 SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
48497   u8 eOld = pPager->journalMode;    /* Prior journalmode */
48498
48499 #ifdef SQLITE_DEBUG
48500   /* The print_pager_state() routine is intended to be used by the debugger
48501   ** only.  We invoke it once here to suppress a compiler warning. */
48502   print_pager_state(pPager);
48503 #endif
48504
48505
48506   /* The eMode parameter is always valid */
48507   assert(      eMode==PAGER_JOURNALMODE_DELETE
48508             || eMode==PAGER_JOURNALMODE_TRUNCATE
48509             || eMode==PAGER_JOURNALMODE_PERSIST
48510             || eMode==PAGER_JOURNALMODE_OFF 
48511             || eMode==PAGER_JOURNALMODE_WAL 
48512             || eMode==PAGER_JOURNALMODE_MEMORY );
48513
48514   /* This routine is only called from the OP_JournalMode opcode, and
48515   ** the logic there will never allow a temporary file to be changed
48516   ** to WAL mode.
48517   */
48518   assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
48519
48520   /* Do allow the journalmode of an in-memory database to be set to
48521   ** anything other than MEMORY or OFF
48522   */
48523   if( MEMDB ){
48524     assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
48525     if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
48526       eMode = eOld;
48527     }
48528   }
48529
48530   if( eMode!=eOld ){
48531
48532     /* Change the journal mode. */
48533     assert( pPager->eState!=PAGER_ERROR );
48534     pPager->journalMode = (u8)eMode;
48535
48536     /* When transistioning from TRUNCATE or PERSIST to any other journal
48537     ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
48538     ** delete the journal file.
48539     */
48540     assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
48541     assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
48542     assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
48543     assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
48544     assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
48545     assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
48546
48547     assert( isOpen(pPager->fd) || pPager->exclusiveMode );
48548     if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
48549
48550       /* In this case we would like to delete the journal file. If it is
48551       ** not possible, then that is not a problem. Deleting the journal file
48552       ** here is an optimization only.
48553       **
48554       ** Before deleting the journal file, obtain a RESERVED lock on the
48555       ** database file. This ensures that the journal file is not deleted
48556       ** while it is in use by some other client.
48557       */
48558       sqlite3OsClose(pPager->jfd);
48559       if( pPager->eLock>=RESERVED_LOCK ){
48560         sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
48561       }else{
48562         int rc = SQLITE_OK;
48563         int state = pPager->eState;
48564         assert( state==PAGER_OPEN || state==PAGER_READER );
48565         if( state==PAGER_OPEN ){
48566           rc = sqlite3PagerSharedLock(pPager);
48567         }
48568         if( pPager->eState==PAGER_READER ){
48569           assert( rc==SQLITE_OK );
48570           rc = pagerLockDb(pPager, RESERVED_LOCK);
48571         }
48572         if( rc==SQLITE_OK ){
48573           sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
48574         }
48575         if( rc==SQLITE_OK && state==PAGER_READER ){
48576           pagerUnlockDb(pPager, SHARED_LOCK);
48577         }else if( state==PAGER_OPEN ){
48578           pager_unlock(pPager);
48579         }
48580         assert( state==pPager->eState );
48581       }
48582     }
48583   }
48584
48585   /* Return the new journal mode */
48586   return (int)pPager->journalMode;
48587 }
48588
48589 /*
48590 ** Return the current journal mode.
48591 */
48592 SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
48593   return (int)pPager->journalMode;
48594 }
48595
48596 /*
48597 ** Return TRUE if the pager is in a state where it is OK to change the
48598 ** journalmode.  Journalmode changes can only happen when the database
48599 ** is unmodified.
48600 */
48601 SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
48602   assert( assert_pager_state(pPager) );
48603   if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
48604   if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
48605   return 1;
48606 }
48607
48608 /*
48609 ** Get/set the size-limit used for persistent journal files.
48610 **
48611 ** Setting the size limit to -1 means no limit is enforced.
48612 ** An attempt to set a limit smaller than -1 is a no-op.
48613 */
48614 SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
48615   if( iLimit>=-1 ){
48616     pPager->journalSizeLimit = iLimit;
48617     sqlite3WalLimit(pPager->pWal, iLimit);
48618   }
48619   return pPager->journalSizeLimit;
48620 }
48621
48622 /*
48623 ** Return a pointer to the pPager->pBackup variable. The backup module
48624 ** in backup.c maintains the content of this variable. This module
48625 ** uses it opaquely as an argument to sqlite3BackupRestart() and
48626 ** sqlite3BackupUpdate() only.
48627 */
48628 SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
48629   return &pPager->pBackup;
48630 }
48631
48632 #ifndef SQLITE_OMIT_VACUUM
48633 /*
48634 ** Unless this is an in-memory or temporary database, clear the pager cache.
48635 */
48636 SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
48637   if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
48638 }
48639 #endif
48640
48641 #ifndef SQLITE_OMIT_WAL
48642 /*
48643 ** This function is called when the user invokes "PRAGMA wal_checkpoint",
48644 ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
48645 ** or wal_blocking_checkpoint() API functions.
48646 **
48647 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
48648 */
48649 SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
48650   int rc = SQLITE_OK;
48651   if( pPager->pWal ){
48652     rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
48653         (eMode==SQLITE_CHECKPOINT_PASSIVE ? 0 : pPager->xBusyHandler),
48654         pPager->pBusyHandlerArg,
48655         pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
48656         pnLog, pnCkpt
48657     );
48658   }
48659   return rc;
48660 }
48661
48662 SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
48663   return sqlite3WalCallback(pPager->pWal);
48664 }
48665
48666 /*
48667 ** Return true if the underlying VFS for the given pager supports the
48668 ** primitives necessary for write-ahead logging.
48669 */
48670 SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
48671   const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
48672   return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
48673 }
48674
48675 /*
48676 ** Attempt to take an exclusive lock on the database file. If a PENDING lock
48677 ** is obtained instead, immediately release it.
48678 */
48679 static int pagerExclusiveLock(Pager *pPager){
48680   int rc;                         /* Return code */
48681
48682   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
48683   rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
48684   if( rc!=SQLITE_OK ){
48685     /* If the attempt to grab the exclusive lock failed, release the 
48686     ** pending lock that may have been obtained instead.  */
48687     pagerUnlockDb(pPager, SHARED_LOCK);
48688   }
48689
48690   return rc;
48691 }
48692
48693 /*
48694 ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in 
48695 ** exclusive-locking mode when this function is called, take an EXCLUSIVE
48696 ** lock on the database file and use heap-memory to store the wal-index
48697 ** in. Otherwise, use the normal shared-memory.
48698 */
48699 static int pagerOpenWal(Pager *pPager){
48700   int rc = SQLITE_OK;
48701
48702   assert( pPager->pWal==0 && pPager->tempFile==0 );
48703   assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
48704
48705   /* If the pager is already in exclusive-mode, the WAL module will use 
48706   ** heap-memory for the wal-index instead of the VFS shared-memory 
48707   ** implementation. Take the exclusive lock now, before opening the WAL
48708   ** file, to make sure this is safe.
48709   */
48710   if( pPager->exclusiveMode ){
48711     rc = pagerExclusiveLock(pPager);
48712   }
48713
48714   /* Open the connection to the log file. If this operation fails, 
48715   ** (e.g. due to malloc() failure), return an error code.
48716   */
48717   if( rc==SQLITE_OK ){
48718     rc = sqlite3WalOpen(pPager->pVfs,
48719         pPager->fd, pPager->zWal, pPager->exclusiveMode,
48720         pPager->journalSizeLimit, &pPager->pWal
48721     );
48722   }
48723   pagerFixMaplimit(pPager);
48724
48725   return rc;
48726 }
48727
48728
48729 /*
48730 ** The caller must be holding a SHARED lock on the database file to call
48731 ** this function.
48732 **
48733 ** If the pager passed as the first argument is open on a real database
48734 ** file (not a temp file or an in-memory database), and the WAL file
48735 ** is not already open, make an attempt to open it now. If successful,
48736 ** return SQLITE_OK. If an error occurs or the VFS used by the pager does 
48737 ** not support the xShmXXX() methods, return an error code. *pbOpen is
48738 ** not modified in either case.
48739 **
48740 ** If the pager is open on a temp-file (or in-memory database), or if
48741 ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
48742 ** without doing anything.
48743 */
48744 SQLITE_PRIVATE int sqlite3PagerOpenWal(
48745   Pager *pPager,                  /* Pager object */
48746   int *pbOpen                     /* OUT: Set to true if call is a no-op */
48747 ){
48748   int rc = SQLITE_OK;             /* Return code */
48749
48750   assert( assert_pager_state(pPager) );
48751   assert( pPager->eState==PAGER_OPEN   || pbOpen );
48752   assert( pPager->eState==PAGER_READER || !pbOpen );
48753   assert( pbOpen==0 || *pbOpen==0 );
48754   assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
48755
48756   if( !pPager->tempFile && !pPager->pWal ){
48757     if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
48758
48759     /* Close any rollback journal previously open */
48760     sqlite3OsClose(pPager->jfd);
48761
48762     rc = pagerOpenWal(pPager);
48763     if( rc==SQLITE_OK ){
48764       pPager->journalMode = PAGER_JOURNALMODE_WAL;
48765       pPager->eState = PAGER_OPEN;
48766     }
48767   }else{
48768     *pbOpen = 1;
48769   }
48770
48771   return rc;
48772 }
48773
48774 /*
48775 ** This function is called to close the connection to the log file prior
48776 ** to switching from WAL to rollback mode.
48777 **
48778 ** Before closing the log file, this function attempts to take an 
48779 ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
48780 ** error (SQLITE_BUSY) is returned and the log connection is not closed.
48781 ** If successful, the EXCLUSIVE lock is not released before returning.
48782 */
48783 SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
48784   int rc = SQLITE_OK;
48785
48786   assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
48787
48788   /* If the log file is not already open, but does exist in the file-system,
48789   ** it may need to be checkpointed before the connection can switch to
48790   ** rollback mode. Open it now so this can happen.
48791   */
48792   if( !pPager->pWal ){
48793     int logexists = 0;
48794     rc = pagerLockDb(pPager, SHARED_LOCK);
48795     if( rc==SQLITE_OK ){
48796       rc = sqlite3OsAccess(
48797           pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
48798       );
48799     }
48800     if( rc==SQLITE_OK && logexists ){
48801       rc = pagerOpenWal(pPager);
48802     }
48803   }
48804     
48805   /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
48806   ** the database file, the log and log-summary files will be deleted.
48807   */
48808   if( rc==SQLITE_OK && pPager->pWal ){
48809     rc = pagerExclusiveLock(pPager);
48810     if( rc==SQLITE_OK ){
48811       rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
48812                            pPager->pageSize, (u8*)pPager->pTmpSpace);
48813       pPager->pWal = 0;
48814       pagerFixMaplimit(pPager);
48815     }
48816   }
48817   return rc;
48818 }
48819
48820 #endif /* !SQLITE_OMIT_WAL */
48821
48822 #ifdef SQLITE_ENABLE_ZIPVFS
48823 /*
48824 ** A read-lock must be held on the pager when this function is called. If
48825 ** the pager is in WAL mode and the WAL file currently contains one or more
48826 ** frames, return the size in bytes of the page images stored within the
48827 ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
48828 ** is empty, return 0.
48829 */
48830 SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
48831   assert( pPager->eState>=PAGER_READER );
48832   return sqlite3WalFramesize(pPager->pWal);
48833 }
48834 #endif
48835
48836
48837 #endif /* SQLITE_OMIT_DISKIO */
48838
48839 /************** End of pager.c ***********************************************/
48840 /************** Begin file wal.c *********************************************/
48841 /*
48842 ** 2010 February 1
48843 **
48844 ** The author disclaims copyright to this source code.  In place of
48845 ** a legal notice, here is a blessing:
48846 **
48847 **    May you do good and not evil.
48848 **    May you find forgiveness for yourself and forgive others.
48849 **    May you share freely, never taking more than you give.
48850 **
48851 *************************************************************************
48852 **
48853 ** This file contains the implementation of a write-ahead log (WAL) used in 
48854 ** "journal_mode=WAL" mode.
48855 **
48856 ** WRITE-AHEAD LOG (WAL) FILE FORMAT
48857 **
48858 ** A WAL file consists of a header followed by zero or more "frames".
48859 ** Each frame records the revised content of a single page from the
48860 ** database file.  All changes to the database are recorded by writing
48861 ** frames into the WAL.  Transactions commit when a frame is written that
48862 ** contains a commit marker.  A single WAL can and usually does record 
48863 ** multiple transactions.  Periodically, the content of the WAL is
48864 ** transferred back into the database file in an operation called a
48865 ** "checkpoint".
48866 **
48867 ** A single WAL file can be used multiple times.  In other words, the
48868 ** WAL can fill up with frames and then be checkpointed and then new
48869 ** frames can overwrite the old ones.  A WAL always grows from beginning
48870 ** toward the end.  Checksums and counters attached to each frame are
48871 ** used to determine which frames within the WAL are valid and which
48872 ** are leftovers from prior checkpoints.
48873 **
48874 ** The WAL header is 32 bytes in size and consists of the following eight
48875 ** big-endian 32-bit unsigned integer values:
48876 **
48877 **     0: Magic number.  0x377f0682 or 0x377f0683
48878 **     4: File format version.  Currently 3007000
48879 **     8: Database page size.  Example: 1024
48880 **    12: Checkpoint sequence number
48881 **    16: Salt-1, random integer incremented with each checkpoint
48882 **    20: Salt-2, a different random integer changing with each ckpt
48883 **    24: Checksum-1 (first part of checksum for first 24 bytes of header).
48884 **    28: Checksum-2 (second part of checksum for first 24 bytes of header).
48885 **
48886 ** Immediately following the wal-header are zero or more frames. Each
48887 ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
48888 ** of page data. The frame-header is six big-endian 32-bit unsigned 
48889 ** integer values, as follows:
48890 **
48891 **     0: Page number.
48892 **     4: For commit records, the size of the database image in pages 
48893 **        after the commit. For all other records, zero.
48894 **     8: Salt-1 (copied from the header)
48895 **    12: Salt-2 (copied from the header)
48896 **    16: Checksum-1.
48897 **    20: Checksum-2.
48898 **
48899 ** A frame is considered valid if and only if the following conditions are
48900 ** true:
48901 **
48902 **    (1) The salt-1 and salt-2 values in the frame-header match
48903 **        salt values in the wal-header
48904 **
48905 **    (2) The checksum values in the final 8 bytes of the frame-header
48906 **        exactly match the checksum computed consecutively on the
48907 **        WAL header and the first 8 bytes and the content of all frames
48908 **        up to and including the current frame.
48909 **
48910 ** The checksum is computed using 32-bit big-endian integers if the
48911 ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
48912 ** is computed using little-endian if the magic number is 0x377f0682.
48913 ** The checksum values are always stored in the frame header in a
48914 ** big-endian format regardless of which byte order is used to compute
48915 ** the checksum.  The checksum is computed by interpreting the input as
48916 ** an even number of unsigned 32-bit integers: x[0] through x[N].  The
48917 ** algorithm used for the checksum is as follows:
48918 ** 
48919 **   for i from 0 to n-1 step 2:
48920 **     s0 += x[i] + s1;
48921 **     s1 += x[i+1] + s0;
48922 **   endfor
48923 **
48924 ** Note that s0 and s1 are both weighted checksums using fibonacci weights
48925 ** in reverse order (the largest fibonacci weight occurs on the first element
48926 ** of the sequence being summed.)  The s1 value spans all 32-bit 
48927 ** terms of the sequence whereas s0 omits the final term.
48928 **
48929 ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
48930 ** WAL is transferred into the database, then the database is VFS.xSync-ed.
48931 ** The VFS.xSync operations serve as write barriers - all writes launched
48932 ** before the xSync must complete before any write that launches after the
48933 ** xSync begins.
48934 **
48935 ** After each checkpoint, the salt-1 value is incremented and the salt-2
48936 ** value is randomized.  This prevents old and new frames in the WAL from
48937 ** being considered valid at the same time and being checkpointing together
48938 ** following a crash.
48939 **
48940 ** READER ALGORITHM
48941 **
48942 ** To read a page from the database (call it page number P), a reader
48943 ** first checks the WAL to see if it contains page P.  If so, then the
48944 ** last valid instance of page P that is a followed by a commit frame
48945 ** or is a commit frame itself becomes the value read.  If the WAL
48946 ** contains no copies of page P that are valid and which are a commit
48947 ** frame or are followed by a commit frame, then page P is read from
48948 ** the database file.
48949 **
48950 ** To start a read transaction, the reader records the index of the last
48951 ** valid frame in the WAL.  The reader uses this recorded "mxFrame" value
48952 ** for all subsequent read operations.  New transactions can be appended
48953 ** to the WAL, but as long as the reader uses its original mxFrame value
48954 ** and ignores the newly appended content, it will see a consistent snapshot
48955 ** of the database from a single point in time.  This technique allows
48956 ** multiple concurrent readers to view different versions of the database
48957 ** content simultaneously.
48958 **
48959 ** The reader algorithm in the previous paragraphs works correctly, but 
48960 ** because frames for page P can appear anywhere within the WAL, the
48961 ** reader has to scan the entire WAL looking for page P frames.  If the
48962 ** WAL is large (multiple megabytes is typical) that scan can be slow,
48963 ** and read performance suffers.  To overcome this problem, a separate
48964 ** data structure called the wal-index is maintained to expedite the
48965 ** search for frames of a particular page.
48966 ** 
48967 ** WAL-INDEX FORMAT
48968 **
48969 ** Conceptually, the wal-index is shared memory, though VFS implementations
48970 ** might choose to implement the wal-index using a mmapped file.  Because
48971 ** the wal-index is shared memory, SQLite does not support journal_mode=WAL 
48972 ** on a network filesystem.  All users of the database must be able to
48973 ** share memory.
48974 **
48975 ** The wal-index is transient.  After a crash, the wal-index can (and should
48976 ** be) reconstructed from the original WAL file.  In fact, the VFS is required
48977 ** to either truncate or zero the header of the wal-index when the last
48978 ** connection to it closes.  Because the wal-index is transient, it can
48979 ** use an architecture-specific format; it does not have to be cross-platform.
48980 ** Hence, unlike the database and WAL file formats which store all values
48981 ** as big endian, the wal-index can store multi-byte values in the native
48982 ** byte order of the host computer.
48983 **
48984 ** The purpose of the wal-index is to answer this question quickly:  Given
48985 ** a page number P and a maximum frame index M, return the index of the 
48986 ** last frame in the wal before frame M for page P in the WAL, or return
48987 ** NULL if there are no frames for page P in the WAL prior to M.
48988 **
48989 ** The wal-index consists of a header region, followed by an one or
48990 ** more index blocks.  
48991 **
48992 ** The wal-index header contains the total number of frames within the WAL
48993 ** in the mxFrame field.
48994 **
48995 ** Each index block except for the first contains information on 
48996 ** HASHTABLE_NPAGE frames. The first index block contains information on
48997 ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and 
48998 ** HASHTABLE_NPAGE are selected so that together the wal-index header and
48999 ** first index block are the same size as all other index blocks in the
49000 ** wal-index.
49001 **
49002 ** Each index block contains two sections, a page-mapping that contains the
49003 ** database page number associated with each wal frame, and a hash-table 
49004 ** that allows readers to query an index block for a specific page number.
49005 ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
49006 ** for the first index block) 32-bit page numbers. The first entry in the 
49007 ** first index-block contains the database page number corresponding to the
49008 ** first frame in the WAL file. The first entry in the second index block
49009 ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
49010 ** the log, and so on.
49011 **
49012 ** The last index block in a wal-index usually contains less than the full
49013 ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
49014 ** depending on the contents of the WAL file. This does not change the
49015 ** allocated size of the page-mapping array - the page-mapping array merely
49016 ** contains unused entries.
49017 **
49018 ** Even without using the hash table, the last frame for page P
49019 ** can be found by scanning the page-mapping sections of each index block
49020 ** starting with the last index block and moving toward the first, and
49021 ** within each index block, starting at the end and moving toward the
49022 ** beginning.  The first entry that equals P corresponds to the frame
49023 ** holding the content for that page.
49024 **
49025 ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
49026 ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
49027 ** hash table for each page number in the mapping section, so the hash 
49028 ** table is never more than half full.  The expected number of collisions 
49029 ** prior to finding a match is 1.  Each entry of the hash table is an
49030 ** 1-based index of an entry in the mapping section of the same
49031 ** index block.   Let K be the 1-based index of the largest entry in
49032 ** the mapping section.  (For index blocks other than the last, K will
49033 ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
49034 ** K will be (mxFrame%HASHTABLE_NPAGE).)  Unused slots of the hash table
49035 ** contain a value of 0.
49036 **
49037 ** To look for page P in the hash table, first compute a hash iKey on
49038 ** P as follows:
49039 **
49040 **      iKey = (P * 383) % HASHTABLE_NSLOT
49041 **
49042 ** Then start scanning entries of the hash table, starting with iKey
49043 ** (wrapping around to the beginning when the end of the hash table is
49044 ** reached) until an unused hash slot is found. Let the first unused slot
49045 ** be at index iUnused.  (iUnused might be less than iKey if there was
49046 ** wrap-around.) Because the hash table is never more than half full,
49047 ** the search is guaranteed to eventually hit an unused entry.  Let 
49048 ** iMax be the value between iKey and iUnused, closest to iUnused,
49049 ** where aHash[iMax]==P.  If there is no iMax entry (if there exists
49050 ** no hash slot such that aHash[i]==p) then page P is not in the
49051 ** current index block.  Otherwise the iMax-th mapping entry of the
49052 ** current index block corresponds to the last entry that references 
49053 ** page P.
49054 **
49055 ** A hash search begins with the last index block and moves toward the
49056 ** first index block, looking for entries corresponding to page P.  On
49057 ** average, only two or three slots in each index block need to be
49058 ** examined in order to either find the last entry for page P, or to
49059 ** establish that no such entry exists in the block.  Each index block
49060 ** holds over 4000 entries.  So two or three index blocks are sufficient
49061 ** to cover a typical 10 megabyte WAL file, assuming 1K pages.  8 or 10
49062 ** comparisons (on average) suffice to either locate a frame in the
49063 ** WAL or to establish that the frame does not exist in the WAL.  This
49064 ** is much faster than scanning the entire 10MB WAL.
49065 **
49066 ** Note that entries are added in order of increasing K.  Hence, one
49067 ** reader might be using some value K0 and a second reader that started
49068 ** at a later time (after additional transactions were added to the WAL
49069 ** and to the wal-index) might be using a different value K1, where K1>K0.
49070 ** Both readers can use the same hash table and mapping section to get
49071 ** the correct result.  There may be entries in the hash table with
49072 ** K>K0 but to the first reader, those entries will appear to be unused
49073 ** slots in the hash table and so the first reader will get an answer as
49074 ** if no values greater than K0 had ever been inserted into the hash table
49075 ** in the first place - which is what reader one wants.  Meanwhile, the
49076 ** second reader using K1 will see additional values that were inserted
49077 ** later, which is exactly what reader two wants.  
49078 **
49079 ** When a rollback occurs, the value of K is decreased. Hash table entries
49080 ** that correspond to frames greater than the new K value are removed
49081 ** from the hash table at this point.
49082 */
49083 #ifndef SQLITE_OMIT_WAL
49084
49085
49086 /*
49087 ** Trace output macros
49088 */
49089 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
49090 SQLITE_PRIVATE int sqlite3WalTrace = 0;
49091 # define WALTRACE(X)  if(sqlite3WalTrace) sqlite3DebugPrintf X
49092 #else
49093 # define WALTRACE(X)
49094 #endif
49095
49096 /*
49097 ** The maximum (and only) versions of the wal and wal-index formats
49098 ** that may be interpreted by this version of SQLite.
49099 **
49100 ** If a client begins recovering a WAL file and finds that (a) the checksum
49101 ** values in the wal-header are correct and (b) the version field is not
49102 ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
49103 **
49104 ** Similarly, if a client successfully reads a wal-index header (i.e. the 
49105 ** checksum test is successful) and finds that the version field is not
49106 ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
49107 ** returns SQLITE_CANTOPEN.
49108 */
49109 #define WAL_MAX_VERSION      3007000
49110 #define WALINDEX_MAX_VERSION 3007000
49111
49112 /*
49113 ** Indices of various locking bytes.   WAL_NREADER is the number
49114 ** of available reader locks and should be at least 3.
49115 */
49116 #define WAL_WRITE_LOCK         0
49117 #define WAL_ALL_BUT_WRITE      1
49118 #define WAL_CKPT_LOCK          1
49119 #define WAL_RECOVER_LOCK       2
49120 #define WAL_READ_LOCK(I)       (3+(I))
49121 #define WAL_NREADER            (SQLITE_SHM_NLOCK-3)
49122
49123
49124 /* Object declarations */
49125 typedef struct WalIndexHdr WalIndexHdr;
49126 typedef struct WalIterator WalIterator;
49127 typedef struct WalCkptInfo WalCkptInfo;
49128
49129
49130 /*
49131 ** The following object holds a copy of the wal-index header content.
49132 **
49133 ** The actual header in the wal-index consists of two copies of this
49134 ** object.
49135 **
49136 ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
49137 ** Or it can be 1 to represent a 65536-byte page.  The latter case was
49138 ** added in 3.7.1 when support for 64K pages was added.  
49139 */
49140 struct WalIndexHdr {
49141   u32 iVersion;                   /* Wal-index version */
49142   u32 unused;                     /* Unused (padding) field */
49143   u32 iChange;                    /* Counter incremented each transaction */
49144   u8 isInit;                      /* 1 when initialized */
49145   u8 bigEndCksum;                 /* True if checksums in WAL are big-endian */
49146   u16 szPage;                     /* Database page size in bytes. 1==64K */
49147   u32 mxFrame;                    /* Index of last valid frame in the WAL */
49148   u32 nPage;                      /* Size of database in pages */
49149   u32 aFrameCksum[2];             /* Checksum of last frame in log */
49150   u32 aSalt[2];                   /* Two salt values copied from WAL header */
49151   u32 aCksum[2];                  /* Checksum over all prior fields */
49152 };
49153
49154 /*
49155 ** A copy of the following object occurs in the wal-index immediately
49156 ** following the second copy of the WalIndexHdr.  This object stores
49157 ** information used by checkpoint.
49158 **
49159 ** nBackfill is the number of frames in the WAL that have been written
49160 ** back into the database. (We call the act of moving content from WAL to
49161 ** database "backfilling".)  The nBackfill number is never greater than
49162 ** WalIndexHdr.mxFrame.  nBackfill can only be increased by threads
49163 ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
49164 ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
49165 ** mxFrame back to zero when the WAL is reset.
49166 **
49167 ** There is one entry in aReadMark[] for each reader lock.  If a reader
49168 ** holds read-lock K, then the value in aReadMark[K] is no greater than
49169 ** the mxFrame for that reader.  The value READMARK_NOT_USED (0xffffffff)
49170 ** for any aReadMark[] means that entry is unused.  aReadMark[0] is 
49171 ** a special case; its value is never used and it exists as a place-holder
49172 ** to avoid having to offset aReadMark[] indexs by one.  Readers holding
49173 ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
49174 ** directly from the database.
49175 **
49176 ** The value of aReadMark[K] may only be changed by a thread that
49177 ** is holding an exclusive lock on WAL_READ_LOCK(K).  Thus, the value of
49178 ** aReadMark[K] cannot changed while there is a reader is using that mark
49179 ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
49180 **
49181 ** The checkpointer may only transfer frames from WAL to database where
49182 ** the frame numbers are less than or equal to every aReadMark[] that is
49183 ** in use (that is, every aReadMark[j] for which there is a corresponding
49184 ** WAL_READ_LOCK(j)).  New readers (usually) pick the aReadMark[] with the
49185 ** largest value and will increase an unused aReadMark[] to mxFrame if there
49186 ** is not already an aReadMark[] equal to mxFrame.  The exception to the
49187 ** previous sentence is when nBackfill equals mxFrame (meaning that everything
49188 ** in the WAL has been backfilled into the database) then new readers
49189 ** will choose aReadMark[0] which has value 0 and hence such reader will
49190 ** get all their all content directly from the database file and ignore 
49191 ** the WAL.
49192 **
49193 ** Writers normally append new frames to the end of the WAL.  However,
49194 ** if nBackfill equals mxFrame (meaning that all WAL content has been
49195 ** written back into the database) and if no readers are using the WAL
49196 ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
49197 ** the writer will first "reset" the WAL back to the beginning and start
49198 ** writing new content beginning at frame 1.
49199 **
49200 ** We assume that 32-bit loads are atomic and so no locks are needed in
49201 ** order to read from any aReadMark[] entries.
49202 */
49203 struct WalCkptInfo {
49204   u32 nBackfill;                  /* Number of WAL frames backfilled into DB */
49205   u32 aReadMark[WAL_NREADER];     /* Reader marks */
49206 };
49207 #define READMARK_NOT_USED  0xffffffff
49208
49209
49210 /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
49211 ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
49212 ** only support mandatory file-locks, we do not read or write data
49213 ** from the region of the file on which locks are applied.
49214 */
49215 #define WALINDEX_LOCK_OFFSET   (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
49216 #define WALINDEX_LOCK_RESERVED 16
49217 #define WALINDEX_HDR_SIZE      (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
49218
49219 /* Size of header before each frame in wal */
49220 #define WAL_FRAME_HDRSIZE 24
49221
49222 /* Size of write ahead log header, including checksum. */
49223 /* #define WAL_HDRSIZE 24 */
49224 #define WAL_HDRSIZE 32
49225
49226 /* WAL magic value. Either this value, or the same value with the least
49227 ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
49228 ** big-endian format in the first 4 bytes of a WAL file.
49229 **
49230 ** If the LSB is set, then the checksums for each frame within the WAL
49231 ** file are calculated by treating all data as an array of 32-bit 
49232 ** big-endian words. Otherwise, they are calculated by interpreting 
49233 ** all data as 32-bit little-endian words.
49234 */
49235 #define WAL_MAGIC 0x377f0682
49236
49237 /*
49238 ** Return the offset of frame iFrame in the write-ahead log file, 
49239 ** assuming a database page size of szPage bytes. The offset returned
49240 ** is to the start of the write-ahead log frame-header.
49241 */
49242 #define walFrameOffset(iFrame, szPage) (                               \
49243   WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE)         \
49244 )
49245
49246 /*
49247 ** An open write-ahead log file is represented by an instance of the
49248 ** following object.
49249 */
49250 struct Wal {
49251   sqlite3_vfs *pVfs;         /* The VFS used to create pDbFd */
49252   sqlite3_file *pDbFd;       /* File handle for the database file */
49253   sqlite3_file *pWalFd;      /* File handle for WAL file */
49254   u32 iCallback;             /* Value to pass to log callback (or 0) */
49255   i64 mxWalSize;             /* Truncate WAL to this size upon reset */
49256   int nWiData;               /* Size of array apWiData */
49257   int szFirstBlock;          /* Size of first block written to WAL file */
49258   volatile u32 **apWiData;   /* Pointer to wal-index content in memory */
49259   u32 szPage;                /* Database page size */
49260   i16 readLock;              /* Which read lock is being held.  -1 for none */
49261   u8 syncFlags;              /* Flags to use to sync header writes */
49262   u8 exclusiveMode;          /* Non-zero if connection is in exclusive mode */
49263   u8 writeLock;              /* True if in a write transaction */
49264   u8 ckptLock;               /* True if holding a checkpoint lock */
49265   u8 readOnly;               /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
49266   u8 truncateOnCommit;       /* True to truncate WAL file on commit */
49267   u8 syncHeader;             /* Fsync the WAL header if true */
49268   u8 padToSectorBoundary;    /* Pad transactions out to the next sector */
49269   WalIndexHdr hdr;           /* Wal-index header for current transaction */
49270   const char *zWalName;      /* Name of WAL file */
49271   u32 nCkpt;                 /* Checkpoint sequence counter in the wal-header */
49272 #ifdef SQLITE_DEBUG
49273   u8 lockError;              /* True if a locking error has occurred */
49274 #endif
49275 };
49276
49277 /*
49278 ** Candidate values for Wal.exclusiveMode.
49279 */
49280 #define WAL_NORMAL_MODE     0
49281 #define WAL_EXCLUSIVE_MODE  1     
49282 #define WAL_HEAPMEMORY_MODE 2
49283
49284 /*
49285 ** Possible values for WAL.readOnly
49286 */
49287 #define WAL_RDWR        0    /* Normal read/write connection */
49288 #define WAL_RDONLY      1    /* The WAL file is readonly */
49289 #define WAL_SHM_RDONLY  2    /* The SHM file is readonly */
49290
49291 /*
49292 ** Each page of the wal-index mapping contains a hash-table made up of
49293 ** an array of HASHTABLE_NSLOT elements of the following type.
49294 */
49295 typedef u16 ht_slot;
49296
49297 /*
49298 ** This structure is used to implement an iterator that loops through
49299 ** all frames in the WAL in database page order. Where two or more frames
49300 ** correspond to the same database page, the iterator visits only the 
49301 ** frame most recently written to the WAL (in other words, the frame with
49302 ** the largest index).
49303 **
49304 ** The internals of this structure are only accessed by:
49305 **
49306 **   walIteratorInit() - Create a new iterator,
49307 **   walIteratorNext() - Step an iterator,
49308 **   walIteratorFree() - Free an iterator.
49309 **
49310 ** This functionality is used by the checkpoint code (see walCheckpoint()).
49311 */
49312 struct WalIterator {
49313   int iPrior;                     /* Last result returned from the iterator */
49314   int nSegment;                   /* Number of entries in aSegment[] */
49315   struct WalSegment {
49316     int iNext;                    /* Next slot in aIndex[] not yet returned */
49317     ht_slot *aIndex;              /* i0, i1, i2... such that aPgno[iN] ascend */
49318     u32 *aPgno;                   /* Array of page numbers. */
49319     int nEntry;                   /* Nr. of entries in aPgno[] and aIndex[] */
49320     int iZero;                    /* Frame number associated with aPgno[0] */
49321   } aSegment[1];                  /* One for every 32KB page in the wal-index */
49322 };
49323
49324 /*
49325 ** Define the parameters of the hash tables in the wal-index file. There
49326 ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
49327 ** wal-index.
49328 **
49329 ** Changing any of these constants will alter the wal-index format and
49330 ** create incompatibilities.
49331 */
49332 #define HASHTABLE_NPAGE      4096                 /* Must be power of 2 */
49333 #define HASHTABLE_HASH_1     383                  /* Should be prime */
49334 #define HASHTABLE_NSLOT      (HASHTABLE_NPAGE*2)  /* Must be a power of 2 */
49335
49336 /* 
49337 ** The block of page numbers associated with the first hash-table in a
49338 ** wal-index is smaller than usual. This is so that there is a complete
49339 ** hash-table on each aligned 32KB page of the wal-index.
49340 */
49341 #define HASHTABLE_NPAGE_ONE  (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
49342
49343 /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
49344 #define WALINDEX_PGSZ   (                                         \
49345     sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
49346 )
49347
49348 /*
49349 ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
49350 ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
49351 ** numbered from zero.
49352 **
49353 ** If this call is successful, *ppPage is set to point to the wal-index
49354 ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
49355 ** then an SQLite error code is returned and *ppPage is set to 0.
49356 */
49357 static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
49358   int rc = SQLITE_OK;
49359
49360   /* Enlarge the pWal->apWiData[] array if required */
49361   if( pWal->nWiData<=iPage ){
49362     int nByte = sizeof(u32*)*(iPage+1);
49363     volatile u32 **apNew;
49364     apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
49365     if( !apNew ){
49366       *ppPage = 0;
49367       return SQLITE_NOMEM;
49368     }
49369     memset((void*)&apNew[pWal->nWiData], 0,
49370            sizeof(u32*)*(iPage+1-pWal->nWiData));
49371     pWal->apWiData = apNew;
49372     pWal->nWiData = iPage+1;
49373   }
49374
49375   /* Request a pointer to the required page from the VFS */
49376   if( pWal->apWiData[iPage]==0 ){
49377     if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
49378       pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
49379       if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
49380     }else{
49381       rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ, 
49382           pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
49383       );
49384       if( rc==SQLITE_READONLY ){
49385         pWal->readOnly |= WAL_SHM_RDONLY;
49386         rc = SQLITE_OK;
49387       }
49388     }
49389   }
49390
49391   *ppPage = pWal->apWiData[iPage];
49392   assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
49393   return rc;
49394 }
49395
49396 /*
49397 ** Return a pointer to the WalCkptInfo structure in the wal-index.
49398 */
49399 static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
49400   assert( pWal->nWiData>0 && pWal->apWiData[0] );
49401   return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
49402 }
49403
49404 /*
49405 ** Return a pointer to the WalIndexHdr structure in the wal-index.
49406 */
49407 static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
49408   assert( pWal->nWiData>0 && pWal->apWiData[0] );
49409   return (volatile WalIndexHdr*)pWal->apWiData[0];
49410 }
49411
49412 /*
49413 ** The argument to this macro must be of type u32. On a little-endian
49414 ** architecture, it returns the u32 value that results from interpreting
49415 ** the 4 bytes as a big-endian value. On a big-endian architecture, it
49416 ** returns the value that would be produced by interpreting the 4 bytes
49417 ** of the input value as a little-endian integer.
49418 */
49419 #define BYTESWAP32(x) ( \
49420     (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8)  \
49421   + (((x)&0x00FF0000)>>8)  + (((x)&0xFF000000)>>24) \
49422 )
49423
49424 /*
49425 ** Generate or extend an 8 byte checksum based on the data in 
49426 ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
49427 ** initial values of 0 and 0 if aIn==NULL).
49428 **
49429 ** The checksum is written back into aOut[] before returning.
49430 **
49431 ** nByte must be a positive multiple of 8.
49432 */
49433 static void walChecksumBytes(
49434   int nativeCksum, /* True for native byte-order, false for non-native */
49435   u8 *a,           /* Content to be checksummed */
49436   int nByte,       /* Bytes of content in a[].  Must be a multiple of 8. */
49437   const u32 *aIn,  /* Initial checksum value input */
49438   u32 *aOut        /* OUT: Final checksum value output */
49439 ){
49440   u32 s1, s2;
49441   u32 *aData = (u32 *)a;
49442   u32 *aEnd = (u32 *)&a[nByte];
49443
49444   if( aIn ){
49445     s1 = aIn[0];
49446     s2 = aIn[1];
49447   }else{
49448     s1 = s2 = 0;
49449   }
49450
49451   assert( nByte>=8 );
49452   assert( (nByte&0x00000007)==0 );
49453
49454   if( nativeCksum ){
49455     do {
49456       s1 += *aData++ + s2;
49457       s2 += *aData++ + s1;
49458     }while( aData<aEnd );
49459   }else{
49460     do {
49461       s1 += BYTESWAP32(aData[0]) + s2;
49462       s2 += BYTESWAP32(aData[1]) + s1;
49463       aData += 2;
49464     }while( aData<aEnd );
49465   }
49466
49467   aOut[0] = s1;
49468   aOut[1] = s2;
49469 }
49470
49471 static void walShmBarrier(Wal *pWal){
49472   if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
49473     sqlite3OsShmBarrier(pWal->pDbFd);
49474   }
49475 }
49476
49477 /*
49478 ** Write the header information in pWal->hdr into the wal-index.
49479 **
49480 ** The checksum on pWal->hdr is updated before it is written.
49481 */
49482 static void walIndexWriteHdr(Wal *pWal){
49483   volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
49484   const int nCksum = offsetof(WalIndexHdr, aCksum);
49485
49486   assert( pWal->writeLock );
49487   pWal->hdr.isInit = 1;
49488   pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
49489   walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
49490   memcpy((void *)&aHdr[1], (const void *)&pWal->hdr, sizeof(WalIndexHdr));
49491   walShmBarrier(pWal);
49492   memcpy((void *)&aHdr[0], (const void *)&pWal->hdr, sizeof(WalIndexHdr));
49493 }
49494
49495 /*
49496 ** This function encodes a single frame header and writes it to a buffer
49497 ** supplied by the caller. A frame-header is made up of a series of 
49498 ** 4-byte big-endian integers, as follows:
49499 **
49500 **     0: Page number.
49501 **     4: For commit records, the size of the database image in pages 
49502 **        after the commit. For all other records, zero.
49503 **     8: Salt-1 (copied from the wal-header)
49504 **    12: Salt-2 (copied from the wal-header)
49505 **    16: Checksum-1.
49506 **    20: Checksum-2.
49507 */
49508 static void walEncodeFrame(
49509   Wal *pWal,                      /* The write-ahead log */
49510   u32 iPage,                      /* Database page number for frame */
49511   u32 nTruncate,                  /* New db size (or 0 for non-commit frames) */
49512   u8 *aData,                      /* Pointer to page data */
49513   u8 *aFrame                      /* OUT: Write encoded frame here */
49514 ){
49515   int nativeCksum;                /* True for native byte-order checksums */
49516   u32 *aCksum = pWal->hdr.aFrameCksum;
49517   assert( WAL_FRAME_HDRSIZE==24 );
49518   sqlite3Put4byte(&aFrame[0], iPage);
49519   sqlite3Put4byte(&aFrame[4], nTruncate);
49520   memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
49521
49522   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
49523   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
49524   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
49525
49526   sqlite3Put4byte(&aFrame[16], aCksum[0]);
49527   sqlite3Put4byte(&aFrame[20], aCksum[1]);
49528 }
49529
49530 /*
49531 ** Check to see if the frame with header in aFrame[] and content
49532 ** in aData[] is valid.  If it is a valid frame, fill *piPage and
49533 ** *pnTruncate and return true.  Return if the frame is not valid.
49534 */
49535 static int walDecodeFrame(
49536   Wal *pWal,                      /* The write-ahead log */
49537   u32 *piPage,                    /* OUT: Database page number for frame */
49538   u32 *pnTruncate,                /* OUT: New db size (or 0 if not commit) */
49539   u8 *aData,                      /* Pointer to page data (for checksum) */
49540   u8 *aFrame                      /* Frame data */
49541 ){
49542   int nativeCksum;                /* True for native byte-order checksums */
49543   u32 *aCksum = pWal->hdr.aFrameCksum;
49544   u32 pgno;                       /* Page number of the frame */
49545   assert( WAL_FRAME_HDRSIZE==24 );
49546
49547   /* A frame is only valid if the salt values in the frame-header
49548   ** match the salt values in the wal-header. 
49549   */
49550   if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
49551     return 0;
49552   }
49553
49554   /* A frame is only valid if the page number is creater than zero.
49555   */
49556   pgno = sqlite3Get4byte(&aFrame[0]);
49557   if( pgno==0 ){
49558     return 0;
49559   }
49560
49561   /* A frame is only valid if a checksum of the WAL header,
49562   ** all prior frams, the first 16 bytes of this frame-header, 
49563   ** and the frame-data matches the checksum in the last 8 
49564   ** bytes of this frame-header.
49565   */
49566   nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
49567   walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
49568   walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
49569   if( aCksum[0]!=sqlite3Get4byte(&aFrame[16]) 
49570    || aCksum[1]!=sqlite3Get4byte(&aFrame[20]) 
49571   ){
49572     /* Checksum failed. */
49573     return 0;
49574   }
49575
49576   /* If we reach this point, the frame is valid.  Return the page number
49577   ** and the new database size.
49578   */
49579   *piPage = pgno;
49580   *pnTruncate = sqlite3Get4byte(&aFrame[4]);
49581   return 1;
49582 }
49583
49584
49585 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
49586 /*
49587 ** Names of locks.  This routine is used to provide debugging output and is not
49588 ** a part of an ordinary build.
49589 */
49590 static const char *walLockName(int lockIdx){
49591   if( lockIdx==WAL_WRITE_LOCK ){
49592     return "WRITE-LOCK";
49593   }else if( lockIdx==WAL_CKPT_LOCK ){
49594     return "CKPT-LOCK";
49595   }else if( lockIdx==WAL_RECOVER_LOCK ){
49596     return "RECOVER-LOCK";
49597   }else{
49598     static char zName[15];
49599     sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
49600                      lockIdx-WAL_READ_LOCK(0));
49601     return zName;
49602   }
49603 }
49604 #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
49605     
49606
49607 /*
49608 ** Set or release locks on the WAL.  Locks are either shared or exclusive.
49609 ** A lock cannot be moved directly between shared and exclusive - it must go
49610 ** through the unlocked state first.
49611 **
49612 ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
49613 */
49614 static int walLockShared(Wal *pWal, int lockIdx){
49615   int rc;
49616   if( pWal->exclusiveMode ) return SQLITE_OK;
49617   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
49618                         SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
49619   WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
49620             walLockName(lockIdx), rc ? "failed" : "ok"));
49621   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
49622   return rc;
49623 }
49624 static void walUnlockShared(Wal *pWal, int lockIdx){
49625   if( pWal->exclusiveMode ) return;
49626   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
49627                          SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
49628   WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
49629 }
49630 static int walLockExclusive(Wal *pWal, int lockIdx, int n, int fBlock){
49631   int rc;
49632   if( pWal->exclusiveMode ) return SQLITE_OK;
49633   if( fBlock ) sqlite3OsFileControl(pWal->pDbFd, SQLITE_FCNTL_WAL_BLOCK, 0);
49634   rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
49635                         SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
49636   WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
49637             walLockName(lockIdx), n, rc ? "failed" : "ok"));
49638   VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
49639   return rc;
49640 }
49641 static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
49642   if( pWal->exclusiveMode ) return;
49643   (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
49644                          SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
49645   WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
49646              walLockName(lockIdx), n));
49647 }
49648
49649 /*
49650 ** Compute a hash on a page number.  The resulting hash value must land
49651 ** between 0 and (HASHTABLE_NSLOT-1).  The walHashNext() function advances
49652 ** the hash to the next value in the event of a collision.
49653 */
49654 static int walHash(u32 iPage){
49655   assert( iPage>0 );
49656   assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
49657   return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
49658 }
49659 static int walNextHash(int iPriorHash){
49660   return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
49661 }
49662
49663 /* 
49664 ** Return pointers to the hash table and page number array stored on
49665 ** page iHash of the wal-index. The wal-index is broken into 32KB pages
49666 ** numbered starting from 0.
49667 **
49668 ** Set output variable *paHash to point to the start of the hash table
49669 ** in the wal-index file. Set *piZero to one less than the frame 
49670 ** number of the first frame indexed by this hash table. If a
49671 ** slot in the hash table is set to N, it refers to frame number 
49672 ** (*piZero+N) in the log.
49673 **
49674 ** Finally, set *paPgno so that *paPgno[1] is the page number of the
49675 ** first frame indexed by the hash table, frame (*piZero+1).
49676 */
49677 static int walHashGet(
49678   Wal *pWal,                      /* WAL handle */
49679   int iHash,                      /* Find the iHash'th table */
49680   volatile ht_slot **paHash,      /* OUT: Pointer to hash index */
49681   volatile u32 **paPgno,          /* OUT: Pointer to page number array */
49682   u32 *piZero                     /* OUT: Frame associated with *paPgno[0] */
49683 ){
49684   int rc;                         /* Return code */
49685   volatile u32 *aPgno;
49686
49687   rc = walIndexPage(pWal, iHash, &aPgno);
49688   assert( rc==SQLITE_OK || iHash>0 );
49689
49690   if( rc==SQLITE_OK ){
49691     u32 iZero;
49692     volatile ht_slot *aHash;
49693
49694     aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
49695     if( iHash==0 ){
49696       aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
49697       iZero = 0;
49698     }else{
49699       iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
49700     }
49701   
49702     *paPgno = &aPgno[-1];
49703     *paHash = aHash;
49704     *piZero = iZero;
49705   }
49706   return rc;
49707 }
49708
49709 /*
49710 ** Return the number of the wal-index page that contains the hash-table
49711 ** and page-number array that contain entries corresponding to WAL frame
49712 ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages 
49713 ** are numbered starting from 0.
49714 */
49715 static int walFramePage(u32 iFrame){
49716   int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
49717   assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
49718        && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
49719        && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
49720        && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
49721        && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
49722   );
49723   return iHash;
49724 }
49725
49726 /*
49727 ** Return the page number associated with frame iFrame in this WAL.
49728 */
49729 static u32 walFramePgno(Wal *pWal, u32 iFrame){
49730   int iHash = walFramePage(iFrame);
49731   if( iHash==0 ){
49732     return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
49733   }
49734   return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
49735 }
49736
49737 /*
49738 ** Remove entries from the hash table that point to WAL slots greater
49739 ** than pWal->hdr.mxFrame.
49740 **
49741 ** This function is called whenever pWal->hdr.mxFrame is decreased due
49742 ** to a rollback or savepoint.
49743 **
49744 ** At most only the hash table containing pWal->hdr.mxFrame needs to be
49745 ** updated.  Any later hash tables will be automatically cleared when
49746 ** pWal->hdr.mxFrame advances to the point where those hash tables are
49747 ** actually needed.
49748 */
49749 static void walCleanupHash(Wal *pWal){
49750   volatile ht_slot *aHash = 0;    /* Pointer to hash table to clear */
49751   volatile u32 *aPgno = 0;        /* Page number array for hash table */
49752   u32 iZero = 0;                  /* frame == (aHash[x]+iZero) */
49753   int iLimit = 0;                 /* Zero values greater than this */
49754   int nByte;                      /* Number of bytes to zero in aPgno[] */
49755   int i;                          /* Used to iterate through aHash[] */
49756
49757   assert( pWal->writeLock );
49758   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
49759   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
49760   testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
49761
49762   if( pWal->hdr.mxFrame==0 ) return;
49763
49764   /* Obtain pointers to the hash-table and page-number array containing 
49765   ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
49766   ** that the page said hash-table and array reside on is already mapped.
49767   */
49768   assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
49769   assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
49770   walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
49771
49772   /* Zero all hash-table entries that correspond to frame numbers greater
49773   ** than pWal->hdr.mxFrame.
49774   */
49775   iLimit = pWal->hdr.mxFrame - iZero;
49776   assert( iLimit>0 );
49777   for(i=0; i<HASHTABLE_NSLOT; i++){
49778     if( aHash[i]>iLimit ){
49779       aHash[i] = 0;
49780     }
49781   }
49782   
49783   /* Zero the entries in the aPgno array that correspond to frames with
49784   ** frame numbers greater than pWal->hdr.mxFrame. 
49785   */
49786   nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
49787   memset((void *)&aPgno[iLimit+1], 0, nByte);
49788
49789 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
49790   /* Verify that the every entry in the mapping region is still reachable
49791   ** via the hash table even after the cleanup.
49792   */
49793   if( iLimit ){
49794     int i;           /* Loop counter */
49795     int iKey;        /* Hash key */
49796     for(i=1; i<=iLimit; i++){
49797       for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
49798         if( aHash[iKey]==i ) break;
49799       }
49800       assert( aHash[iKey]==i );
49801     }
49802   }
49803 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
49804 }
49805
49806
49807 /*
49808 ** Set an entry in the wal-index that will map database page number
49809 ** pPage into WAL frame iFrame.
49810 */
49811 static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
49812   int rc;                         /* Return code */
49813   u32 iZero = 0;                  /* One less than frame number of aPgno[1] */
49814   volatile u32 *aPgno = 0;        /* Page number array */
49815   volatile ht_slot *aHash = 0;    /* Hash table */
49816
49817   rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
49818
49819   /* Assuming the wal-index file was successfully mapped, populate the
49820   ** page number array and hash table entry.
49821   */
49822   if( rc==SQLITE_OK ){
49823     int iKey;                     /* Hash table key */
49824     int idx;                      /* Value to write to hash-table slot */
49825     int nCollide;                 /* Number of hash collisions */
49826
49827     idx = iFrame - iZero;
49828     assert( idx <= HASHTABLE_NSLOT/2 + 1 );
49829     
49830     /* If this is the first entry to be added to this hash-table, zero the
49831     ** entire hash table and aPgno[] array before proceeding. 
49832     */
49833     if( idx==1 ){
49834       int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
49835       memset((void*)&aPgno[1], 0, nByte);
49836     }
49837
49838     /* If the entry in aPgno[] is already set, then the previous writer
49839     ** must have exited unexpectedly in the middle of a transaction (after
49840     ** writing one or more dirty pages to the WAL to free up memory). 
49841     ** Remove the remnants of that writers uncommitted transaction from 
49842     ** the hash-table before writing any new entries.
49843     */
49844     if( aPgno[idx] ){
49845       walCleanupHash(pWal);
49846       assert( !aPgno[idx] );
49847     }
49848
49849     /* Write the aPgno[] array entry and the hash-table slot. */
49850     nCollide = idx;
49851     for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
49852       if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
49853     }
49854     aPgno[idx] = iPage;
49855     aHash[iKey] = (ht_slot)idx;
49856
49857 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
49858     /* Verify that the number of entries in the hash table exactly equals
49859     ** the number of entries in the mapping region.
49860     */
49861     {
49862       int i;           /* Loop counter */
49863       int nEntry = 0;  /* Number of entries in the hash table */
49864       for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
49865       assert( nEntry==idx );
49866     }
49867
49868     /* Verify that the every entry in the mapping region is reachable
49869     ** via the hash table.  This turns out to be a really, really expensive
49870     ** thing to check, so only do this occasionally - not on every
49871     ** iteration.
49872     */
49873     if( (idx&0x3ff)==0 ){
49874       int i;           /* Loop counter */
49875       for(i=1; i<=idx; i++){
49876         for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
49877           if( aHash[iKey]==i ) break;
49878         }
49879         assert( aHash[iKey]==i );
49880       }
49881     }
49882 #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
49883   }
49884
49885
49886   return rc;
49887 }
49888
49889
49890 /*
49891 ** Recover the wal-index by reading the write-ahead log file. 
49892 **
49893 ** This routine first tries to establish an exclusive lock on the
49894 ** wal-index to prevent other threads/processes from doing anything
49895 ** with the WAL or wal-index while recovery is running.  The
49896 ** WAL_RECOVER_LOCK is also held so that other threads will know
49897 ** that this thread is running recovery.  If unable to establish
49898 ** the necessary locks, this routine returns SQLITE_BUSY.
49899 */
49900 static int walIndexRecover(Wal *pWal){
49901   int rc;                         /* Return Code */
49902   i64 nSize;                      /* Size of log file */
49903   u32 aFrameCksum[2] = {0, 0};
49904   int iLock;                      /* Lock offset to lock for checkpoint */
49905   int nLock;                      /* Number of locks to hold */
49906
49907   /* Obtain an exclusive lock on all byte in the locking range not already
49908   ** locked by the caller. The caller is guaranteed to have locked the
49909   ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
49910   ** If successful, the same bytes that are locked here are unlocked before
49911   ** this function returns.
49912   */
49913   assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
49914   assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
49915   assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
49916   assert( pWal->writeLock );
49917   iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
49918   nLock = SQLITE_SHM_NLOCK - iLock;
49919   rc = walLockExclusive(pWal, iLock, nLock, 0);
49920   if( rc ){
49921     return rc;
49922   }
49923   WALTRACE(("WAL%p: recovery begin...\n", pWal));
49924
49925   memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
49926
49927   rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
49928   if( rc!=SQLITE_OK ){
49929     goto recovery_error;
49930   }
49931
49932   if( nSize>WAL_HDRSIZE ){
49933     u8 aBuf[WAL_HDRSIZE];         /* Buffer to load WAL header into */
49934     u8 *aFrame = 0;               /* Malloc'd buffer to load entire frame */
49935     int szFrame;                  /* Number of bytes in buffer aFrame[] */
49936     u8 *aData;                    /* Pointer to data part of aFrame buffer */
49937     int iFrame;                   /* Index of last frame read */
49938     i64 iOffset;                  /* Next offset to read from log file */
49939     int szPage;                   /* Page size according to the log */
49940     u32 magic;                    /* Magic value read from WAL header */
49941     u32 version;                  /* Magic value read from WAL header */
49942     int isValid;                  /* True if this frame is valid */
49943
49944     /* Read in the WAL header. */
49945     rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
49946     if( rc!=SQLITE_OK ){
49947       goto recovery_error;
49948     }
49949
49950     /* If the database page size is not a power of two, or is greater than
49951     ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid 
49952     ** data. Similarly, if the 'magic' value is invalid, ignore the whole
49953     ** WAL file.
49954     */
49955     magic = sqlite3Get4byte(&aBuf[0]);
49956     szPage = sqlite3Get4byte(&aBuf[8]);
49957     if( (magic&0xFFFFFFFE)!=WAL_MAGIC 
49958      || szPage&(szPage-1) 
49959      || szPage>SQLITE_MAX_PAGE_SIZE 
49960      || szPage<512 
49961     ){
49962       goto finished;
49963     }
49964     pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
49965     pWal->szPage = szPage;
49966     pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
49967     memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
49968
49969     /* Verify that the WAL header checksum is correct */
49970     walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN, 
49971         aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
49972     );
49973     if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
49974      || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
49975     ){
49976       goto finished;
49977     }
49978
49979     /* Verify that the version number on the WAL format is one that
49980     ** are able to understand */
49981     version = sqlite3Get4byte(&aBuf[4]);
49982     if( version!=WAL_MAX_VERSION ){
49983       rc = SQLITE_CANTOPEN_BKPT;
49984       goto finished;
49985     }
49986
49987     /* Malloc a buffer to read frames into. */
49988     szFrame = szPage + WAL_FRAME_HDRSIZE;
49989     aFrame = (u8 *)sqlite3_malloc(szFrame);
49990     if( !aFrame ){
49991       rc = SQLITE_NOMEM;
49992       goto recovery_error;
49993     }
49994     aData = &aFrame[WAL_FRAME_HDRSIZE];
49995
49996     /* Read all frames from the log file. */
49997     iFrame = 0;
49998     for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
49999       u32 pgno;                   /* Database page number for frame */
50000       u32 nTruncate;              /* dbsize field from frame header */
50001
50002       /* Read and decode the next log frame. */
50003       iFrame++;
50004       rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
50005       if( rc!=SQLITE_OK ) break;
50006       isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
50007       if( !isValid ) break;
50008       rc = walIndexAppend(pWal, iFrame, pgno);
50009       if( rc!=SQLITE_OK ) break;
50010
50011       /* If nTruncate is non-zero, this is a commit record. */
50012       if( nTruncate ){
50013         pWal->hdr.mxFrame = iFrame;
50014         pWal->hdr.nPage = nTruncate;
50015         pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
50016         testcase( szPage<=32768 );
50017         testcase( szPage>=65536 );
50018         aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
50019         aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
50020       }
50021     }
50022
50023     sqlite3_free(aFrame);
50024   }
50025
50026 finished:
50027   if( rc==SQLITE_OK ){
50028     volatile WalCkptInfo *pInfo;
50029     int i;
50030     pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
50031     pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
50032     walIndexWriteHdr(pWal);
50033
50034     /* Reset the checkpoint-header. This is safe because this thread is 
50035     ** currently holding locks that exclude all other readers, writers and
50036     ** checkpointers.
50037     */
50038     pInfo = walCkptInfo(pWal);
50039     pInfo->nBackfill = 0;
50040     pInfo->aReadMark[0] = 0;
50041     for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
50042     if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
50043
50044     /* If more than one frame was recovered from the log file, report an
50045     ** event via sqlite3_log(). This is to help with identifying performance
50046     ** problems caused by applications routinely shutting down without
50047     ** checkpointing the log file.
50048     */
50049     if( pWal->hdr.nPage ){
50050       sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
50051           "recovered %d frames from WAL file %s",
50052           pWal->hdr.mxFrame, pWal->zWalName
50053       );
50054     }
50055   }
50056
50057 recovery_error:
50058   WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
50059   walUnlockExclusive(pWal, iLock, nLock);
50060   return rc;
50061 }
50062
50063 /*
50064 ** Close an open wal-index.
50065 */
50066 static void walIndexClose(Wal *pWal, int isDelete){
50067   if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
50068     int i;
50069     for(i=0; i<pWal->nWiData; i++){
50070       sqlite3_free((void *)pWal->apWiData[i]);
50071       pWal->apWiData[i] = 0;
50072     }
50073   }else{
50074     sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
50075   }
50076 }
50077
50078 /* 
50079 ** Open a connection to the WAL file zWalName. The database file must 
50080 ** already be opened on connection pDbFd. The buffer that zWalName points
50081 ** to must remain valid for the lifetime of the returned Wal* handle.
50082 **
50083 ** A SHARED lock should be held on the database file when this function
50084 ** is called. The purpose of this SHARED lock is to prevent any other
50085 ** client from unlinking the WAL or wal-index file. If another process
50086 ** were to do this just after this client opened one of these files, the
50087 ** system would be badly broken.
50088 **
50089 ** If the log file is successfully opened, SQLITE_OK is returned and 
50090 ** *ppWal is set to point to a new WAL handle. If an error occurs,
50091 ** an SQLite error code is returned and *ppWal is left unmodified.
50092 */
50093 SQLITE_PRIVATE int sqlite3WalOpen(
50094   sqlite3_vfs *pVfs,              /* vfs module to open wal and wal-index */
50095   sqlite3_file *pDbFd,            /* The open database file */
50096   const char *zWalName,           /* Name of the WAL file */
50097   int bNoShm,                     /* True to run in heap-memory mode */
50098   i64 mxWalSize,                  /* Truncate WAL to this size on reset */
50099   Wal **ppWal                     /* OUT: Allocated Wal handle */
50100 ){
50101   int rc;                         /* Return Code */
50102   Wal *pRet;                      /* Object to allocate and return */
50103   int flags;                      /* Flags passed to OsOpen() */
50104
50105   assert( zWalName && zWalName[0] );
50106   assert( pDbFd );
50107
50108   /* In the amalgamation, the os_unix.c and os_win.c source files come before
50109   ** this source file.  Verify that the #defines of the locking byte offsets
50110   ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
50111   */
50112 #ifdef WIN_SHM_BASE
50113   assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
50114 #endif
50115 #ifdef UNIX_SHM_BASE
50116   assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
50117 #endif
50118
50119
50120   /* Allocate an instance of struct Wal to return. */
50121   *ppWal = 0;
50122   pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
50123   if( !pRet ){
50124     return SQLITE_NOMEM;
50125   }
50126
50127   pRet->pVfs = pVfs;
50128   pRet->pWalFd = (sqlite3_file *)&pRet[1];
50129   pRet->pDbFd = pDbFd;
50130   pRet->readLock = -1;
50131   pRet->mxWalSize = mxWalSize;
50132   pRet->zWalName = zWalName;
50133   pRet->syncHeader = 1;
50134   pRet->padToSectorBoundary = 1;
50135   pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
50136
50137   /* Open file handle on the write-ahead log file. */
50138   flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
50139   rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
50140   if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
50141     pRet->readOnly = WAL_RDONLY;
50142   }
50143
50144   if( rc!=SQLITE_OK ){
50145     walIndexClose(pRet, 0);
50146     sqlite3OsClose(pRet->pWalFd);
50147     sqlite3_free(pRet);
50148   }else{
50149     int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
50150     if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
50151     if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
50152       pRet->padToSectorBoundary = 0;
50153     }
50154     *ppWal = pRet;
50155     WALTRACE(("WAL%d: opened\n", pRet));
50156   }
50157   return rc;
50158 }
50159
50160 /*
50161 ** Change the size to which the WAL file is trucated on each reset.
50162 */
50163 SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
50164   if( pWal ) pWal->mxWalSize = iLimit;
50165 }
50166
50167 /*
50168 ** Find the smallest page number out of all pages held in the WAL that
50169 ** has not been returned by any prior invocation of this method on the
50170 ** same WalIterator object.   Write into *piFrame the frame index where
50171 ** that page was last written into the WAL.  Write into *piPage the page
50172 ** number.
50173 **
50174 ** Return 0 on success.  If there are no pages in the WAL with a page
50175 ** number larger than *piPage, then return 1.
50176 */
50177 static int walIteratorNext(
50178   WalIterator *p,               /* Iterator */
50179   u32 *piPage,                  /* OUT: The page number of the next page */
50180   u32 *piFrame                  /* OUT: Wal frame index of next page */
50181 ){
50182   u32 iMin;                     /* Result pgno must be greater than iMin */
50183   u32 iRet = 0xFFFFFFFF;        /* 0xffffffff is never a valid page number */
50184   int i;                        /* For looping through segments */
50185
50186   iMin = p->iPrior;
50187   assert( iMin<0xffffffff );
50188   for(i=p->nSegment-1; i>=0; i--){
50189     struct WalSegment *pSegment = &p->aSegment[i];
50190     while( pSegment->iNext<pSegment->nEntry ){
50191       u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
50192       if( iPg>iMin ){
50193         if( iPg<iRet ){
50194           iRet = iPg;
50195           *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
50196         }
50197         break;
50198       }
50199       pSegment->iNext++;
50200     }
50201   }
50202
50203   *piPage = p->iPrior = iRet;
50204   return (iRet==0xFFFFFFFF);
50205 }
50206
50207 /*
50208 ** This function merges two sorted lists into a single sorted list.
50209 **
50210 ** aLeft[] and aRight[] are arrays of indices.  The sort key is
50211 ** aContent[aLeft[]] and aContent[aRight[]].  Upon entry, the following
50212 ** is guaranteed for all J<K:
50213 **
50214 **        aContent[aLeft[J]] < aContent[aLeft[K]]
50215 **        aContent[aRight[J]] < aContent[aRight[K]]
50216 **
50217 ** This routine overwrites aRight[] with a new (probably longer) sequence
50218 ** of indices such that the aRight[] contains every index that appears in
50219 ** either aLeft[] or the old aRight[] and such that the second condition
50220 ** above is still met.
50221 **
50222 ** The aContent[aLeft[X]] values will be unique for all X.  And the
50223 ** aContent[aRight[X]] values will be unique too.  But there might be
50224 ** one or more combinations of X and Y such that
50225 **
50226 **      aLeft[X]!=aRight[Y]  &&  aContent[aLeft[X]] == aContent[aRight[Y]]
50227 **
50228 ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
50229 */
50230 static void walMerge(
50231   const u32 *aContent,            /* Pages in wal - keys for the sort */
50232   ht_slot *aLeft,                 /* IN: Left hand input list */
50233   int nLeft,                      /* IN: Elements in array *paLeft */
50234   ht_slot **paRight,              /* IN/OUT: Right hand input list */
50235   int *pnRight,                   /* IN/OUT: Elements in *paRight */
50236   ht_slot *aTmp                   /* Temporary buffer */
50237 ){
50238   int iLeft = 0;                  /* Current index in aLeft */
50239   int iRight = 0;                 /* Current index in aRight */
50240   int iOut = 0;                   /* Current index in output buffer */
50241   int nRight = *pnRight;
50242   ht_slot *aRight = *paRight;
50243
50244   assert( nLeft>0 && nRight>0 );
50245   while( iRight<nRight || iLeft<nLeft ){
50246     ht_slot logpage;
50247     Pgno dbpage;
50248
50249     if( (iLeft<nLeft) 
50250      && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
50251     ){
50252       logpage = aLeft[iLeft++];
50253     }else{
50254       logpage = aRight[iRight++];
50255     }
50256     dbpage = aContent[logpage];
50257
50258     aTmp[iOut++] = logpage;
50259     if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
50260
50261     assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
50262     assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
50263   }
50264
50265   *paRight = aLeft;
50266   *pnRight = iOut;
50267   memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
50268 }
50269
50270 /*
50271 ** Sort the elements in list aList using aContent[] as the sort key.
50272 ** Remove elements with duplicate keys, preferring to keep the
50273 ** larger aList[] values.
50274 **
50275 ** The aList[] entries are indices into aContent[].  The values in
50276 ** aList[] are to be sorted so that for all J<K:
50277 **
50278 **      aContent[aList[J]] < aContent[aList[K]]
50279 **
50280 ** For any X and Y such that
50281 **
50282 **      aContent[aList[X]] == aContent[aList[Y]]
50283 **
50284 ** Keep the larger of the two values aList[X] and aList[Y] and discard
50285 ** the smaller.
50286 */
50287 static void walMergesort(
50288   const u32 *aContent,            /* Pages in wal */
50289   ht_slot *aBuffer,               /* Buffer of at least *pnList items to use */
50290   ht_slot *aList,                 /* IN/OUT: List to sort */
50291   int *pnList                     /* IN/OUT: Number of elements in aList[] */
50292 ){
50293   struct Sublist {
50294     int nList;                    /* Number of elements in aList */
50295     ht_slot *aList;               /* Pointer to sub-list content */
50296   };
50297
50298   const int nList = *pnList;      /* Size of input list */
50299   int nMerge = 0;                 /* Number of elements in list aMerge */
50300   ht_slot *aMerge = 0;            /* List to be merged */
50301   int iList;                      /* Index into input list */
50302   int iSub = 0;                   /* Index into aSub array */
50303   struct Sublist aSub[13];        /* Array of sub-lists */
50304
50305   memset(aSub, 0, sizeof(aSub));
50306   assert( nList<=HASHTABLE_NPAGE && nList>0 );
50307   assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
50308
50309   for(iList=0; iList<nList; iList++){
50310     nMerge = 1;
50311     aMerge = &aList[iList];
50312     for(iSub=0; iList & (1<<iSub); iSub++){
50313       struct Sublist *p = &aSub[iSub];
50314       assert( p->aList && p->nList<=(1<<iSub) );
50315       assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
50316       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
50317     }
50318     aSub[iSub].aList = aMerge;
50319     aSub[iSub].nList = nMerge;
50320   }
50321
50322   for(iSub++; iSub<ArraySize(aSub); iSub++){
50323     if( nList & (1<<iSub) ){
50324       struct Sublist *p = &aSub[iSub];
50325       assert( p->nList<=(1<<iSub) );
50326       assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
50327       walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
50328     }
50329   }
50330   assert( aMerge==aList );
50331   *pnList = nMerge;
50332
50333 #ifdef SQLITE_DEBUG
50334   {
50335     int i;
50336     for(i=1; i<*pnList; i++){
50337       assert( aContent[aList[i]] > aContent[aList[i-1]] );
50338     }
50339   }
50340 #endif
50341 }
50342
50343 /* 
50344 ** Free an iterator allocated by walIteratorInit().
50345 */
50346 static void walIteratorFree(WalIterator *p){
50347   sqlite3_free(p);
50348 }
50349
50350 /*
50351 ** Construct a WalInterator object that can be used to loop over all 
50352 ** pages in the WAL in ascending order. The caller must hold the checkpoint
50353 ** lock.
50354 **
50355 ** On success, make *pp point to the newly allocated WalInterator object
50356 ** return SQLITE_OK. Otherwise, return an error code. If this routine
50357 ** returns an error, the value of *pp is undefined.
50358 **
50359 ** The calling routine should invoke walIteratorFree() to destroy the
50360 ** WalIterator object when it has finished with it.
50361 */
50362 static int walIteratorInit(Wal *pWal, WalIterator **pp){
50363   WalIterator *p;                 /* Return value */
50364   int nSegment;                   /* Number of segments to merge */
50365   u32 iLast;                      /* Last frame in log */
50366   int nByte;                      /* Number of bytes to allocate */
50367   int i;                          /* Iterator variable */
50368   ht_slot *aTmp;                  /* Temp space used by merge-sort */
50369   int rc = SQLITE_OK;             /* Return Code */
50370
50371   /* This routine only runs while holding the checkpoint lock. And
50372   ** it only runs if there is actually content in the log (mxFrame>0).
50373   */
50374   assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
50375   iLast = pWal->hdr.mxFrame;
50376
50377   /* Allocate space for the WalIterator object. */
50378   nSegment = walFramePage(iLast) + 1;
50379   nByte = sizeof(WalIterator) 
50380         + (nSegment-1)*sizeof(struct WalSegment)
50381         + iLast*sizeof(ht_slot);
50382   p = (WalIterator *)sqlite3_malloc(nByte);
50383   if( !p ){
50384     return SQLITE_NOMEM;
50385   }
50386   memset(p, 0, nByte);
50387   p->nSegment = nSegment;
50388
50389   /* Allocate temporary space used by the merge-sort routine. This block
50390   ** of memory will be freed before this function returns.
50391   */
50392   aTmp = (ht_slot *)sqlite3_malloc(
50393       sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
50394   );
50395   if( !aTmp ){
50396     rc = SQLITE_NOMEM;
50397   }
50398
50399   for(i=0; rc==SQLITE_OK && i<nSegment; i++){
50400     volatile ht_slot *aHash;
50401     u32 iZero;
50402     volatile u32 *aPgno;
50403
50404     rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
50405     if( rc==SQLITE_OK ){
50406       int j;                      /* Counter variable */
50407       int nEntry;                 /* Number of entries in this segment */
50408       ht_slot *aIndex;            /* Sorted index for this segment */
50409
50410       aPgno++;
50411       if( (i+1)==nSegment ){
50412         nEntry = (int)(iLast - iZero);
50413       }else{
50414         nEntry = (int)((u32*)aHash - (u32*)aPgno);
50415       }
50416       aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
50417       iZero++;
50418   
50419       for(j=0; j<nEntry; j++){
50420         aIndex[j] = (ht_slot)j;
50421       }
50422       walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
50423       p->aSegment[i].iZero = iZero;
50424       p->aSegment[i].nEntry = nEntry;
50425       p->aSegment[i].aIndex = aIndex;
50426       p->aSegment[i].aPgno = (u32 *)aPgno;
50427     }
50428   }
50429   sqlite3_free(aTmp);
50430
50431   if( rc!=SQLITE_OK ){
50432     walIteratorFree(p);
50433   }
50434   *pp = p;
50435   return rc;
50436 }
50437
50438 /*
50439 ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
50440 ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
50441 ** busy-handler function. Invoke it and retry the lock until either the
50442 ** lock is successfully obtained or the busy-handler returns 0.
50443 */
50444 static int walBusyLock(
50445   Wal *pWal,                      /* WAL connection */
50446   int (*xBusy)(void*),            /* Function to call when busy */
50447   void *pBusyArg,                 /* Context argument for xBusyHandler */
50448   int lockIdx,                    /* Offset of first byte to lock */
50449   int n                           /* Number of bytes to lock */
50450 ){
50451   int rc;
50452   do {
50453     rc = walLockExclusive(pWal, lockIdx, n, 0);
50454   }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
50455   return rc;
50456 }
50457
50458 /*
50459 ** The cache of the wal-index header must be valid to call this function.
50460 ** Return the page-size in bytes used by the database.
50461 */
50462 static int walPagesize(Wal *pWal){
50463   return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
50464 }
50465
50466 /*
50467 ** The following is guaranteed when this function is called:
50468 **
50469 **   a) the WRITER lock is held,
50470 **   b) the entire log file has been checkpointed, and
50471 **   c) any existing readers are reading exclusively from the database
50472 **      file - there are no readers that may attempt to read a frame from
50473 **      the log file.
50474 **
50475 ** This function updates the shared-memory structures so that the next
50476 ** client to write to the database (which may be this one) does so by
50477 ** writing frames into the start of the log file.
50478 **
50479 ** The value of parameter salt1 is used as the aSalt[1] value in the 
50480 ** new wal-index header. It should be passed a pseudo-random value (i.e. 
50481 ** one obtained from sqlite3_randomness()).
50482 */
50483 static void walRestartHdr(Wal *pWal, u32 salt1){
50484   volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
50485   int i;                          /* Loop counter */
50486   u32 *aSalt = pWal->hdr.aSalt;   /* Big-endian salt values */
50487   pWal->nCkpt++;
50488   pWal->hdr.mxFrame = 0;
50489   sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
50490   memcpy(&pWal->hdr.aSalt[1], &salt1, 4);
50491   walIndexWriteHdr(pWal);
50492   pInfo->nBackfill = 0;
50493   pInfo->aReadMark[1] = 0;
50494   for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
50495   assert( pInfo->aReadMark[0]==0 );
50496 }
50497
50498 /*
50499 ** Copy as much content as we can from the WAL back into the database file
50500 ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
50501 **
50502 ** The amount of information copies from WAL to database might be limited
50503 ** by active readers.  This routine will never overwrite a database page
50504 ** that a concurrent reader might be using.
50505 **
50506 ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
50507 ** SQLite is in WAL-mode in synchronous=NORMAL.  That means that if 
50508 ** checkpoints are always run by a background thread or background 
50509 ** process, foreground threads will never block on a lengthy fsync call.
50510 **
50511 ** Fsync is called on the WAL before writing content out of the WAL and
50512 ** into the database.  This ensures that if the new content is persistent
50513 ** in the WAL and can be recovered following a power-loss or hard reset.
50514 **
50515 ** Fsync is also called on the database file if (and only if) the entire
50516 ** WAL content is copied into the database file.  This second fsync makes
50517 ** it safe to delete the WAL since the new content will persist in the
50518 ** database file.
50519 **
50520 ** This routine uses and updates the nBackfill field of the wal-index header.
50521 ** This is the only routine that will increase the value of nBackfill.  
50522 ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
50523 ** its value.)
50524 **
50525 ** The caller must be holding sufficient locks to ensure that no other
50526 ** checkpoint is running (in any other thread or process) at the same
50527 ** time.
50528 */
50529 static int walCheckpoint(
50530   Wal *pWal,                      /* Wal connection */
50531   int eMode,                      /* One of PASSIVE, FULL or RESTART */
50532   int (*xBusy)(void*),            /* Function to call when busy */
50533   void *pBusyArg,                 /* Context argument for xBusyHandler */
50534   int sync_flags,                 /* Flags for OsSync() (or 0) */
50535   u8 *zBuf                        /* Temporary buffer to use */
50536 ){
50537   int rc = SQLITE_OK;             /* Return code */
50538   int szPage;                     /* Database page-size */
50539   WalIterator *pIter = 0;         /* Wal iterator context */
50540   u32 iDbpage = 0;                /* Next database page to write */
50541   u32 iFrame = 0;                 /* Wal frame containing data for iDbpage */
50542   u32 mxSafeFrame;                /* Max frame that can be backfilled */
50543   u32 mxPage;                     /* Max database page to write */
50544   int i;                          /* Loop counter */
50545   volatile WalCkptInfo *pInfo;    /* The checkpoint status information */
50546
50547   szPage = walPagesize(pWal);
50548   testcase( szPage<=32768 );
50549   testcase( szPage>=65536 );
50550   pInfo = walCkptInfo(pWal);
50551   if( pInfo->nBackfill<pWal->hdr.mxFrame ){
50552
50553     /* Allocate the iterator */
50554     rc = walIteratorInit(pWal, &pIter);
50555     if( rc!=SQLITE_OK ){
50556       return rc;
50557     }
50558     assert( pIter );
50559
50560     /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
50561     ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
50562     assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
50563
50564     /* Compute in mxSafeFrame the index of the last frame of the WAL that is
50565     ** safe to write into the database.  Frames beyond mxSafeFrame might
50566     ** overwrite database pages that are in use by active readers and thus
50567     ** cannot be backfilled from the WAL.
50568     */
50569     mxSafeFrame = pWal->hdr.mxFrame;
50570     mxPage = pWal->hdr.nPage;
50571     for(i=1; i<WAL_NREADER; i++){
50572       u32 y = pInfo->aReadMark[i];
50573       if( mxSafeFrame>y ){
50574         assert( y<=pWal->hdr.mxFrame );
50575         rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
50576         if( rc==SQLITE_OK ){
50577           pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
50578           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
50579         }else if( rc==SQLITE_BUSY ){
50580           mxSafeFrame = y;
50581           xBusy = 0;
50582         }else{
50583           goto walcheckpoint_out;
50584         }
50585       }
50586     }
50587
50588     if( pInfo->nBackfill<mxSafeFrame
50589      && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0),1))==SQLITE_OK
50590     ){
50591       i64 nSize;                    /* Current size of database file */
50592       u32 nBackfill = pInfo->nBackfill;
50593
50594       /* Sync the WAL to disk */
50595       if( sync_flags ){
50596         rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
50597       }
50598
50599       /* If the database may grow as a result of this checkpoint, hint
50600       ** about the eventual size of the db file to the VFS layer.
50601       */
50602       if( rc==SQLITE_OK ){
50603         i64 nReq = ((i64)mxPage * szPage);
50604         rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
50605         if( rc==SQLITE_OK && nSize<nReq ){
50606           sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
50607         }
50608       }
50609
50610
50611       /* Iterate through the contents of the WAL, copying data to the db file */
50612       while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
50613         i64 iOffset;
50614         assert( walFramePgno(pWal, iFrame)==iDbpage );
50615         if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ){
50616           continue;
50617         }
50618         iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
50619         /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
50620         rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
50621         if( rc!=SQLITE_OK ) break;
50622         iOffset = (iDbpage-1)*(i64)szPage;
50623         testcase( IS_BIG_INT(iOffset) );
50624         rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
50625         if( rc!=SQLITE_OK ) break;
50626       }
50627
50628       /* If work was actually accomplished... */
50629       if( rc==SQLITE_OK ){
50630         if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
50631           i64 szDb = pWal->hdr.nPage*(i64)szPage;
50632           testcase( IS_BIG_INT(szDb) );
50633           rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
50634           if( rc==SQLITE_OK && sync_flags ){
50635             rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
50636           }
50637         }
50638         if( rc==SQLITE_OK ){
50639           pInfo->nBackfill = mxSafeFrame;
50640         }
50641       }
50642
50643       /* Release the reader lock held while backfilling */
50644       walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
50645     }
50646
50647     if( rc==SQLITE_BUSY ){
50648       /* Reset the return code so as not to report a checkpoint failure
50649       ** just because there are active readers.  */
50650       rc = SQLITE_OK;
50651     }
50652   }
50653
50654   /* If this is an SQLITE_CHECKPOINT_RESTART or TRUNCATE operation, and the
50655   ** entire wal file has been copied into the database file, then block 
50656   ** until all readers have finished using the wal file. This ensures that 
50657   ** the next process to write to the database restarts the wal file.
50658   */
50659   if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
50660     assert( pWal->writeLock );
50661     if( pInfo->nBackfill<pWal->hdr.mxFrame ){
50662       rc = SQLITE_BUSY;
50663     }else if( eMode>=SQLITE_CHECKPOINT_RESTART ){
50664       u32 salt1;
50665       sqlite3_randomness(4, &salt1);
50666       assert( pInfo->nBackfill==pWal->hdr.mxFrame );
50667       rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
50668       if( rc==SQLITE_OK ){
50669         if( eMode==SQLITE_CHECKPOINT_TRUNCATE ){
50670           /* IMPLEMENTATION-OF: R-44699-57140 This mode works the same way as
50671           ** SQLITE_CHECKPOINT_RESTART with the addition that it also
50672           ** truncates the log file to zero bytes just prior to a
50673           ** successful return.
50674           **
50675           ** In theory, it might be safe to do this without updating the
50676           ** wal-index header in shared memory, as all subsequent reader or
50677           ** writer clients should see that the entire log file has been
50678           ** checkpointed and behave accordingly. This seems unsafe though,
50679           ** as it would leave the system in a state where the contents of
50680           ** the wal-index header do not match the contents of the 
50681           ** file-system. To avoid this, update the wal-index header to
50682           ** indicate that the log file contains zero valid frames.  */
50683           walRestartHdr(pWal, salt1);
50684           rc = sqlite3OsTruncate(pWal->pWalFd, 0);
50685         }
50686         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
50687       }
50688     }
50689   }
50690
50691  walcheckpoint_out:
50692   walIteratorFree(pIter);
50693   return rc;
50694 }
50695
50696 /*
50697 ** If the WAL file is currently larger than nMax bytes in size, truncate
50698 ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
50699 */
50700 static void walLimitSize(Wal *pWal, i64 nMax){
50701   i64 sz;
50702   int rx;
50703   sqlite3BeginBenignMalloc();
50704   rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
50705   if( rx==SQLITE_OK && (sz > nMax ) ){
50706     rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
50707   }
50708   sqlite3EndBenignMalloc();
50709   if( rx ){
50710     sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
50711   }
50712 }
50713
50714 /*
50715 ** Close a connection to a log file.
50716 */
50717 SQLITE_PRIVATE int sqlite3WalClose(
50718   Wal *pWal,                      /* Wal to close */
50719   int sync_flags,                 /* Flags to pass to OsSync() (or 0) */
50720   int nBuf,
50721   u8 *zBuf                        /* Buffer of at least nBuf bytes */
50722 ){
50723   int rc = SQLITE_OK;
50724   if( pWal ){
50725     int isDelete = 0;             /* True to unlink wal and wal-index files */
50726
50727     /* If an EXCLUSIVE lock can be obtained on the database file (using the
50728     ** ordinary, rollback-mode locking methods, this guarantees that the
50729     ** connection associated with this log file is the only connection to
50730     ** the database. In this case checkpoint the database and unlink both
50731     ** the wal and wal-index files.
50732     **
50733     ** The EXCLUSIVE lock is not released before returning.
50734     */
50735     rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
50736     if( rc==SQLITE_OK ){
50737       if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
50738         pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
50739       }
50740       rc = sqlite3WalCheckpoint(
50741           pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
50742       );
50743       if( rc==SQLITE_OK ){
50744         int bPersist = -1;
50745         sqlite3OsFileControlHint(
50746             pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
50747         );
50748         if( bPersist!=1 ){
50749           /* Try to delete the WAL file if the checkpoint completed and
50750           ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
50751           ** mode (!bPersist) */
50752           isDelete = 1;
50753         }else if( pWal->mxWalSize>=0 ){
50754           /* Try to truncate the WAL file to zero bytes if the checkpoint
50755           ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
50756           ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
50757           ** non-negative value (pWal->mxWalSize>=0).  Note that we truncate
50758           ** to zero bytes as truncating to the journal_size_limit might
50759           ** leave a corrupt WAL file on disk. */
50760           walLimitSize(pWal, 0);
50761         }
50762       }
50763     }
50764
50765     walIndexClose(pWal, isDelete);
50766     sqlite3OsClose(pWal->pWalFd);
50767     if( isDelete ){
50768       sqlite3BeginBenignMalloc();
50769       sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
50770       sqlite3EndBenignMalloc();
50771     }
50772     WALTRACE(("WAL%p: closed\n", pWal));
50773     sqlite3_free((void *)pWal->apWiData);
50774     sqlite3_free(pWal);
50775   }
50776   return rc;
50777 }
50778
50779 /*
50780 ** Try to read the wal-index header.  Return 0 on success and 1 if
50781 ** there is a problem.
50782 **
50783 ** The wal-index is in shared memory.  Another thread or process might
50784 ** be writing the header at the same time this procedure is trying to
50785 ** read it, which might result in inconsistency.  A dirty read is detected
50786 ** by verifying that both copies of the header are the same and also by
50787 ** a checksum on the header.
50788 **
50789 ** If and only if the read is consistent and the header is different from
50790 ** pWal->hdr, then pWal->hdr is updated to the content of the new header
50791 ** and *pChanged is set to 1.
50792 **
50793 ** If the checksum cannot be verified return non-zero. If the header
50794 ** is read successfully and the checksum verified, return zero.
50795 */
50796 static int walIndexTryHdr(Wal *pWal, int *pChanged){
50797   u32 aCksum[2];                  /* Checksum on the header content */
50798   WalIndexHdr h1, h2;             /* Two copies of the header content */
50799   WalIndexHdr volatile *aHdr;     /* Header in shared memory */
50800
50801   /* The first page of the wal-index must be mapped at this point. */
50802   assert( pWal->nWiData>0 && pWal->apWiData[0] );
50803
50804   /* Read the header. This might happen concurrently with a write to the
50805   ** same area of shared memory on a different CPU in a SMP,
50806   ** meaning it is possible that an inconsistent snapshot is read
50807   ** from the file. If this happens, return non-zero.
50808   **
50809   ** There are two copies of the header at the beginning of the wal-index.
50810   ** When reading, read [0] first then [1].  Writes are in the reverse order.
50811   ** Memory barriers are used to prevent the compiler or the hardware from
50812   ** reordering the reads and writes.
50813   */
50814   aHdr = walIndexHdr(pWal);
50815   memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
50816   walShmBarrier(pWal);
50817   memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
50818
50819   if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
50820     return 1;   /* Dirty read */
50821   }  
50822   if( h1.isInit==0 ){
50823     return 1;   /* Malformed header - probably all zeros */
50824   }
50825   walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
50826   if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
50827     return 1;   /* Checksum does not match */
50828   }
50829
50830   if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
50831     *pChanged = 1;
50832     memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
50833     pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
50834     testcase( pWal->szPage<=32768 );
50835     testcase( pWal->szPage>=65536 );
50836   }
50837
50838   /* The header was successfully read. Return zero. */
50839   return 0;
50840 }
50841
50842 /*
50843 ** Read the wal-index header from the wal-index and into pWal->hdr.
50844 ** If the wal-header appears to be corrupt, try to reconstruct the
50845 ** wal-index from the WAL before returning.
50846 **
50847 ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
50848 ** changed by this operation.  If pWal->hdr is unchanged, set *pChanged
50849 ** to 0.
50850 **
50851 ** If the wal-index header is successfully read, return SQLITE_OK. 
50852 ** Otherwise an SQLite error code.
50853 */
50854 static int walIndexReadHdr(Wal *pWal, int *pChanged){
50855   int rc;                         /* Return code */
50856   int badHdr;                     /* True if a header read failed */
50857   volatile u32 *page0;            /* Chunk of wal-index containing header */
50858
50859   /* Ensure that page 0 of the wal-index (the page that contains the 
50860   ** wal-index header) is mapped. Return early if an error occurs here.
50861   */
50862   assert( pChanged );
50863   rc = walIndexPage(pWal, 0, &page0);
50864   if( rc!=SQLITE_OK ){
50865     return rc;
50866   };
50867   assert( page0 || pWal->writeLock==0 );
50868
50869   /* If the first page of the wal-index has been mapped, try to read the
50870   ** wal-index header immediately, without holding any lock. This usually
50871   ** works, but may fail if the wal-index header is corrupt or currently 
50872   ** being modified by another thread or process.
50873   */
50874   badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
50875
50876   /* If the first attempt failed, it might have been due to a race
50877   ** with a writer.  So get a WRITE lock and try again.
50878   */
50879   assert( badHdr==0 || pWal->writeLock==0 );
50880   if( badHdr ){
50881     if( pWal->readOnly & WAL_SHM_RDONLY ){
50882       if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
50883         walUnlockShared(pWal, WAL_WRITE_LOCK);
50884         rc = SQLITE_READONLY_RECOVERY;
50885       }
50886     }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1, 1)) ){
50887       pWal->writeLock = 1;
50888       if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
50889         badHdr = walIndexTryHdr(pWal, pChanged);
50890         if( badHdr ){
50891           /* If the wal-index header is still malformed even while holding
50892           ** a WRITE lock, it can only mean that the header is corrupted and
50893           ** needs to be reconstructed.  So run recovery to do exactly that.
50894           */
50895           rc = walIndexRecover(pWal);
50896           *pChanged = 1;
50897         }
50898       }
50899       pWal->writeLock = 0;
50900       walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
50901     }
50902   }
50903
50904   /* If the header is read successfully, check the version number to make
50905   ** sure the wal-index was not constructed with some future format that
50906   ** this version of SQLite cannot understand.
50907   */
50908   if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
50909     rc = SQLITE_CANTOPEN_BKPT;
50910   }
50911
50912   return rc;
50913 }
50914
50915 /*
50916 ** This is the value that walTryBeginRead returns when it needs to
50917 ** be retried.
50918 */
50919 #define WAL_RETRY  (-1)
50920
50921 /*
50922 ** Attempt to start a read transaction.  This might fail due to a race or
50923 ** other transient condition.  When that happens, it returns WAL_RETRY to
50924 ** indicate to the caller that it is safe to retry immediately.
50925 **
50926 ** On success return SQLITE_OK.  On a permanent failure (such an
50927 ** I/O error or an SQLITE_BUSY because another process is running
50928 ** recovery) return a positive error code.
50929 **
50930 ** The useWal parameter is true to force the use of the WAL and disable
50931 ** the case where the WAL is bypassed because it has been completely
50932 ** checkpointed.  If useWal==0 then this routine calls walIndexReadHdr() 
50933 ** to make a copy of the wal-index header into pWal->hdr.  If the 
50934 ** wal-index header has changed, *pChanged is set to 1 (as an indication 
50935 ** to the caller that the local paget cache is obsolete and needs to be 
50936 ** flushed.)  When useWal==1, the wal-index header is assumed to already
50937 ** be loaded and the pChanged parameter is unused.
50938 **
50939 ** The caller must set the cnt parameter to the number of prior calls to
50940 ** this routine during the current read attempt that returned WAL_RETRY.
50941 ** This routine will start taking more aggressive measures to clear the
50942 ** race conditions after multiple WAL_RETRY returns, and after an excessive
50943 ** number of errors will ultimately return SQLITE_PROTOCOL.  The
50944 ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
50945 ** and is not honoring the locking protocol.  There is a vanishingly small
50946 ** chance that SQLITE_PROTOCOL could be returned because of a run of really
50947 ** bad luck when there is lots of contention for the wal-index, but that
50948 ** possibility is so small that it can be safely neglected, we believe.
50949 **
50950 ** On success, this routine obtains a read lock on 
50951 ** WAL_READ_LOCK(pWal->readLock).  The pWal->readLock integer is
50952 ** in the range 0 <= pWal->readLock < WAL_NREADER.  If pWal->readLock==(-1)
50953 ** that means the Wal does not hold any read lock.  The reader must not
50954 ** access any database page that is modified by a WAL frame up to and
50955 ** including frame number aReadMark[pWal->readLock].  The reader will
50956 ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
50957 ** Or if pWal->readLock==0, then the reader will ignore the WAL
50958 ** completely and get all content directly from the database file.
50959 ** If the useWal parameter is 1 then the WAL will never be ignored and
50960 ** this routine will always set pWal->readLock>0 on success.
50961 ** When the read transaction is completed, the caller must release the
50962 ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
50963 **
50964 ** This routine uses the nBackfill and aReadMark[] fields of the header
50965 ** to select a particular WAL_READ_LOCK() that strives to let the
50966 ** checkpoint process do as much work as possible.  This routine might
50967 ** update values of the aReadMark[] array in the header, but if it does
50968 ** so it takes care to hold an exclusive lock on the corresponding
50969 ** WAL_READ_LOCK() while changing values.
50970 */
50971 static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
50972   volatile WalCkptInfo *pInfo;    /* Checkpoint information in wal-index */
50973   u32 mxReadMark;                 /* Largest aReadMark[] value */
50974   int mxI;                        /* Index of largest aReadMark[] value */
50975   int i;                          /* Loop counter */
50976   int rc = SQLITE_OK;             /* Return code  */
50977
50978   assert( pWal->readLock<0 );     /* Not currently locked */
50979
50980   /* Take steps to avoid spinning forever if there is a protocol error.
50981   **
50982   ** Circumstances that cause a RETRY should only last for the briefest
50983   ** instances of time.  No I/O or other system calls are done while the
50984   ** locks are held, so the locks should not be held for very long. But 
50985   ** if we are unlucky, another process that is holding a lock might get
50986   ** paged out or take a page-fault that is time-consuming to resolve, 
50987   ** during the few nanoseconds that it is holding the lock.  In that case,
50988   ** it might take longer than normal for the lock to free.
50989   **
50990   ** After 5 RETRYs, we begin calling sqlite3OsSleep().  The first few
50991   ** calls to sqlite3OsSleep() have a delay of 1 microsecond.  Really this
50992   ** is more of a scheduler yield than an actual delay.  But on the 10th
50993   ** an subsequent retries, the delays start becoming longer and longer, 
50994   ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
50995   ** The total delay time before giving up is less than 10 seconds.
50996   */
50997   if( cnt>5 ){
50998     int nDelay = 1;                      /* Pause time in microseconds */
50999     if( cnt>100 ){
51000       VVA_ONLY( pWal->lockError = 1; )
51001       return SQLITE_PROTOCOL;
51002     }
51003     if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
51004     sqlite3OsSleep(pWal->pVfs, nDelay);
51005   }
51006
51007   if( !useWal ){
51008     rc = walIndexReadHdr(pWal, pChanged);
51009     if( rc==SQLITE_BUSY ){
51010       /* If there is not a recovery running in another thread or process
51011       ** then convert BUSY errors to WAL_RETRY.  If recovery is known to
51012       ** be running, convert BUSY to BUSY_RECOVERY.  There is a race here
51013       ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
51014       ** would be technically correct.  But the race is benign since with
51015       ** WAL_RETRY this routine will be called again and will probably be
51016       ** right on the second iteration.
51017       */
51018       if( pWal->apWiData[0]==0 ){
51019         /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
51020         ** We assume this is a transient condition, so return WAL_RETRY. The
51021         ** xShmMap() implementation used by the default unix and win32 VFS 
51022         ** modules may return SQLITE_BUSY due to a race condition in the 
51023         ** code that determines whether or not the shared-memory region 
51024         ** must be zeroed before the requested page is returned.
51025         */
51026         rc = WAL_RETRY;
51027       }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
51028         walUnlockShared(pWal, WAL_RECOVER_LOCK);
51029         rc = WAL_RETRY;
51030       }else if( rc==SQLITE_BUSY ){
51031         rc = SQLITE_BUSY_RECOVERY;
51032       }
51033     }
51034     if( rc!=SQLITE_OK ){
51035       return rc;
51036     }
51037   }
51038
51039   pInfo = walCkptInfo(pWal);
51040   if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
51041     /* The WAL has been completely backfilled (or it is empty).
51042     ** and can be safely ignored.
51043     */
51044     rc = walLockShared(pWal, WAL_READ_LOCK(0));
51045     walShmBarrier(pWal);
51046     if( rc==SQLITE_OK ){
51047       if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
51048         /* It is not safe to allow the reader to continue here if frames
51049         ** may have been appended to the log before READ_LOCK(0) was obtained.
51050         ** When holding READ_LOCK(0), the reader ignores the entire log file,
51051         ** which implies that the database file contains a trustworthy
51052         ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
51053         ** happening, this is usually correct.
51054         **
51055         ** However, if frames have been appended to the log (or if the log 
51056         ** is wrapped and written for that matter) before the READ_LOCK(0)
51057         ** is obtained, that is not necessarily true. A checkpointer may
51058         ** have started to backfill the appended frames but crashed before
51059         ** it finished. Leaving a corrupt image in the database file.
51060         */
51061         walUnlockShared(pWal, WAL_READ_LOCK(0));
51062         return WAL_RETRY;
51063       }
51064       pWal->readLock = 0;
51065       return SQLITE_OK;
51066     }else if( rc!=SQLITE_BUSY ){
51067       return rc;
51068     }
51069   }
51070
51071   /* If we get this far, it means that the reader will want to use
51072   ** the WAL to get at content from recent commits.  The job now is
51073   ** to select one of the aReadMark[] entries that is closest to
51074   ** but not exceeding pWal->hdr.mxFrame and lock that entry.
51075   */
51076   mxReadMark = 0;
51077   mxI = 0;
51078   for(i=1; i<WAL_NREADER; i++){
51079     u32 thisMark = pInfo->aReadMark[i];
51080     if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
51081       assert( thisMark!=READMARK_NOT_USED );
51082       mxReadMark = thisMark;
51083       mxI = i;
51084     }
51085   }
51086   /* There was once an "if" here. The extra "{" is to preserve indentation. */
51087   {
51088     if( (pWal->readOnly & WAL_SHM_RDONLY)==0
51089      && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
51090     ){
51091       for(i=1; i<WAL_NREADER; i++){
51092         rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1, 0);
51093         if( rc==SQLITE_OK ){
51094           mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
51095           mxI = i;
51096           walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
51097           break;
51098         }else if( rc!=SQLITE_BUSY ){
51099           return rc;
51100         }
51101       }
51102     }
51103     if( mxI==0 ){
51104       assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
51105       return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
51106     }
51107
51108     rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
51109     if( rc ){
51110       return rc==SQLITE_BUSY ? WAL_RETRY : rc;
51111     }
51112     /* Now that the read-lock has been obtained, check that neither the
51113     ** value in the aReadMark[] array or the contents of the wal-index
51114     ** header have changed.
51115     **
51116     ** It is necessary to check that the wal-index header did not change
51117     ** between the time it was read and when the shared-lock was obtained
51118     ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
51119     ** that the log file may have been wrapped by a writer, or that frames
51120     ** that occur later in the log than pWal->hdr.mxFrame may have been
51121     ** copied into the database by a checkpointer. If either of these things
51122     ** happened, then reading the database with the current value of
51123     ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
51124     ** instead.
51125     **
51126     ** This does not guarantee that the copy of the wal-index header is up to
51127     ** date before proceeding. That would not be possible without somehow
51128     ** blocking writers. It only guarantees that a dangerous checkpoint or 
51129     ** log-wrap (either of which would require an exclusive lock on
51130     ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
51131     */
51132     walShmBarrier(pWal);
51133     if( pInfo->aReadMark[mxI]!=mxReadMark
51134      || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
51135     ){
51136       walUnlockShared(pWal, WAL_READ_LOCK(mxI));
51137       return WAL_RETRY;
51138     }else{
51139       assert( mxReadMark<=pWal->hdr.mxFrame );
51140       pWal->readLock = (i16)mxI;
51141     }
51142   }
51143   return rc;
51144 }
51145
51146 /*
51147 ** Begin a read transaction on the database.
51148 **
51149 ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
51150 ** it takes a snapshot of the state of the WAL and wal-index for the current
51151 ** instant in time.  The current thread will continue to use this snapshot.
51152 ** Other threads might append new content to the WAL and wal-index but
51153 ** that extra content is ignored by the current thread.
51154 **
51155 ** If the database contents have changes since the previous read
51156 ** transaction, then *pChanged is set to 1 before returning.  The
51157 ** Pager layer will use this to know that is cache is stale and
51158 ** needs to be flushed.
51159 */
51160 SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
51161   int rc;                         /* Return code */
51162   int cnt = 0;                    /* Number of TryBeginRead attempts */
51163
51164   do{
51165     rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
51166   }while( rc==WAL_RETRY );
51167   testcase( (rc&0xff)==SQLITE_BUSY );
51168   testcase( (rc&0xff)==SQLITE_IOERR );
51169   testcase( rc==SQLITE_PROTOCOL );
51170   testcase( rc==SQLITE_OK );
51171   return rc;
51172 }
51173
51174 /*
51175 ** Finish with a read transaction.  All this does is release the
51176 ** read-lock.
51177 */
51178 SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
51179   sqlite3WalEndWriteTransaction(pWal);
51180   if( pWal->readLock>=0 ){
51181     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
51182     pWal->readLock = -1;
51183   }
51184 }
51185
51186 /*
51187 ** Search the wal file for page pgno. If found, set *piRead to the frame that
51188 ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
51189 ** to zero.
51190 **
51191 ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
51192 ** error does occur, the final value of *piRead is undefined.
51193 */
51194 SQLITE_PRIVATE int sqlite3WalFindFrame(
51195   Wal *pWal,                      /* WAL handle */
51196   Pgno pgno,                      /* Database page number to read data for */
51197   u32 *piRead                     /* OUT: Frame number (or zero) */
51198 ){
51199   u32 iRead = 0;                  /* If !=0, WAL frame to return data from */
51200   u32 iLast = pWal->hdr.mxFrame;  /* Last page in WAL for this reader */
51201   int iHash;                      /* Used to loop through N hash tables */
51202
51203   /* This routine is only be called from within a read transaction. */
51204   assert( pWal->readLock>=0 || pWal->lockError );
51205
51206   /* If the "last page" field of the wal-index header snapshot is 0, then
51207   ** no data will be read from the wal under any circumstances. Return early
51208   ** in this case as an optimization.  Likewise, if pWal->readLock==0, 
51209   ** then the WAL is ignored by the reader so return early, as if the 
51210   ** WAL were empty.
51211   */
51212   if( iLast==0 || pWal->readLock==0 ){
51213     *piRead = 0;
51214     return SQLITE_OK;
51215   }
51216
51217   /* Search the hash table or tables for an entry matching page number
51218   ** pgno. Each iteration of the following for() loop searches one
51219   ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
51220   **
51221   ** This code might run concurrently to the code in walIndexAppend()
51222   ** that adds entries to the wal-index (and possibly to this hash 
51223   ** table). This means the value just read from the hash 
51224   ** slot (aHash[iKey]) may have been added before or after the 
51225   ** current read transaction was opened. Values added after the
51226   ** read transaction was opened may have been written incorrectly -
51227   ** i.e. these slots may contain garbage data. However, we assume
51228   ** that any slots written before the current read transaction was
51229   ** opened remain unmodified.
51230   **
51231   ** For the reasons above, the if(...) condition featured in the inner
51232   ** loop of the following block is more stringent that would be required 
51233   ** if we had exclusive access to the hash-table:
51234   **
51235   **   (aPgno[iFrame]==pgno): 
51236   **     This condition filters out normal hash-table collisions.
51237   **
51238   **   (iFrame<=iLast): 
51239   **     This condition filters out entries that were added to the hash
51240   **     table after the current read-transaction had started.
51241   */
51242   for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
51243     volatile ht_slot *aHash;      /* Pointer to hash table */
51244     volatile u32 *aPgno;          /* Pointer to array of page numbers */
51245     u32 iZero;                    /* Frame number corresponding to aPgno[0] */
51246     int iKey;                     /* Hash slot index */
51247     int nCollide;                 /* Number of hash collisions remaining */
51248     int rc;                       /* Error code */
51249
51250     rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
51251     if( rc!=SQLITE_OK ){
51252       return rc;
51253     }
51254     nCollide = HASHTABLE_NSLOT;
51255     for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
51256       u32 iFrame = aHash[iKey] + iZero;
51257       if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
51258         assert( iFrame>iRead || CORRUPT_DB );
51259         iRead = iFrame;
51260       }
51261       if( (nCollide--)==0 ){
51262         return SQLITE_CORRUPT_BKPT;
51263       }
51264     }
51265   }
51266
51267 #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
51268   /* If expensive assert() statements are available, do a linear search
51269   ** of the wal-index file content. Make sure the results agree with the
51270   ** result obtained using the hash indexes above.  */
51271   {
51272     u32 iRead2 = 0;
51273     u32 iTest;
51274     for(iTest=iLast; iTest>0; iTest--){
51275       if( walFramePgno(pWal, iTest)==pgno ){
51276         iRead2 = iTest;
51277         break;
51278       }
51279     }
51280     assert( iRead==iRead2 );
51281   }
51282 #endif
51283
51284   *piRead = iRead;
51285   return SQLITE_OK;
51286 }
51287
51288 /*
51289 ** Read the contents of frame iRead from the wal file into buffer pOut
51290 ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
51291 ** error code otherwise.
51292 */
51293 SQLITE_PRIVATE int sqlite3WalReadFrame(
51294   Wal *pWal,                      /* WAL handle */
51295   u32 iRead,                      /* Frame to read */
51296   int nOut,                       /* Size of buffer pOut in bytes */
51297   u8 *pOut                        /* Buffer to write page data to */
51298 ){
51299   int sz;
51300   i64 iOffset;
51301   sz = pWal->hdr.szPage;
51302   sz = (sz&0xfe00) + ((sz&0x0001)<<16);
51303   testcase( sz<=32768 );
51304   testcase( sz>=65536 );
51305   iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
51306   /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
51307   return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
51308 }
51309
51310 /* 
51311 ** Return the size of the database in pages (or zero, if unknown).
51312 */
51313 SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
51314   if( pWal && ALWAYS(pWal->readLock>=0) ){
51315     return pWal->hdr.nPage;
51316   }
51317   return 0;
51318 }
51319
51320
51321 /* 
51322 ** This function starts a write transaction on the WAL.
51323 **
51324 ** A read transaction must have already been started by a prior call
51325 ** to sqlite3WalBeginReadTransaction().
51326 **
51327 ** If another thread or process has written into the database since
51328 ** the read transaction was started, then it is not possible for this
51329 ** thread to write as doing so would cause a fork.  So this routine
51330 ** returns SQLITE_BUSY in that case and no write transaction is started.
51331 **
51332 ** There can only be a single writer active at a time.
51333 */
51334 SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
51335   int rc;
51336
51337   /* Cannot start a write transaction without first holding a read
51338   ** transaction. */
51339   assert( pWal->readLock>=0 );
51340
51341   if( pWal->readOnly ){
51342     return SQLITE_READONLY;
51343   }
51344
51345   /* Only one writer allowed at a time.  Get the write lock.  Return
51346   ** SQLITE_BUSY if unable.
51347   */
51348   rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1, 0);
51349   if( rc ){
51350     return rc;
51351   }
51352   pWal->writeLock = 1;
51353
51354   /* If another connection has written to the database file since the
51355   ** time the read transaction on this connection was started, then
51356   ** the write is disallowed.
51357   */
51358   if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
51359     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
51360     pWal->writeLock = 0;
51361     rc = SQLITE_BUSY_SNAPSHOT;
51362   }
51363
51364   return rc;
51365 }
51366
51367 /*
51368 ** End a write transaction.  The commit has already been done.  This
51369 ** routine merely releases the lock.
51370 */
51371 SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
51372   if( pWal->writeLock ){
51373     walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
51374     pWal->writeLock = 0;
51375     pWal->truncateOnCommit = 0;
51376   }
51377   return SQLITE_OK;
51378 }
51379
51380 /*
51381 ** If any data has been written (but not committed) to the log file, this
51382 ** function moves the write-pointer back to the start of the transaction.
51383 **
51384 ** Additionally, the callback function is invoked for each frame written
51385 ** to the WAL since the start of the transaction. If the callback returns
51386 ** other than SQLITE_OK, it is not invoked again and the error code is
51387 ** returned to the caller.
51388 **
51389 ** Otherwise, if the callback function does not return an error, this
51390 ** function returns SQLITE_OK.
51391 */
51392 SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
51393   int rc = SQLITE_OK;
51394   if( ALWAYS(pWal->writeLock) ){
51395     Pgno iMax = pWal->hdr.mxFrame;
51396     Pgno iFrame;
51397   
51398     /* Restore the clients cache of the wal-index header to the state it
51399     ** was in before the client began writing to the database. 
51400     */
51401     memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
51402
51403     for(iFrame=pWal->hdr.mxFrame+1; 
51404         ALWAYS(rc==SQLITE_OK) && iFrame<=iMax; 
51405         iFrame++
51406     ){
51407       /* This call cannot fail. Unless the page for which the page number
51408       ** is passed as the second argument is (a) in the cache and 
51409       ** (b) has an outstanding reference, then xUndo is either a no-op
51410       ** (if (a) is false) or simply expels the page from the cache (if (b)
51411       ** is false).
51412       **
51413       ** If the upper layer is doing a rollback, it is guaranteed that there
51414       ** are no outstanding references to any page other than page 1. And
51415       ** page 1 is never written to the log until the transaction is
51416       ** committed. As a result, the call to xUndo may not fail.
51417       */
51418       assert( walFramePgno(pWal, iFrame)!=1 );
51419       rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
51420     }
51421     if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
51422   }
51423   return rc;
51424 }
51425
51426 /* 
51427 ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32 
51428 ** values. This function populates the array with values required to 
51429 ** "rollback" the write position of the WAL handle back to the current 
51430 ** point in the event of a savepoint rollback (via WalSavepointUndo()).
51431 */
51432 SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
51433   assert( pWal->writeLock );
51434   aWalData[0] = pWal->hdr.mxFrame;
51435   aWalData[1] = pWal->hdr.aFrameCksum[0];
51436   aWalData[2] = pWal->hdr.aFrameCksum[1];
51437   aWalData[3] = pWal->nCkpt;
51438 }
51439
51440 /* 
51441 ** Move the write position of the WAL back to the point identified by
51442 ** the values in the aWalData[] array. aWalData must point to an array
51443 ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
51444 ** by a call to WalSavepoint().
51445 */
51446 SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
51447   int rc = SQLITE_OK;
51448
51449   assert( pWal->writeLock );
51450   assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
51451
51452   if( aWalData[3]!=pWal->nCkpt ){
51453     /* This savepoint was opened immediately after the write-transaction
51454     ** was started. Right after that, the writer decided to wrap around
51455     ** to the start of the log. Update the savepoint values to match.
51456     */
51457     aWalData[0] = 0;
51458     aWalData[3] = pWal->nCkpt;
51459   }
51460
51461   if( aWalData[0]<pWal->hdr.mxFrame ){
51462     pWal->hdr.mxFrame = aWalData[0];
51463     pWal->hdr.aFrameCksum[0] = aWalData[1];
51464     pWal->hdr.aFrameCksum[1] = aWalData[2];
51465     walCleanupHash(pWal);
51466   }
51467
51468   return rc;
51469 }
51470
51471 /*
51472 ** This function is called just before writing a set of frames to the log
51473 ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
51474 ** to the current log file, it is possible to overwrite the start of the
51475 ** existing log file with the new frames (i.e. "reset" the log). If so,
51476 ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
51477 ** unchanged.
51478 **
51479 ** SQLITE_OK is returned if no error is encountered (regardless of whether
51480 ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
51481 ** if an error occurs.
51482 */
51483 static int walRestartLog(Wal *pWal){
51484   int rc = SQLITE_OK;
51485   int cnt;
51486
51487   if( pWal->readLock==0 ){
51488     volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
51489     assert( pInfo->nBackfill==pWal->hdr.mxFrame );
51490     if( pInfo->nBackfill>0 ){
51491       u32 salt1;
51492       sqlite3_randomness(4, &salt1);
51493       rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1, 0);
51494       if( rc==SQLITE_OK ){
51495         /* If all readers are using WAL_READ_LOCK(0) (in other words if no
51496         ** readers are currently using the WAL), then the transactions
51497         ** frames will overwrite the start of the existing log. Update the
51498         ** wal-index header to reflect this.
51499         **
51500         ** In theory it would be Ok to update the cache of the header only
51501         ** at this point. But updating the actual wal-index header is also
51502         ** safe and means there is no special case for sqlite3WalUndo()
51503         ** to handle if this transaction is rolled back.  */
51504         walRestartHdr(pWal, salt1);
51505         walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
51506       }else if( rc!=SQLITE_BUSY ){
51507         return rc;
51508       }
51509     }
51510     walUnlockShared(pWal, WAL_READ_LOCK(0));
51511     pWal->readLock = -1;
51512     cnt = 0;
51513     do{
51514       int notUsed;
51515       rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
51516     }while( rc==WAL_RETRY );
51517     assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
51518     testcase( (rc&0xff)==SQLITE_IOERR );
51519     testcase( rc==SQLITE_PROTOCOL );
51520     testcase( rc==SQLITE_OK );
51521   }
51522   return rc;
51523 }
51524
51525 /*
51526 ** Information about the current state of the WAL file and where
51527 ** the next fsync should occur - passed from sqlite3WalFrames() into
51528 ** walWriteToLog().
51529 */
51530 typedef struct WalWriter {
51531   Wal *pWal;                   /* The complete WAL information */
51532   sqlite3_file *pFd;           /* The WAL file to which we write */
51533   sqlite3_int64 iSyncPoint;    /* Fsync at this offset */
51534   int syncFlags;               /* Flags for the fsync */
51535   int szPage;                  /* Size of one page */
51536 } WalWriter;
51537
51538 /*
51539 ** Write iAmt bytes of content into the WAL file beginning at iOffset.
51540 ** Do a sync when crossing the p->iSyncPoint boundary.
51541 **
51542 ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
51543 ** first write the part before iSyncPoint, then sync, then write the
51544 ** rest.
51545 */
51546 static int walWriteToLog(
51547   WalWriter *p,              /* WAL to write to */
51548   void *pContent,            /* Content to be written */
51549   int iAmt,                  /* Number of bytes to write */
51550   sqlite3_int64 iOffset      /* Start writing at this offset */
51551 ){
51552   int rc;
51553   if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
51554     int iFirstAmt = (int)(p->iSyncPoint - iOffset);
51555     rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
51556     if( rc ) return rc;
51557     iOffset += iFirstAmt;
51558     iAmt -= iFirstAmt;
51559     pContent = (void*)(iFirstAmt + (char*)pContent);
51560     assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
51561     rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
51562     if( iAmt==0 || rc ) return rc;
51563   }
51564   rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
51565   return rc;
51566 }
51567
51568 /*
51569 ** Write out a single frame of the WAL
51570 */
51571 static int walWriteOneFrame(
51572   WalWriter *p,               /* Where to write the frame */
51573   PgHdr *pPage,               /* The page of the frame to be written */
51574   int nTruncate,              /* The commit flag.  Usually 0.  >0 for commit */
51575   sqlite3_int64 iOffset       /* Byte offset at which to write */
51576 ){
51577   int rc;                         /* Result code from subfunctions */
51578   void *pData;                    /* Data actually written */
51579   u8 aFrame[WAL_FRAME_HDRSIZE];   /* Buffer to assemble frame-header in */
51580 #if defined(SQLITE_HAS_CODEC)
51581   if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
51582 #else
51583   pData = pPage->pData;
51584 #endif
51585   walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
51586   rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
51587   if( rc ) return rc;
51588   /* Write the page data */
51589   rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
51590   return rc;
51591 }
51592
51593 /* 
51594 ** Write a set of frames to the log. The caller must hold the write-lock
51595 ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
51596 */
51597 SQLITE_PRIVATE int sqlite3WalFrames(
51598   Wal *pWal,                      /* Wal handle to write to */
51599   int szPage,                     /* Database page-size in bytes */
51600   PgHdr *pList,                   /* List of dirty pages to write */
51601   Pgno nTruncate,                 /* Database size after this commit */
51602   int isCommit,                   /* True if this is a commit */
51603   int sync_flags                  /* Flags to pass to OsSync() (or 0) */
51604 ){
51605   int rc;                         /* Used to catch return codes */
51606   u32 iFrame;                     /* Next frame address */
51607   PgHdr *p;                       /* Iterator to run through pList with. */
51608   PgHdr *pLast = 0;               /* Last frame in list */
51609   int nExtra = 0;                 /* Number of extra copies of last page */
51610   int szFrame;                    /* The size of a single frame */
51611   i64 iOffset;                    /* Next byte to write in WAL file */
51612   WalWriter w;                    /* The writer */
51613
51614   assert( pList );
51615   assert( pWal->writeLock );
51616
51617   /* If this frame set completes a transaction, then nTruncate>0.  If
51618   ** nTruncate==0 then this frame set does not complete the transaction. */
51619   assert( (isCommit!=0)==(nTruncate!=0) );
51620
51621 #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
51622   { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
51623     WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
51624               pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
51625   }
51626 #endif
51627
51628   /* See if it is possible to write these frames into the start of the
51629   ** log file, instead of appending to it at pWal->hdr.mxFrame.
51630   */
51631   if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
51632     return rc;
51633   }
51634
51635   /* If this is the first frame written into the log, write the WAL
51636   ** header to the start of the WAL file. See comments at the top of
51637   ** this source file for a description of the WAL header format.
51638   */
51639   iFrame = pWal->hdr.mxFrame;
51640   if( iFrame==0 ){
51641     u8 aWalHdr[WAL_HDRSIZE];      /* Buffer to assemble wal-header in */
51642     u32 aCksum[2];                /* Checksum for wal-header */
51643
51644     sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
51645     sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
51646     sqlite3Put4byte(&aWalHdr[8], szPage);
51647     sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
51648     if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
51649     memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
51650     walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
51651     sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
51652     sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
51653     
51654     pWal->szPage = szPage;
51655     pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
51656     pWal->hdr.aFrameCksum[0] = aCksum[0];
51657     pWal->hdr.aFrameCksum[1] = aCksum[1];
51658     pWal->truncateOnCommit = 1;
51659
51660     rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
51661     WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
51662     if( rc!=SQLITE_OK ){
51663       return rc;
51664     }
51665
51666     /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
51667     ** all syncing is turned off by PRAGMA synchronous=OFF).  Otherwise
51668     ** an out-of-order write following a WAL restart could result in
51669     ** database corruption.  See the ticket:
51670     **
51671     **     http://localhost:591/sqlite/info/ff5be73dee
51672     */
51673     if( pWal->syncHeader && sync_flags ){
51674       rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
51675       if( rc ) return rc;
51676     }
51677   }
51678   assert( (int)pWal->szPage==szPage );
51679
51680   /* Setup information needed to write frames into the WAL */
51681   w.pWal = pWal;
51682   w.pFd = pWal->pWalFd;
51683   w.iSyncPoint = 0;
51684   w.syncFlags = sync_flags;
51685   w.szPage = szPage;
51686   iOffset = walFrameOffset(iFrame+1, szPage);
51687   szFrame = szPage + WAL_FRAME_HDRSIZE;
51688
51689   /* Write all frames into the log file exactly once */
51690   for(p=pList; p; p=p->pDirty){
51691     int nDbSize;   /* 0 normally.  Positive == commit flag */
51692     iFrame++;
51693     assert( iOffset==walFrameOffset(iFrame, szPage) );
51694     nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
51695     rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
51696     if( rc ) return rc;
51697     pLast = p;
51698     iOffset += szFrame;
51699   }
51700
51701   /* If this is the end of a transaction, then we might need to pad
51702   ** the transaction and/or sync the WAL file.
51703   **
51704   ** Padding and syncing only occur if this set of frames complete a
51705   ** transaction and if PRAGMA synchronous=FULL.  If synchronous==NORMAL
51706   ** or synchronous==OFF, then no padding or syncing are needed.
51707   **
51708   ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
51709   ** needed and only the sync is done.  If padding is needed, then the
51710   ** final frame is repeated (with its commit mark) until the next sector
51711   ** boundary is crossed.  Only the part of the WAL prior to the last
51712   ** sector boundary is synced; the part of the last frame that extends
51713   ** past the sector boundary is written after the sync.
51714   */
51715   if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
51716     if( pWal->padToSectorBoundary ){
51717       int sectorSize = sqlite3SectorSize(pWal->pWalFd);
51718       w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
51719       while( iOffset<w.iSyncPoint ){
51720         rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
51721         if( rc ) return rc;
51722         iOffset += szFrame;
51723         nExtra++;
51724       }
51725     }else{
51726       rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
51727     }
51728   }
51729
51730   /* If this frame set completes the first transaction in the WAL and
51731   ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
51732   ** journal size limit, if possible.
51733   */
51734   if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
51735     i64 sz = pWal->mxWalSize;
51736     if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
51737       sz = walFrameOffset(iFrame+nExtra+1, szPage);
51738     }
51739     walLimitSize(pWal, sz);
51740     pWal->truncateOnCommit = 0;
51741   }
51742
51743   /* Append data to the wal-index. It is not necessary to lock the 
51744   ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
51745   ** guarantees that there are no other writers, and no data that may
51746   ** be in use by existing readers is being overwritten.
51747   */
51748   iFrame = pWal->hdr.mxFrame;
51749   for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
51750     iFrame++;
51751     rc = walIndexAppend(pWal, iFrame, p->pgno);
51752   }
51753   while( rc==SQLITE_OK && nExtra>0 ){
51754     iFrame++;
51755     nExtra--;
51756     rc = walIndexAppend(pWal, iFrame, pLast->pgno);
51757   }
51758
51759   if( rc==SQLITE_OK ){
51760     /* Update the private copy of the header. */
51761     pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
51762     testcase( szPage<=32768 );
51763     testcase( szPage>=65536 );
51764     pWal->hdr.mxFrame = iFrame;
51765     if( isCommit ){
51766       pWal->hdr.iChange++;
51767       pWal->hdr.nPage = nTruncate;
51768     }
51769     /* If this is a commit, update the wal-index header too. */
51770     if( isCommit ){
51771       walIndexWriteHdr(pWal);
51772       pWal->iCallback = iFrame;
51773     }
51774   }
51775
51776   WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
51777   return rc;
51778 }
51779
51780 /* 
51781 ** This routine is called to implement sqlite3_wal_checkpoint() and
51782 ** related interfaces.
51783 **
51784 ** Obtain a CHECKPOINT lock and then backfill as much information as
51785 ** we can from WAL into the database.
51786 **
51787 ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
51788 ** callback. In this case this function runs a blocking checkpoint.
51789 */
51790 SQLITE_PRIVATE int sqlite3WalCheckpoint(
51791   Wal *pWal,                      /* Wal connection */
51792   int eMode,                      /* PASSIVE, FULL, RESTART, or TRUNCATE */
51793   int (*xBusy)(void*),            /* Function to call when busy */
51794   void *pBusyArg,                 /* Context argument for xBusyHandler */
51795   int sync_flags,                 /* Flags to sync db file with (or 0) */
51796   int nBuf,                       /* Size of temporary buffer */
51797   u8 *zBuf,                       /* Temporary buffer to use */
51798   int *pnLog,                     /* OUT: Number of frames in WAL */
51799   int *pnCkpt                     /* OUT: Number of backfilled frames in WAL */
51800 ){
51801   int rc;                         /* Return code */
51802   int isChanged = 0;              /* True if a new wal-index header is loaded */
51803   int eMode2 = eMode;             /* Mode to pass to walCheckpoint() */
51804   int (*xBusy2)(void*) = xBusy;   /* Busy handler for eMode2 */
51805
51806   assert( pWal->ckptLock==0 );
51807   assert( pWal->writeLock==0 );
51808
51809   /* EVIDENCE-OF: R-62920-47450 The busy-handler callback is never invoked
51810   ** in the SQLITE_CHECKPOINT_PASSIVE mode. */
51811   assert( eMode!=SQLITE_CHECKPOINT_PASSIVE || xBusy==0 );
51812
51813   if( pWal->readOnly ) return SQLITE_READONLY;
51814   WALTRACE(("WAL%p: checkpoint begins\n", pWal));
51815
51816   /* IMPLEMENTATION-OF: R-62028-47212 All calls obtain an exclusive 
51817   ** "checkpoint" lock on the database file. */
51818   rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1, 0);
51819   if( rc ){
51820     /* EVIDENCE-OF: R-10421-19736 If any other process is running a
51821     ** checkpoint operation at the same time, the lock cannot be obtained and
51822     ** SQLITE_BUSY is returned.
51823     ** EVIDENCE-OF: R-53820-33897 Even if there is a busy-handler configured,
51824     ** it will not be invoked in this case.
51825     */
51826     testcase( rc==SQLITE_BUSY );
51827     testcase( xBusy!=0 );
51828     return rc;
51829   }
51830   pWal->ckptLock = 1;
51831
51832   /* IMPLEMENTATION-OF: R-59782-36818 The SQLITE_CHECKPOINT_FULL, RESTART and
51833   ** TRUNCATE modes also obtain the exclusive "writer" lock on the database
51834   ** file.
51835   **
51836   ** EVIDENCE-OF: R-60642-04082 If the writer lock cannot be obtained
51837   ** immediately, and a busy-handler is configured, it is invoked and the
51838   ** writer lock retried until either the busy-handler returns 0 or the
51839   ** lock is successfully obtained.
51840   */
51841   if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
51842     rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
51843     if( rc==SQLITE_OK ){
51844       pWal->writeLock = 1;
51845     }else if( rc==SQLITE_BUSY ){
51846       eMode2 = SQLITE_CHECKPOINT_PASSIVE;
51847       xBusy2 = 0;
51848       rc = SQLITE_OK;
51849     }
51850   }
51851
51852   /* Read the wal-index header. */
51853   if( rc==SQLITE_OK ){
51854     rc = walIndexReadHdr(pWal, &isChanged);
51855     if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
51856       sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
51857     }
51858   }
51859
51860   /* Copy data from the log to the database file. */
51861   if( rc==SQLITE_OK ){
51862     if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
51863       rc = SQLITE_CORRUPT_BKPT;
51864     }else{
51865       rc = walCheckpoint(pWal, eMode2, xBusy2, pBusyArg, sync_flags, zBuf);
51866     }
51867
51868     /* If no error occurred, set the output variables. */
51869     if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
51870       if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
51871       if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
51872     }
51873   }
51874
51875   if( isChanged ){
51876     /* If a new wal-index header was loaded before the checkpoint was 
51877     ** performed, then the pager-cache associated with pWal is now
51878     ** out of date. So zero the cached wal-index header to ensure that
51879     ** next time the pager opens a snapshot on this database it knows that
51880     ** the cache needs to be reset.
51881     */
51882     memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
51883   }
51884
51885   /* Release the locks. */
51886   sqlite3WalEndWriteTransaction(pWal);
51887   walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
51888   pWal->ckptLock = 0;
51889   WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
51890   return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
51891 }
51892
51893 /* Return the value to pass to a sqlite3_wal_hook callback, the
51894 ** number of frames in the WAL at the point of the last commit since
51895 ** sqlite3WalCallback() was called.  If no commits have occurred since
51896 ** the last call, then return 0.
51897 */
51898 SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
51899   u32 ret = 0;
51900   if( pWal ){
51901     ret = pWal->iCallback;
51902     pWal->iCallback = 0;
51903   }
51904   return (int)ret;
51905 }
51906
51907 /*
51908 ** This function is called to change the WAL subsystem into or out
51909 ** of locking_mode=EXCLUSIVE.
51910 **
51911 ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
51912 ** into locking_mode=NORMAL.  This means that we must acquire a lock
51913 ** on the pWal->readLock byte.  If the WAL is already in locking_mode=NORMAL
51914 ** or if the acquisition of the lock fails, then return 0.  If the
51915 ** transition out of exclusive-mode is successful, return 1.  This
51916 ** operation must occur while the pager is still holding the exclusive
51917 ** lock on the main database file.
51918 **
51919 ** If op is one, then change from locking_mode=NORMAL into 
51920 ** locking_mode=EXCLUSIVE.  This means that the pWal->readLock must
51921 ** be released.  Return 1 if the transition is made and 0 if the
51922 ** WAL is already in exclusive-locking mode - meaning that this
51923 ** routine is a no-op.  The pager must already hold the exclusive lock
51924 ** on the main database file before invoking this operation.
51925 **
51926 ** If op is negative, then do a dry-run of the op==1 case but do
51927 ** not actually change anything. The pager uses this to see if it
51928 ** should acquire the database exclusive lock prior to invoking
51929 ** the op==1 case.
51930 */
51931 SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
51932   int rc;
51933   assert( pWal->writeLock==0 );
51934   assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
51935
51936   /* pWal->readLock is usually set, but might be -1 if there was a 
51937   ** prior error while attempting to acquire are read-lock. This cannot 
51938   ** happen if the connection is actually in exclusive mode (as no xShmLock
51939   ** locks are taken in this case). Nor should the pager attempt to
51940   ** upgrade to exclusive-mode following such an error.
51941   */
51942   assert( pWal->readLock>=0 || pWal->lockError );
51943   assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
51944
51945   if( op==0 ){
51946     if( pWal->exclusiveMode ){
51947       pWal->exclusiveMode = 0;
51948       if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
51949         pWal->exclusiveMode = 1;
51950       }
51951       rc = pWal->exclusiveMode==0;
51952     }else{
51953       /* Already in locking_mode=NORMAL */
51954       rc = 0;
51955     }
51956   }else if( op>0 ){
51957     assert( pWal->exclusiveMode==0 );
51958     assert( pWal->readLock>=0 );
51959     walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
51960     pWal->exclusiveMode = 1;
51961     rc = 1;
51962   }else{
51963     rc = pWal->exclusiveMode==0;
51964   }
51965   return rc;
51966 }
51967
51968 /* 
51969 ** Return true if the argument is non-NULL and the WAL module is using
51970 ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
51971 ** WAL module is using shared-memory, return false. 
51972 */
51973 SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
51974   return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
51975 }
51976
51977 #ifdef SQLITE_ENABLE_ZIPVFS
51978 /*
51979 ** If the argument is not NULL, it points to a Wal object that holds a
51980 ** read-lock. This function returns the database page-size if it is known,
51981 ** or zero if it is not (or if pWal is NULL).
51982 */
51983 SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
51984   assert( pWal==0 || pWal->readLock>=0 );
51985   return (pWal ? pWal->szPage : 0);
51986 }
51987 #endif
51988
51989 #endif /* #ifndef SQLITE_OMIT_WAL */
51990
51991 /************** End of wal.c *************************************************/
51992 /************** Begin file btmutex.c *****************************************/
51993 /*
51994 ** 2007 August 27
51995 **
51996 ** The author disclaims copyright to this source code.  In place of
51997 ** a legal notice, here is a blessing:
51998 **
51999 **    May you do good and not evil.
52000 **    May you find forgiveness for yourself and forgive others.
52001 **    May you share freely, never taking more than you give.
52002 **
52003 *************************************************************************
52004 **
52005 ** This file contains code used to implement mutexes on Btree objects.
52006 ** This code really belongs in btree.c.  But btree.c is getting too
52007 ** big and we want to break it down some.  This packaged seemed like
52008 ** a good breakout.
52009 */
52010 /************** Include btreeInt.h in the middle of btmutex.c ****************/
52011 /************** Begin file btreeInt.h ****************************************/
52012 /*
52013 ** 2004 April 6
52014 **
52015 ** The author disclaims copyright to this source code.  In place of
52016 ** a legal notice, here is a blessing:
52017 **
52018 **    May you do good and not evil.
52019 **    May you find forgiveness for yourself and forgive others.
52020 **    May you share freely, never taking more than you give.
52021 **
52022 *************************************************************************
52023 ** This file implements an external (disk-based) database using BTrees.
52024 ** For a detailed discussion of BTrees, refer to
52025 **
52026 **     Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
52027 **     "Sorting And Searching", pages 473-480. Addison-Wesley
52028 **     Publishing Company, Reading, Massachusetts.
52029 **
52030 ** The basic idea is that each page of the file contains N database
52031 ** entries and N+1 pointers to subpages.
52032 **
52033 **   ----------------------------------------------------------------
52034 **   |  Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
52035 **   ----------------------------------------------------------------
52036 **
52037 ** All of the keys on the page that Ptr(0) points to have values less
52038 ** than Key(0).  All of the keys on page Ptr(1) and its subpages have
52039 ** values greater than Key(0) and less than Key(1).  All of the keys
52040 ** on Ptr(N) and its subpages have values greater than Key(N-1).  And
52041 ** so forth.
52042 **
52043 ** Finding a particular key requires reading O(log(M)) pages from the 
52044 ** disk where M is the number of entries in the tree.
52045 **
52046 ** In this implementation, a single file can hold one or more separate 
52047 ** BTrees.  Each BTree is identified by the index of its root page.  The
52048 ** key and data for any entry are combined to form the "payload".  A
52049 ** fixed amount of payload can be carried directly on the database
52050 ** page.  If the payload is larger than the preset amount then surplus
52051 ** bytes are stored on overflow pages.  The payload for an entry
52052 ** and the preceding pointer are combined to form a "Cell".  Each 
52053 ** page has a small header which contains the Ptr(N) pointer and other
52054 ** information such as the size of key and data.
52055 **
52056 ** FORMAT DETAILS
52057 **
52058 ** The file is divided into pages.  The first page is called page 1,
52059 ** the second is page 2, and so forth.  A page number of zero indicates
52060 ** "no such page".  The page size can be any power of 2 between 512 and 65536.
52061 ** Each page can be either a btree page, a freelist page, an overflow
52062 ** page, or a pointer-map page.
52063 **
52064 ** The first page is always a btree page.  The first 100 bytes of the first
52065 ** page contain a special header (the "file header") that describes the file.
52066 ** The format of the file header is as follows:
52067 **
52068 **   OFFSET   SIZE    DESCRIPTION
52069 **      0      16     Header string: "SQLite format 3\000"
52070 **     16       2     Page size in bytes.  (1 means 65536)
52071 **     18       1     File format write version
52072 **     19       1     File format read version
52073 **     20       1     Bytes of unused space at the end of each page
52074 **     21       1     Max embedded payload fraction (must be 64)
52075 **     22       1     Min embedded payload fraction (must be 32)
52076 **     23       1     Min leaf payload fraction (must be 32)
52077 **     24       4     File change counter
52078 **     28       4     Reserved for future use
52079 **     32       4     First freelist page
52080 **     36       4     Number of freelist pages in the file
52081 **     40      60     15 4-byte meta values passed to higher layers
52082 **
52083 **     40       4     Schema cookie
52084 **     44       4     File format of schema layer
52085 **     48       4     Size of page cache
52086 **     52       4     Largest root-page (auto/incr_vacuum)
52087 **     56       4     1=UTF-8 2=UTF16le 3=UTF16be
52088 **     60       4     User version
52089 **     64       4     Incremental vacuum mode
52090 **     68       4     Application-ID
52091 **     72      20     unused
52092 **     92       4     The version-valid-for number
52093 **     96       4     SQLITE_VERSION_NUMBER
52094 **
52095 ** All of the integer values are big-endian (most significant byte first).
52096 **
52097 ** The file change counter is incremented when the database is changed
52098 ** This counter allows other processes to know when the file has changed
52099 ** and thus when they need to flush their cache.
52100 **
52101 ** The max embedded payload fraction is the amount of the total usable
52102 ** space in a page that can be consumed by a single cell for standard
52103 ** B-tree (non-LEAFDATA) tables.  A value of 255 means 100%.  The default
52104 ** is to limit the maximum cell size so that at least 4 cells will fit
52105 ** on one page.  Thus the default max embedded payload fraction is 64.
52106 **
52107 ** If the payload for a cell is larger than the max payload, then extra
52108 ** payload is spilled to overflow pages.  Once an overflow page is allocated,
52109 ** as many bytes as possible are moved into the overflow pages without letting
52110 ** the cell size drop below the min embedded payload fraction.
52111 **
52112 ** The min leaf payload fraction is like the min embedded payload fraction
52113 ** except that it applies to leaf nodes in a LEAFDATA tree.  The maximum
52114 ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
52115 ** not specified in the header.
52116 **
52117 ** Each btree pages is divided into three sections:  The header, the
52118 ** cell pointer array, and the cell content area.  Page 1 also has a 100-byte
52119 ** file header that occurs before the page header.
52120 **
52121 **      |----------------|
52122 **      | file header    |   100 bytes.  Page 1 only.
52123 **      |----------------|
52124 **      | page header    |   8 bytes for leaves.  12 bytes for interior nodes
52125 **      |----------------|
52126 **      | cell pointer   |   |  2 bytes per cell.  Sorted order.
52127 **      | array          |   |  Grows downward
52128 **      |                |   v
52129 **      |----------------|
52130 **      | unallocated    |
52131 **      | space          |
52132 **      |----------------|   ^  Grows upwards
52133 **      | cell content   |   |  Arbitrary order interspersed with freeblocks.
52134 **      | area           |   |  and free space fragments.
52135 **      |----------------|
52136 **
52137 ** The page headers looks like this:
52138 **
52139 **   OFFSET   SIZE     DESCRIPTION
52140 **      0       1      Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
52141 **      1       2      byte offset to the first freeblock
52142 **      3       2      number of cells on this page
52143 **      5       2      first byte of the cell content area
52144 **      7       1      number of fragmented free bytes
52145 **      8       4      Right child (the Ptr(N) value).  Omitted on leaves.
52146 **
52147 ** The flags define the format of this btree page.  The leaf flag means that
52148 ** this page has no children.  The zerodata flag means that this page carries
52149 ** only keys and no data.  The intkey flag means that the key is an integer
52150 ** which is stored in the key size entry of the cell header rather than in
52151 ** the payload area.
52152 **
52153 ** The cell pointer array begins on the first byte after the page header.
52154 ** The cell pointer array contains zero or more 2-byte numbers which are
52155 ** offsets from the beginning of the page to the cell content in the cell
52156 ** content area.  The cell pointers occur in sorted order.  The system strives
52157 ** to keep free space after the last cell pointer so that new cells can
52158 ** be easily added without having to defragment the page.
52159 **
52160 ** Cell content is stored at the very end of the page and grows toward the
52161 ** beginning of the page.
52162 **
52163 ** Unused space within the cell content area is collected into a linked list of
52164 ** freeblocks.  Each freeblock is at least 4 bytes in size.  The byte offset
52165 ** to the first freeblock is given in the header.  Freeblocks occur in
52166 ** increasing order.  Because a freeblock must be at least 4 bytes in size,
52167 ** any group of 3 or fewer unused bytes in the cell content area cannot
52168 ** exist on the freeblock chain.  A group of 3 or fewer free bytes is called
52169 ** a fragment.  The total number of bytes in all fragments is recorded.
52170 ** in the page header at offset 7.
52171 **
52172 **    SIZE    DESCRIPTION
52173 **      2     Byte offset of the next freeblock
52174 **      2     Bytes in this freeblock
52175 **
52176 ** Cells are of variable length.  Cells are stored in the cell content area at
52177 ** the end of the page.  Pointers to the cells are in the cell pointer array
52178 ** that immediately follows the page header.  Cells is not necessarily
52179 ** contiguous or in order, but cell pointers are contiguous and in order.
52180 **
52181 ** Cell content makes use of variable length integers.  A variable
52182 ** length integer is 1 to 9 bytes where the lower 7 bits of each 
52183 ** byte are used.  The integer consists of all bytes that have bit 8 set and
52184 ** the first byte with bit 8 clear.  The most significant byte of the integer
52185 ** appears first.  A variable-length integer may not be more than 9 bytes long.
52186 ** As a special case, all 8 bytes of the 9th byte are used as data.  This
52187 ** allows a 64-bit integer to be encoded in 9 bytes.
52188 **
52189 **    0x00                      becomes  0x00000000
52190 **    0x7f                      becomes  0x0000007f
52191 **    0x81 0x00                 becomes  0x00000080
52192 **    0x82 0x00                 becomes  0x00000100
52193 **    0x80 0x7f                 becomes  0x0000007f
52194 **    0x8a 0x91 0xd1 0xac 0x78  becomes  0x12345678
52195 **    0x81 0x81 0x81 0x81 0x01  becomes  0x10204081
52196 **
52197 ** Variable length integers are used for rowids and to hold the number of
52198 ** bytes of key and data in a btree cell.
52199 **
52200 ** The content of a cell looks like this:
52201 **
52202 **    SIZE    DESCRIPTION
52203 **      4     Page number of the left child. Omitted if leaf flag is set.
52204 **     var    Number of bytes of data. Omitted if the zerodata flag is set.
52205 **     var    Number of bytes of key. Or the key itself if intkey flag is set.
52206 **      *     Payload
52207 **      4     First page of the overflow chain.  Omitted if no overflow
52208 **
52209 ** Overflow pages form a linked list.  Each page except the last is completely
52210 ** filled with data (pagesize - 4 bytes).  The last page can have as little
52211 ** as 1 byte of data.
52212 **
52213 **    SIZE    DESCRIPTION
52214 **      4     Page number of next overflow page
52215 **      *     Data
52216 **
52217 ** Freelist pages come in two subtypes: trunk pages and leaf pages.  The
52218 ** file header points to the first in a linked list of trunk page.  Each trunk
52219 ** page points to multiple leaf pages.  The content of a leaf page is
52220 ** unspecified.  A trunk page looks like this:
52221 **
52222 **    SIZE    DESCRIPTION
52223 **      4     Page number of next trunk page
52224 **      4     Number of leaf pointers on this page
52225 **      *     zero or more pages numbers of leaves
52226 */
52227
52228
52229 /* The following value is the maximum cell size assuming a maximum page
52230 ** size give above.
52231 */
52232 #define MX_CELL_SIZE(pBt)  ((int)(pBt->pageSize-8))
52233
52234 /* The maximum number of cells on a single page of the database.  This
52235 ** assumes a minimum cell size of 6 bytes  (4 bytes for the cell itself
52236 ** plus 2 bytes for the index to the cell in the page header).  Such
52237 ** small cells will be rare, but they are possible.
52238 */
52239 #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
52240
52241 /* Forward declarations */
52242 typedef struct MemPage MemPage;
52243 typedef struct BtLock BtLock;
52244
52245 /*
52246 ** This is a magic string that appears at the beginning of every
52247 ** SQLite database in order to identify the file as a real database.
52248 **
52249 ** You can change this value at compile-time by specifying a
52250 ** -DSQLITE_FILE_HEADER="..." on the compiler command-line.  The
52251 ** header must be exactly 16 bytes including the zero-terminator so
52252 ** the string itself should be 15 characters long.  If you change
52253 ** the header, then your custom library will not be able to read 
52254 ** databases generated by the standard tools and the standard tools
52255 ** will not be able to read databases created by your custom library.
52256 */
52257 #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
52258 #  define SQLITE_FILE_HEADER "SQLite format 3"
52259 #endif
52260
52261 /*
52262 ** Page type flags.  An ORed combination of these flags appear as the
52263 ** first byte of on-disk image of every BTree page.
52264 */
52265 #define PTF_INTKEY    0x01
52266 #define PTF_ZERODATA  0x02
52267 #define PTF_LEAFDATA  0x04
52268 #define PTF_LEAF      0x08
52269
52270 /*
52271 ** As each page of the file is loaded into memory, an instance of the following
52272 ** structure is appended and initialized to zero.  This structure stores
52273 ** information about the page that is decoded from the raw file page.
52274 **
52275 ** The pParent field points back to the parent page.  This allows us to
52276 ** walk up the BTree from any leaf to the root.  Care must be taken to
52277 ** unref() the parent page pointer when this page is no longer referenced.
52278 ** The pageDestructor() routine handles that chore.
52279 **
52280 ** Access to all fields of this structure is controlled by the mutex
52281 ** stored in MemPage.pBt->mutex.
52282 */
52283 struct MemPage {
52284   u8 isInit;           /* True if previously initialized. MUST BE FIRST! */
52285   u8 nOverflow;        /* Number of overflow cell bodies in aCell[] */
52286   u8 intKey;           /* True if table b-trees.  False for index b-trees */
52287   u8 intKeyLeaf;       /* True if the leaf of an intKey table */
52288   u8 noPayload;        /* True if internal intKey page (thus w/o data) */
52289   u8 leaf;             /* True if a leaf page */
52290   u8 hdrOffset;        /* 100 for page 1.  0 otherwise */
52291   u8 childPtrSize;     /* 0 if leaf==1.  4 if leaf==0 */
52292   u8 max1bytePayload;  /* min(maxLocal,127) */
52293   u8 bBusy;            /* Prevent endless loops on corrupt database files */
52294   u16 maxLocal;        /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
52295   u16 minLocal;        /* Copy of BtShared.minLocal or BtShared.minLeaf */
52296   u16 cellOffset;      /* Index in aData of first cell pointer */
52297   u16 nFree;           /* Number of free bytes on the page */
52298   u16 nCell;           /* Number of cells on this page, local and ovfl */
52299   u16 maskPage;        /* Mask for page offset */
52300   u16 aiOvfl[5];       /* Insert the i-th overflow cell before the aiOvfl-th
52301                        ** non-overflow cell */
52302   u8 *apOvfl[5];       /* Pointers to the body of overflow cells */
52303   BtShared *pBt;       /* Pointer to BtShared that this page is part of */
52304   u8 *aData;           /* Pointer to disk image of the page data */
52305   u8 *aDataEnd;        /* One byte past the end of usable data */
52306   u8 *aCellIdx;        /* The cell index area */
52307   DbPage *pDbPage;     /* Pager page handle */
52308   Pgno pgno;           /* Page number for this page */
52309 };
52310
52311 /*
52312 ** The in-memory image of a disk page has the auxiliary information appended
52313 ** to the end.  EXTRA_SIZE is the number of bytes of space needed to hold
52314 ** that extra information.
52315 */
52316 #define EXTRA_SIZE sizeof(MemPage)
52317
52318 /*
52319 ** A linked list of the following structures is stored at BtShared.pLock.
52320 ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor 
52321 ** is opened on the table with root page BtShared.iTable. Locks are removed
52322 ** from this list when a transaction is committed or rolled back, or when
52323 ** a btree handle is closed.
52324 */
52325 struct BtLock {
52326   Btree *pBtree;        /* Btree handle holding this lock */
52327   Pgno iTable;          /* Root page of table */
52328   u8 eLock;             /* READ_LOCK or WRITE_LOCK */
52329   BtLock *pNext;        /* Next in BtShared.pLock list */
52330 };
52331
52332 /* Candidate values for BtLock.eLock */
52333 #define READ_LOCK     1
52334 #define WRITE_LOCK    2
52335
52336 /* A Btree handle
52337 **
52338 ** A database connection contains a pointer to an instance of
52339 ** this object for every database file that it has open.  This structure
52340 ** is opaque to the database connection.  The database connection cannot
52341 ** see the internals of this structure and only deals with pointers to
52342 ** this structure.
52343 **
52344 ** For some database files, the same underlying database cache might be 
52345 ** shared between multiple connections.  In that case, each connection
52346 ** has it own instance of this object.  But each instance of this object
52347 ** points to the same BtShared object.  The database cache and the
52348 ** schema associated with the database file are all contained within
52349 ** the BtShared object.
52350 **
52351 ** All fields in this structure are accessed under sqlite3.mutex.
52352 ** The pBt pointer itself may not be changed while there exists cursors 
52353 ** in the referenced BtShared that point back to this Btree since those
52354 ** cursors have to go through this Btree to find their BtShared and
52355 ** they often do so without holding sqlite3.mutex.
52356 */
52357 struct Btree {
52358   sqlite3 *db;       /* The database connection holding this btree */
52359   BtShared *pBt;     /* Sharable content of this btree */
52360   u8 inTrans;        /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
52361   u8 sharable;       /* True if we can share pBt with another db */
52362   u8 locked;         /* True if db currently has pBt locked */
52363   int wantToLock;    /* Number of nested calls to sqlite3BtreeEnter() */
52364   int nBackup;       /* Number of backup operations reading this btree */
52365   u32 iDataVersion;  /* Combines with pBt->pPager->iDataVersion */
52366   Btree *pNext;      /* List of other sharable Btrees from the same db */
52367   Btree *pPrev;      /* Back pointer of the same list */
52368 #ifndef SQLITE_OMIT_SHARED_CACHE
52369   BtLock lock;       /* Object used to lock page 1 */
52370 #endif
52371 };
52372
52373 /*
52374 ** Btree.inTrans may take one of the following values.
52375 **
52376 ** If the shared-data extension is enabled, there may be multiple users
52377 ** of the Btree structure. At most one of these may open a write transaction,
52378 ** but any number may have active read transactions.
52379 */
52380 #define TRANS_NONE  0
52381 #define TRANS_READ  1
52382 #define TRANS_WRITE 2
52383
52384 /*
52385 ** An instance of this object represents a single database file.
52386 ** 
52387 ** A single database file can be in use at the same time by two
52388 ** or more database connections.  When two or more connections are
52389 ** sharing the same database file, each connection has it own
52390 ** private Btree object for the file and each of those Btrees points
52391 ** to this one BtShared object.  BtShared.nRef is the number of
52392 ** connections currently sharing this database file.
52393 **
52394 ** Fields in this structure are accessed under the BtShared.mutex
52395 ** mutex, except for nRef and pNext which are accessed under the
52396 ** global SQLITE_MUTEX_STATIC_MASTER mutex.  The pPager field
52397 ** may not be modified once it is initially set as long as nRef>0.
52398 ** The pSchema field may be set once under BtShared.mutex and
52399 ** thereafter is unchanged as long as nRef>0.
52400 **
52401 ** isPending:
52402 **
52403 **   If a BtShared client fails to obtain a write-lock on a database
52404 **   table (because there exists one or more read-locks on the table),
52405 **   the shared-cache enters 'pending-lock' state and isPending is
52406 **   set to true.
52407 **
52408 **   The shared-cache leaves the 'pending lock' state when either of
52409 **   the following occur:
52410 **
52411 **     1) The current writer (BtShared.pWriter) concludes its transaction, OR
52412 **     2) The number of locks held by other connections drops to zero.
52413 **
52414 **   while in the 'pending-lock' state, no connection may start a new
52415 **   transaction.
52416 **
52417 **   This feature is included to help prevent writer-starvation.
52418 */
52419 struct BtShared {
52420   Pager *pPager;        /* The page cache */
52421   sqlite3 *db;          /* Database connection currently using this Btree */
52422   BtCursor *pCursor;    /* A list of all open cursors */
52423   MemPage *pPage1;      /* First page of the database */
52424   u8 openFlags;         /* Flags to sqlite3BtreeOpen() */
52425 #ifndef SQLITE_OMIT_AUTOVACUUM
52426   u8 autoVacuum;        /* True if auto-vacuum is enabled */
52427   u8 incrVacuum;        /* True if incr-vacuum is enabled */
52428   u8 bDoTruncate;       /* True to truncate db on commit */
52429 #endif
52430   u8 inTransaction;     /* Transaction state */
52431   u8 max1bytePayload;   /* Maximum first byte of cell for a 1-byte payload */
52432 #ifdef SQLITE_HAS_CODEC
52433   u8 optimalReserve;    /* Desired amount of reserved space per page */
52434 #endif
52435   u16 btsFlags;         /* Boolean parameters.  See BTS_* macros below */
52436   u16 maxLocal;         /* Maximum local payload in non-LEAFDATA tables */
52437   u16 minLocal;         /* Minimum local payload in non-LEAFDATA tables */
52438   u16 maxLeaf;          /* Maximum local payload in a LEAFDATA table */
52439   u16 minLeaf;          /* Minimum local payload in a LEAFDATA table */
52440   u32 pageSize;         /* Total number of bytes on a page */
52441   u32 usableSize;       /* Number of usable bytes on each page */
52442   int nTransaction;     /* Number of open transactions (read + write) */
52443   u32 nPage;            /* Number of pages in the database */
52444   void *pSchema;        /* Pointer to space allocated by sqlite3BtreeSchema() */
52445   void (*xFreeSchema)(void*);  /* Destructor for BtShared.pSchema */
52446   sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
52447   Bitvec *pHasContent;  /* Set of pages moved to free-list this transaction */
52448 #ifndef SQLITE_OMIT_SHARED_CACHE
52449   int nRef;             /* Number of references to this structure */
52450   BtShared *pNext;      /* Next on a list of sharable BtShared structs */
52451   BtLock *pLock;        /* List of locks held on this shared-btree struct */
52452   Btree *pWriter;       /* Btree with currently open write transaction */
52453 #endif
52454   u8 *pTmpSpace;        /* Temp space sufficient to hold a single cell */
52455 };
52456
52457 /*
52458 ** Allowed values for BtShared.btsFlags
52459 */
52460 #define BTS_READ_ONLY        0x0001   /* Underlying file is readonly */
52461 #define BTS_PAGESIZE_FIXED   0x0002   /* Page size can no longer be changed */
52462 #define BTS_SECURE_DELETE    0x0004   /* PRAGMA secure_delete is enabled */
52463 #define BTS_INITIALLY_EMPTY  0x0008   /* Database was empty at trans start */
52464 #define BTS_NO_WAL           0x0010   /* Do not open write-ahead-log files */
52465 #define BTS_EXCLUSIVE        0x0020   /* pWriter has an exclusive lock */
52466 #define BTS_PENDING          0x0040   /* Waiting for read-locks to clear */
52467
52468 /*
52469 ** An instance of the following structure is used to hold information
52470 ** about a cell.  The parseCellPtr() function fills in this structure
52471 ** based on information extract from the raw disk page.
52472 */
52473 typedef struct CellInfo CellInfo;
52474 struct CellInfo {
52475   i64 nKey;      /* The key for INTKEY tables, or nPayload otherwise */
52476   u8 *pPayload;  /* Pointer to the start of payload */
52477   u32 nPayload;  /* Bytes of payload */
52478   u16 nLocal;    /* Amount of payload held locally, not on overflow */
52479   u16 iOverflow; /* Offset to overflow page number.  Zero if no overflow */
52480   u16 nSize;     /* Size of the cell content on the main b-tree page */
52481 };
52482
52483 /*
52484 ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
52485 ** this will be declared corrupt. This value is calculated based on a
52486 ** maximum database size of 2^31 pages a minimum fanout of 2 for a
52487 ** root-node and 3 for all other internal nodes.
52488 **
52489 ** If a tree that appears to be taller than this is encountered, it is
52490 ** assumed that the database is corrupt.
52491 */
52492 #define BTCURSOR_MAX_DEPTH 20
52493
52494 /*
52495 ** A cursor is a pointer to a particular entry within a particular
52496 ** b-tree within a database file.
52497 **
52498 ** The entry is identified by its MemPage and the index in
52499 ** MemPage.aCell[] of the entry.
52500 **
52501 ** A single database file can be shared by two more database connections,
52502 ** but cursors cannot be shared.  Each cursor is associated with a
52503 ** particular database connection identified BtCursor.pBtree.db.
52504 **
52505 ** Fields in this structure are accessed under the BtShared.mutex
52506 ** found at self->pBt->mutex. 
52507 **
52508 ** skipNext meaning:
52509 **    eState==SKIPNEXT && skipNext>0:  Next sqlite3BtreeNext() is no-op.
52510 **    eState==SKIPNEXT && skipNext<0:  Next sqlite3BtreePrevious() is no-op.
52511 **    eState==FAULT:                   Cursor fault with skipNext as error code.
52512 */
52513 struct BtCursor {
52514   Btree *pBtree;            /* The Btree to which this cursor belongs */
52515   BtShared *pBt;            /* The BtShared this cursor points to */
52516   BtCursor *pNext, *pPrev;  /* Forms a linked list of all cursors */
52517   struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
52518   Pgno *aOverflow;          /* Cache of overflow page locations */
52519   CellInfo info;            /* A parse of the cell we are pointing at */
52520   i64 nKey;                 /* Size of pKey, or last integer key */
52521   void *pKey;               /* Saved key that was cursor last known position */
52522   Pgno pgnoRoot;            /* The root page of this tree */
52523   int nOvflAlloc;           /* Allocated size of aOverflow[] array */
52524   int skipNext;    /* Prev() is noop if negative. Next() is noop if positive.
52525                    ** Error code if eState==CURSOR_FAULT */
52526   u8 curFlags;              /* zero or more BTCF_* flags defined below */
52527   u8 eState;                /* One of the CURSOR_XXX constants (see below) */
52528   u8 hints;                             /* As configured by CursorSetHints() */
52529   i16 iPage;                            /* Index of current page in apPage */
52530   u16 aiIdx[BTCURSOR_MAX_DEPTH];        /* Current index in apPage[i] */
52531   MemPage *apPage[BTCURSOR_MAX_DEPTH];  /* Pages from root to current page */
52532 };
52533
52534 /*
52535 ** Legal values for BtCursor.curFlags
52536 */
52537 #define BTCF_WriteFlag    0x01   /* True if a write cursor */
52538 #define BTCF_ValidNKey    0x02   /* True if info.nKey is valid */
52539 #define BTCF_ValidOvfl    0x04   /* True if aOverflow is valid */
52540 #define BTCF_AtLast       0x08   /* Cursor is pointing ot the last entry */
52541 #define BTCF_Incrblob     0x10   /* True if an incremental I/O handle */
52542
52543 /*
52544 ** Potential values for BtCursor.eState.
52545 **
52546 ** CURSOR_INVALID:
52547 **   Cursor does not point to a valid entry. This can happen (for example) 
52548 **   because the table is empty or because BtreeCursorFirst() has not been
52549 **   called.
52550 **
52551 ** CURSOR_VALID:
52552 **   Cursor points to a valid entry. getPayload() etc. may be called.
52553 **
52554 ** CURSOR_SKIPNEXT:
52555 **   Cursor is valid except that the Cursor.skipNext field is non-zero
52556 **   indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
52557 **   operation should be a no-op.
52558 **
52559 ** CURSOR_REQUIRESEEK:
52560 **   The table that this cursor was opened on still exists, but has been 
52561 **   modified since the cursor was last used. The cursor position is saved
52562 **   in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in 
52563 **   this state, restoreCursorPosition() can be called to attempt to
52564 **   seek the cursor to the saved position.
52565 **
52566 ** CURSOR_FAULT:
52567 **   An unrecoverable error (an I/O error or a malloc failure) has occurred
52568 **   on a different connection that shares the BtShared cache with this
52569 **   cursor.  The error has left the cache in an inconsistent state.
52570 **   Do nothing else with this cursor.  Any attempt to use the cursor
52571 **   should return the error code stored in BtCursor.skipNext
52572 */
52573 #define CURSOR_INVALID           0
52574 #define CURSOR_VALID             1
52575 #define CURSOR_SKIPNEXT          2
52576 #define CURSOR_REQUIRESEEK       3
52577 #define CURSOR_FAULT             4
52578
52579 /* 
52580 ** The database page the PENDING_BYTE occupies. This page is never used.
52581 */
52582 # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
52583
52584 /*
52585 ** These macros define the location of the pointer-map entry for a 
52586 ** database page. The first argument to each is the number of usable
52587 ** bytes on each page of the database (often 1024). The second is the
52588 ** page number to look up in the pointer map.
52589 **
52590 ** PTRMAP_PAGENO returns the database page number of the pointer-map
52591 ** page that stores the required pointer. PTRMAP_PTROFFSET returns
52592 ** the offset of the requested map entry.
52593 **
52594 ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
52595 ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
52596 ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
52597 ** this test.
52598 */
52599 #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
52600 #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
52601 #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
52602
52603 /*
52604 ** The pointer map is a lookup table that identifies the parent page for
52605 ** each child page in the database file.  The parent page is the page that
52606 ** contains a pointer to the child.  Every page in the database contains
52607 ** 0 or 1 parent pages.  (In this context 'database page' refers
52608 ** to any page that is not part of the pointer map itself.)  Each pointer map
52609 ** entry consists of a single byte 'type' and a 4 byte parent page number.
52610 ** The PTRMAP_XXX identifiers below are the valid types.
52611 **
52612 ** The purpose of the pointer map is to facility moving pages from one
52613 ** position in the file to another as part of autovacuum.  When a page
52614 ** is moved, the pointer in its parent must be updated to point to the
52615 ** new location.  The pointer map is used to locate the parent page quickly.
52616 **
52617 ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
52618 **                  used in this case.
52619 **
52620 ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number 
52621 **                  is not used in this case.
52622 **
52623 ** PTRMAP_OVERFLOW1: The database page is the first page in a list of 
52624 **                   overflow pages. The page number identifies the page that
52625 **                   contains the cell with a pointer to this overflow page.
52626 **
52627 ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
52628 **                   overflow pages. The page-number identifies the previous
52629 **                   page in the overflow page list.
52630 **
52631 ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
52632 **               identifies the parent page in the btree.
52633 */
52634 #define PTRMAP_ROOTPAGE 1
52635 #define PTRMAP_FREEPAGE 2
52636 #define PTRMAP_OVERFLOW1 3
52637 #define PTRMAP_OVERFLOW2 4
52638 #define PTRMAP_BTREE 5
52639
52640 /* A bunch of assert() statements to check the transaction state variables
52641 ** of handle p (type Btree*) are internally consistent.
52642 */
52643 #define btreeIntegrity(p) \
52644   assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
52645   assert( p->pBt->inTransaction>=p->inTrans ); 
52646
52647
52648 /*
52649 ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
52650 ** if the database supports auto-vacuum or not. Because it is used
52651 ** within an expression that is an argument to another macro 
52652 ** (sqliteMallocRaw), it is not possible to use conditional compilation.
52653 ** So, this macro is defined instead.
52654 */
52655 #ifndef SQLITE_OMIT_AUTOVACUUM
52656 #define ISAUTOVACUUM (pBt->autoVacuum)
52657 #else
52658 #define ISAUTOVACUUM 0
52659 #endif
52660
52661
52662 /*
52663 ** This structure is passed around through all the sanity checking routines
52664 ** in order to keep track of some global state information.
52665 **
52666 ** The aRef[] array is allocated so that there is 1 bit for each page in
52667 ** the database. As the integrity-check proceeds, for each page used in
52668 ** the database the corresponding bit is set. This allows integrity-check to 
52669 ** detect pages that are used twice and orphaned pages (both of which 
52670 ** indicate corruption).
52671 */
52672 typedef struct IntegrityCk IntegrityCk;
52673 struct IntegrityCk {
52674   BtShared *pBt;    /* The tree being checked out */
52675   Pager *pPager;    /* The associated pager.  Also accessible by pBt->pPager */
52676   u8 *aPgRef;       /* 1 bit per page in the db (see above) */
52677   Pgno nPage;       /* Number of pages in the database */
52678   int mxErr;        /* Stop accumulating errors when this reaches zero */
52679   int nErr;         /* Number of messages written to zErrMsg so far */
52680   int mallocFailed; /* A memory allocation error has occurred */
52681   const char *zPfx; /* Error message prefix */
52682   int v1, v2;       /* Values for up to two %d fields in zPfx */
52683   StrAccum errMsg;  /* Accumulate the error message text here */
52684 };
52685
52686 /*
52687 ** Routines to read or write a two- and four-byte big-endian integer values.
52688 */
52689 #define get2byte(x)   ((x)[0]<<8 | (x)[1])
52690 #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
52691 #define get4byte sqlite3Get4byte
52692 #define put4byte sqlite3Put4byte
52693
52694 /************** End of btreeInt.h ********************************************/
52695 /************** Continuing where we left off in btmutex.c ********************/
52696 #ifndef SQLITE_OMIT_SHARED_CACHE
52697 #if SQLITE_THREADSAFE
52698
52699 /*
52700 ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
52701 ** set BtShared.db to the database handle associated with p and the
52702 ** p->locked boolean to true.
52703 */
52704 static void lockBtreeMutex(Btree *p){
52705   assert( p->locked==0 );
52706   assert( sqlite3_mutex_notheld(p->pBt->mutex) );
52707   assert( sqlite3_mutex_held(p->db->mutex) );
52708
52709   sqlite3_mutex_enter(p->pBt->mutex);
52710   p->pBt->db = p->db;
52711   p->locked = 1;
52712 }
52713
52714 /*
52715 ** Release the BtShared mutex associated with B-Tree handle p and
52716 ** clear the p->locked boolean.
52717 */
52718 static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
52719   BtShared *pBt = p->pBt;
52720   assert( p->locked==1 );
52721   assert( sqlite3_mutex_held(pBt->mutex) );
52722   assert( sqlite3_mutex_held(p->db->mutex) );
52723   assert( p->db==pBt->db );
52724
52725   sqlite3_mutex_leave(pBt->mutex);
52726   p->locked = 0;
52727 }
52728
52729 /* Forward reference */
52730 static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
52731
52732 /*
52733 ** Enter a mutex on the given BTree object.
52734 **
52735 ** If the object is not sharable, then no mutex is ever required
52736 ** and this routine is a no-op.  The underlying mutex is non-recursive.
52737 ** But we keep a reference count in Btree.wantToLock so the behavior
52738 ** of this interface is recursive.
52739 **
52740 ** To avoid deadlocks, multiple Btrees are locked in the same order
52741 ** by all database connections.  The p->pNext is a list of other
52742 ** Btrees belonging to the same database connection as the p Btree
52743 ** which need to be locked after p.  If we cannot get a lock on
52744 ** p, then first unlock all of the others on p->pNext, then wait
52745 ** for the lock to become available on p, then relock all of the
52746 ** subsequent Btrees that desire a lock.
52747 */
52748 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
52749   /* Some basic sanity checking on the Btree.  The list of Btrees
52750   ** connected by pNext and pPrev should be in sorted order by
52751   ** Btree.pBt value. All elements of the list should belong to
52752   ** the same connection. Only shared Btrees are on the list. */
52753   assert( p->pNext==0 || p->pNext->pBt>p->pBt );
52754   assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
52755   assert( p->pNext==0 || p->pNext->db==p->db );
52756   assert( p->pPrev==0 || p->pPrev->db==p->db );
52757   assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
52758
52759   /* Check for locking consistency */
52760   assert( !p->locked || p->wantToLock>0 );
52761   assert( p->sharable || p->wantToLock==0 );
52762
52763   /* We should already hold a lock on the database connection */
52764   assert( sqlite3_mutex_held(p->db->mutex) );
52765
52766   /* Unless the database is sharable and unlocked, then BtShared.db
52767   ** should already be set correctly. */
52768   assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
52769
52770   if( !p->sharable ) return;
52771   p->wantToLock++;
52772   if( p->locked ) return;
52773   btreeLockCarefully(p);
52774 }
52775
52776 /* This is a helper function for sqlite3BtreeLock(). By moving
52777 ** complex, but seldom used logic, out of sqlite3BtreeLock() and
52778 ** into this routine, we avoid unnecessary stack pointer changes
52779 ** and thus help the sqlite3BtreeLock() routine to run much faster
52780 ** in the common case.
52781 */
52782 static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
52783   Btree *pLater;
52784
52785   /* In most cases, we should be able to acquire the lock we
52786   ** want without having to go through the ascending lock
52787   ** procedure that follows.  Just be sure not to block.
52788   */
52789   if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
52790     p->pBt->db = p->db;
52791     p->locked = 1;
52792     return;
52793   }
52794
52795   /* To avoid deadlock, first release all locks with a larger
52796   ** BtShared address.  Then acquire our lock.  Then reacquire
52797   ** the other BtShared locks that we used to hold in ascending
52798   ** order.
52799   */
52800   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
52801     assert( pLater->sharable );
52802     assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
52803     assert( !pLater->locked || pLater->wantToLock>0 );
52804     if( pLater->locked ){
52805       unlockBtreeMutex(pLater);
52806     }
52807   }
52808   lockBtreeMutex(p);
52809   for(pLater=p->pNext; pLater; pLater=pLater->pNext){
52810     if( pLater->wantToLock ){
52811       lockBtreeMutex(pLater);
52812     }
52813   }
52814 }
52815
52816
52817 /*
52818 ** Exit the recursive mutex on a Btree.
52819 */
52820 SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
52821   assert( sqlite3_mutex_held(p->db->mutex) );
52822   if( p->sharable ){
52823     assert( p->wantToLock>0 );
52824     p->wantToLock--;
52825     if( p->wantToLock==0 ){
52826       unlockBtreeMutex(p);
52827     }
52828   }
52829 }
52830
52831 #ifndef NDEBUG
52832 /*
52833 ** Return true if the BtShared mutex is held on the btree, or if the
52834 ** B-Tree is not marked as sharable.
52835 **
52836 ** This routine is used only from within assert() statements.
52837 */
52838 SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
52839   assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
52840   assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
52841   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
52842   assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
52843
52844   return (p->sharable==0 || p->locked);
52845 }
52846 #endif
52847
52848
52849 #ifndef SQLITE_OMIT_INCRBLOB
52850 /*
52851 ** Enter and leave a mutex on a Btree given a cursor owned by that
52852 ** Btree.  These entry points are used by incremental I/O and can be
52853 ** omitted if that module is not used.
52854 */
52855 SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
52856   sqlite3BtreeEnter(pCur->pBtree);
52857 }
52858 SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
52859   sqlite3BtreeLeave(pCur->pBtree);
52860 }
52861 #endif /* SQLITE_OMIT_INCRBLOB */
52862
52863
52864 /*
52865 ** Enter the mutex on every Btree associated with a database
52866 ** connection.  This is needed (for example) prior to parsing
52867 ** a statement since we will be comparing table and column names
52868 ** against all schemas and we do not want those schemas being
52869 ** reset out from under us.
52870 **
52871 ** There is a corresponding leave-all procedures.
52872 **
52873 ** Enter the mutexes in accending order by BtShared pointer address
52874 ** to avoid the possibility of deadlock when two threads with
52875 ** two or more btrees in common both try to lock all their btrees
52876 ** at the same instant.
52877 */
52878 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
52879   int i;
52880   Btree *p;
52881   assert( sqlite3_mutex_held(db->mutex) );
52882   for(i=0; i<db->nDb; i++){
52883     p = db->aDb[i].pBt;
52884     if( p ) sqlite3BtreeEnter(p);
52885   }
52886 }
52887 SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
52888   int i;
52889   Btree *p;
52890   assert( sqlite3_mutex_held(db->mutex) );
52891   for(i=0; i<db->nDb; i++){
52892     p = db->aDb[i].pBt;
52893     if( p ) sqlite3BtreeLeave(p);
52894   }
52895 }
52896
52897 /*
52898 ** Return true if a particular Btree requires a lock.  Return FALSE if
52899 ** no lock is ever required since it is not sharable.
52900 */
52901 SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
52902   return p->sharable;
52903 }
52904
52905 #ifndef NDEBUG
52906 /*
52907 ** Return true if the current thread holds the database connection
52908 ** mutex and all required BtShared mutexes.
52909 **
52910 ** This routine is used inside assert() statements only.
52911 */
52912 SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
52913   int i;
52914   if( !sqlite3_mutex_held(db->mutex) ){
52915     return 0;
52916   }
52917   for(i=0; i<db->nDb; i++){
52918     Btree *p;
52919     p = db->aDb[i].pBt;
52920     if( p && p->sharable &&
52921          (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
52922       return 0;
52923     }
52924   }
52925   return 1;
52926 }
52927 #endif /* NDEBUG */
52928
52929 #ifndef NDEBUG
52930 /*
52931 ** Return true if the correct mutexes are held for accessing the
52932 ** db->aDb[iDb].pSchema structure.  The mutexes required for schema
52933 ** access are:
52934 **
52935 **   (1) The mutex on db
52936 **   (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
52937 **
52938 ** If pSchema is not NULL, then iDb is computed from pSchema and
52939 ** db using sqlite3SchemaToIndex().
52940 */
52941 SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
52942   Btree *p;
52943   assert( db!=0 );
52944   if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
52945   assert( iDb>=0 && iDb<db->nDb );
52946   if( !sqlite3_mutex_held(db->mutex) ) return 0;
52947   if( iDb==1 ) return 1;
52948   p = db->aDb[iDb].pBt;
52949   assert( p!=0 );
52950   return p->sharable==0 || p->locked==1;
52951 }
52952 #endif /* NDEBUG */
52953
52954 #else /* SQLITE_THREADSAFE>0 above.  SQLITE_THREADSAFE==0 below */
52955 /*
52956 ** The following are special cases for mutex enter routines for use
52957 ** in single threaded applications that use shared cache.  Except for
52958 ** these two routines, all mutex operations are no-ops in that case and
52959 ** are null #defines in btree.h.
52960 **
52961 ** If shared cache is disabled, then all btree mutex routines, including
52962 ** the ones below, are no-ops and are null #defines in btree.h.
52963 */
52964
52965 SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
52966   p->pBt->db = p->db;
52967 }
52968 SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
52969   int i;
52970   for(i=0; i<db->nDb; i++){
52971     Btree *p = db->aDb[i].pBt;
52972     if( p ){
52973       p->pBt->db = p->db;
52974     }
52975   }
52976 }
52977 #endif /* if SQLITE_THREADSAFE */
52978 #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
52979
52980 /************** End of btmutex.c *********************************************/
52981 /************** Begin file btree.c *******************************************/
52982 /*
52983 ** 2004 April 6
52984 **
52985 ** The author disclaims copyright to this source code.  In place of
52986 ** a legal notice, here is a blessing:
52987 **
52988 **    May you do good and not evil.
52989 **    May you find forgiveness for yourself and forgive others.
52990 **    May you share freely, never taking more than you give.
52991 **
52992 *************************************************************************
52993 ** This file implements an external (disk-based) database using BTrees.
52994 ** See the header comment on "btreeInt.h" for additional information.
52995 ** Including a description of file format and an overview of operation.
52996 */
52997
52998 /*
52999 ** The header string that appears at the beginning of every
53000 ** SQLite database.
53001 */
53002 static const char zMagicHeader[] = SQLITE_FILE_HEADER;
53003
53004 /*
53005 ** Set this global variable to 1 to enable tracing using the TRACE
53006 ** macro.
53007 */
53008 #if 0
53009 int sqlite3BtreeTrace=1;  /* True to enable tracing */
53010 # define TRACE(X)  if(sqlite3BtreeTrace){printf X;fflush(stdout);}
53011 #else
53012 # define TRACE(X)
53013 #endif
53014
53015 /*
53016 ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
53017 ** But if the value is zero, make it 65536.
53018 **
53019 ** This routine is used to extract the "offset to cell content area" value
53020 ** from the header of a btree page.  If the page size is 65536 and the page
53021 ** is empty, the offset should be 65536, but the 2-byte value stores zero.
53022 ** This routine makes the necessary adjustment to 65536.
53023 */
53024 #define get2byteNotZero(X)  (((((int)get2byte(X))-1)&0xffff)+1)
53025
53026 /*
53027 ** Values passed as the 5th argument to allocateBtreePage()
53028 */
53029 #define BTALLOC_ANY   0           /* Allocate any page */
53030 #define BTALLOC_EXACT 1           /* Allocate exact page if possible */
53031 #define BTALLOC_LE    2           /* Allocate any page <= the parameter */
53032
53033 /*
53034 ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not 
53035 ** defined, or 0 if it is. For example:
53036 **
53037 **   bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
53038 */
53039 #ifndef SQLITE_OMIT_AUTOVACUUM
53040 #define IfNotOmitAV(expr) (expr)
53041 #else
53042 #define IfNotOmitAV(expr) 0
53043 #endif
53044
53045 #ifndef SQLITE_OMIT_SHARED_CACHE
53046 /*
53047 ** A list of BtShared objects that are eligible for participation
53048 ** in shared cache.  This variable has file scope during normal builds,
53049 ** but the test harness needs to access it so we make it global for 
53050 ** test builds.
53051 **
53052 ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
53053 */
53054 #ifdef SQLITE_TEST
53055 SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
53056 #else
53057 static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
53058 #endif
53059 #endif /* SQLITE_OMIT_SHARED_CACHE */
53060
53061 #ifndef SQLITE_OMIT_SHARED_CACHE
53062 /*
53063 ** Enable or disable the shared pager and schema features.
53064 **
53065 ** This routine has no effect on existing database connections.
53066 ** The shared cache setting effects only future calls to
53067 ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
53068 */
53069 SQLITE_API int SQLITE_STDCALL sqlite3_enable_shared_cache(int enable){
53070   sqlite3GlobalConfig.sharedCacheEnabled = enable;
53071   return SQLITE_OK;
53072 }
53073 #endif
53074
53075
53076
53077 #ifdef SQLITE_OMIT_SHARED_CACHE
53078   /*
53079   ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
53080   ** and clearAllSharedCacheTableLocks()
53081   ** manipulate entries in the BtShared.pLock linked list used to store
53082   ** shared-cache table level locks. If the library is compiled with the
53083   ** shared-cache feature disabled, then there is only ever one user
53084   ** of each BtShared structure and so this locking is not necessary. 
53085   ** So define the lock related functions as no-ops.
53086   */
53087   #define querySharedCacheTableLock(a,b,c) SQLITE_OK
53088   #define setSharedCacheTableLock(a,b,c) SQLITE_OK
53089   #define clearAllSharedCacheTableLocks(a)
53090   #define downgradeAllSharedCacheTableLocks(a)
53091   #define hasSharedCacheTableLock(a,b,c,d) 1
53092   #define hasReadConflicts(a, b) 0
53093 #endif
53094
53095 #ifndef SQLITE_OMIT_SHARED_CACHE
53096
53097 #ifdef SQLITE_DEBUG
53098 /*
53099 **** This function is only used as part of an assert() statement. ***
53100 **
53101 ** Check to see if pBtree holds the required locks to read or write to the 
53102 ** table with root page iRoot.   Return 1 if it does and 0 if not.
53103 **
53104 ** For example, when writing to a table with root-page iRoot via 
53105 ** Btree connection pBtree:
53106 **
53107 **    assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
53108 **
53109 ** When writing to an index that resides in a sharable database, the 
53110 ** caller should have first obtained a lock specifying the root page of
53111 ** the corresponding table. This makes things a bit more complicated,
53112 ** as this module treats each table as a separate structure. To determine
53113 ** the table corresponding to the index being written, this
53114 ** function has to search through the database schema.
53115 **
53116 ** Instead of a lock on the table/index rooted at page iRoot, the caller may
53117 ** hold a write-lock on the schema table (root page 1). This is also
53118 ** acceptable.
53119 */
53120 static int hasSharedCacheTableLock(
53121   Btree *pBtree,         /* Handle that must hold lock */
53122   Pgno iRoot,            /* Root page of b-tree */
53123   int isIndex,           /* True if iRoot is the root of an index b-tree */
53124   int eLockType          /* Required lock type (READ_LOCK or WRITE_LOCK) */
53125 ){
53126   Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
53127   Pgno iTab = 0;
53128   BtLock *pLock;
53129
53130   /* If this database is not shareable, or if the client is reading
53131   ** and has the read-uncommitted flag set, then no lock is required. 
53132   ** Return true immediately.
53133   */
53134   if( (pBtree->sharable==0)
53135    || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
53136   ){
53137     return 1;
53138   }
53139
53140   /* If the client is reading  or writing an index and the schema is
53141   ** not loaded, then it is too difficult to actually check to see if
53142   ** the correct locks are held.  So do not bother - just return true.
53143   ** This case does not come up very often anyhow.
53144   */
53145   if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
53146     return 1;
53147   }
53148
53149   /* Figure out the root-page that the lock should be held on. For table
53150   ** b-trees, this is just the root page of the b-tree being read or
53151   ** written. For index b-trees, it is the root page of the associated
53152   ** table.  */
53153   if( isIndex ){
53154     HashElem *p;
53155     for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
53156       Index *pIdx = (Index *)sqliteHashData(p);
53157       if( pIdx->tnum==(int)iRoot ){
53158         if( iTab ){
53159           /* Two or more indexes share the same root page.  There must
53160           ** be imposter tables.  So just return true.  The assert is not
53161           ** useful in that case. */
53162           return 1;
53163         }
53164         iTab = pIdx->pTable->tnum;
53165       }
53166     }
53167   }else{
53168     iTab = iRoot;
53169   }
53170
53171   /* Search for the required lock. Either a write-lock on root-page iTab, a 
53172   ** write-lock on the schema table, or (if the client is reading) a
53173   ** read-lock on iTab will suffice. Return 1 if any of these are found.  */
53174   for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
53175     if( pLock->pBtree==pBtree 
53176      && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
53177      && pLock->eLock>=eLockType 
53178     ){
53179       return 1;
53180     }
53181   }
53182
53183   /* Failed to find the required lock. */
53184   return 0;
53185 }
53186 #endif /* SQLITE_DEBUG */
53187
53188 #ifdef SQLITE_DEBUG
53189 /*
53190 **** This function may be used as part of assert() statements only. ****
53191 **
53192 ** Return true if it would be illegal for pBtree to write into the
53193 ** table or index rooted at iRoot because other shared connections are
53194 ** simultaneously reading that same table or index.
53195 **
53196 ** It is illegal for pBtree to write if some other Btree object that
53197 ** shares the same BtShared object is currently reading or writing
53198 ** the iRoot table.  Except, if the other Btree object has the
53199 ** read-uncommitted flag set, then it is OK for the other object to
53200 ** have a read cursor.
53201 **
53202 ** For example, before writing to any part of the table or index
53203 ** rooted at page iRoot, one should call:
53204 **
53205 **    assert( !hasReadConflicts(pBtree, iRoot) );
53206 */
53207 static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
53208   BtCursor *p;
53209   for(p=pBtree->pBt->pCursor; p; p=p->pNext){
53210     if( p->pgnoRoot==iRoot 
53211      && p->pBtree!=pBtree
53212      && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
53213     ){
53214       return 1;
53215     }
53216   }
53217   return 0;
53218 }
53219 #endif    /* #ifdef SQLITE_DEBUG */
53220
53221 /*
53222 ** Query to see if Btree handle p may obtain a lock of type eLock 
53223 ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
53224 ** SQLITE_OK if the lock may be obtained (by calling
53225 ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
53226 */
53227 static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
53228   BtShared *pBt = p->pBt;
53229   BtLock *pIter;
53230
53231   assert( sqlite3BtreeHoldsMutex(p) );
53232   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
53233   assert( p->db!=0 );
53234   assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
53235   
53236   /* If requesting a write-lock, then the Btree must have an open write
53237   ** transaction on this file. And, obviously, for this to be so there 
53238   ** must be an open write transaction on the file itself.
53239   */
53240   assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
53241   assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
53242   
53243   /* This routine is a no-op if the shared-cache is not enabled */
53244   if( !p->sharable ){
53245     return SQLITE_OK;
53246   }
53247
53248   /* If some other connection is holding an exclusive lock, the
53249   ** requested lock may not be obtained.
53250   */
53251   if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
53252     sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
53253     return SQLITE_LOCKED_SHAREDCACHE;
53254   }
53255
53256   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
53257     /* The condition (pIter->eLock!=eLock) in the following if(...) 
53258     ** statement is a simplification of:
53259     **
53260     **   (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
53261     **
53262     ** since we know that if eLock==WRITE_LOCK, then no other connection
53263     ** may hold a WRITE_LOCK on any table in this file (since there can
53264     ** only be a single writer).
53265     */
53266     assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
53267     assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
53268     if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
53269       sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
53270       if( eLock==WRITE_LOCK ){
53271         assert( p==pBt->pWriter );
53272         pBt->btsFlags |= BTS_PENDING;
53273       }
53274       return SQLITE_LOCKED_SHAREDCACHE;
53275     }
53276   }
53277   return SQLITE_OK;
53278 }
53279 #endif /* !SQLITE_OMIT_SHARED_CACHE */
53280
53281 #ifndef SQLITE_OMIT_SHARED_CACHE
53282 /*
53283 ** Add a lock on the table with root-page iTable to the shared-btree used
53284 ** by Btree handle p. Parameter eLock must be either READ_LOCK or 
53285 ** WRITE_LOCK.
53286 **
53287 ** This function assumes the following:
53288 **
53289 **   (a) The specified Btree object p is connected to a sharable
53290 **       database (one with the BtShared.sharable flag set), and
53291 **
53292 **   (b) No other Btree objects hold a lock that conflicts
53293 **       with the requested lock (i.e. querySharedCacheTableLock() has
53294 **       already been called and returned SQLITE_OK).
53295 **
53296 ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM 
53297 ** is returned if a malloc attempt fails.
53298 */
53299 static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
53300   BtShared *pBt = p->pBt;
53301   BtLock *pLock = 0;
53302   BtLock *pIter;
53303
53304   assert( sqlite3BtreeHoldsMutex(p) );
53305   assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
53306   assert( p->db!=0 );
53307
53308   /* A connection with the read-uncommitted flag set will never try to
53309   ** obtain a read-lock using this function. The only read-lock obtained
53310   ** by a connection in read-uncommitted mode is on the sqlite_master 
53311   ** table, and that lock is obtained in BtreeBeginTrans().  */
53312   assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
53313
53314   /* This function should only be called on a sharable b-tree after it 
53315   ** has been determined that no other b-tree holds a conflicting lock.  */
53316   assert( p->sharable );
53317   assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
53318
53319   /* First search the list for an existing lock on this table. */
53320   for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
53321     if( pIter->iTable==iTable && pIter->pBtree==p ){
53322       pLock = pIter;
53323       break;
53324     }
53325   }
53326
53327   /* If the above search did not find a BtLock struct associating Btree p
53328   ** with table iTable, allocate one and link it into the list.
53329   */
53330   if( !pLock ){
53331     pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
53332     if( !pLock ){
53333       return SQLITE_NOMEM;
53334     }
53335     pLock->iTable = iTable;
53336     pLock->pBtree = p;
53337     pLock->pNext = pBt->pLock;
53338     pBt->pLock = pLock;
53339   }
53340
53341   /* Set the BtLock.eLock variable to the maximum of the current lock
53342   ** and the requested lock. This means if a write-lock was already held
53343   ** and a read-lock requested, we don't incorrectly downgrade the lock.
53344   */
53345   assert( WRITE_LOCK>READ_LOCK );
53346   if( eLock>pLock->eLock ){
53347     pLock->eLock = eLock;
53348   }
53349
53350   return SQLITE_OK;
53351 }
53352 #endif /* !SQLITE_OMIT_SHARED_CACHE */
53353
53354 #ifndef SQLITE_OMIT_SHARED_CACHE
53355 /*
53356 ** Release all the table locks (locks obtained via calls to
53357 ** the setSharedCacheTableLock() procedure) held by Btree object p.
53358 **
53359 ** This function assumes that Btree p has an open read or write 
53360 ** transaction. If it does not, then the BTS_PENDING flag
53361 ** may be incorrectly cleared.
53362 */
53363 static void clearAllSharedCacheTableLocks(Btree *p){
53364   BtShared *pBt = p->pBt;
53365   BtLock **ppIter = &pBt->pLock;
53366
53367   assert( sqlite3BtreeHoldsMutex(p) );
53368   assert( p->sharable || 0==*ppIter );
53369   assert( p->inTrans>0 );
53370
53371   while( *ppIter ){
53372     BtLock *pLock = *ppIter;
53373     assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
53374     assert( pLock->pBtree->inTrans>=pLock->eLock );
53375     if( pLock->pBtree==p ){
53376       *ppIter = pLock->pNext;
53377       assert( pLock->iTable!=1 || pLock==&p->lock );
53378       if( pLock->iTable!=1 ){
53379         sqlite3_free(pLock);
53380       }
53381     }else{
53382       ppIter = &pLock->pNext;
53383     }
53384   }
53385
53386   assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
53387   if( pBt->pWriter==p ){
53388     pBt->pWriter = 0;
53389     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
53390   }else if( pBt->nTransaction==2 ){
53391     /* This function is called when Btree p is concluding its 
53392     ** transaction. If there currently exists a writer, and p is not
53393     ** that writer, then the number of locks held by connections other
53394     ** than the writer must be about to drop to zero. In this case
53395     ** set the BTS_PENDING flag to 0.
53396     **
53397     ** If there is not currently a writer, then BTS_PENDING must
53398     ** be zero already. So this next line is harmless in that case.
53399     */
53400     pBt->btsFlags &= ~BTS_PENDING;
53401   }
53402 }
53403
53404 /*
53405 ** This function changes all write-locks held by Btree p into read-locks.
53406 */
53407 static void downgradeAllSharedCacheTableLocks(Btree *p){
53408   BtShared *pBt = p->pBt;
53409   if( pBt->pWriter==p ){
53410     BtLock *pLock;
53411     pBt->pWriter = 0;
53412     pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
53413     for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
53414       assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
53415       pLock->eLock = READ_LOCK;
53416     }
53417   }
53418 }
53419
53420 #endif /* SQLITE_OMIT_SHARED_CACHE */
53421
53422 static void releasePage(MemPage *pPage);  /* Forward reference */
53423
53424 /*
53425 ***** This routine is used inside of assert() only ****
53426 **
53427 ** Verify that the cursor holds the mutex on its BtShared
53428 */
53429 #ifdef SQLITE_DEBUG
53430 static int cursorHoldsMutex(BtCursor *p){
53431   return sqlite3_mutex_held(p->pBt->mutex);
53432 }
53433 #endif
53434
53435 /*
53436 ** Invalidate the overflow cache of the cursor passed as the first argument.
53437 ** on the shared btree structure pBt.
53438 */
53439 #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
53440
53441 /*
53442 ** Invalidate the overflow page-list cache for all cursors opened
53443 ** on the shared btree structure pBt.
53444 */
53445 static void invalidateAllOverflowCache(BtShared *pBt){
53446   BtCursor *p;
53447   assert( sqlite3_mutex_held(pBt->mutex) );
53448   for(p=pBt->pCursor; p; p=p->pNext){
53449     invalidateOverflowCache(p);
53450   }
53451 }
53452
53453 #ifndef SQLITE_OMIT_INCRBLOB
53454 /*
53455 ** This function is called before modifying the contents of a table
53456 ** to invalidate any incrblob cursors that are open on the
53457 ** row or one of the rows being modified.
53458 **
53459 ** If argument isClearTable is true, then the entire contents of the
53460 ** table is about to be deleted. In this case invalidate all incrblob
53461 ** cursors open on any row within the table with root-page pgnoRoot.
53462 **
53463 ** Otherwise, if argument isClearTable is false, then the row with
53464 ** rowid iRow is being replaced or deleted. In this case invalidate
53465 ** only those incrblob cursors open on that specific row.
53466 */
53467 static void invalidateIncrblobCursors(
53468   Btree *pBtree,          /* The database file to check */
53469   i64 iRow,               /* The rowid that might be changing */
53470   int isClearTable        /* True if all rows are being deleted */
53471 ){
53472   BtCursor *p;
53473   BtShared *pBt = pBtree->pBt;
53474   assert( sqlite3BtreeHoldsMutex(pBtree) );
53475   for(p=pBt->pCursor; p; p=p->pNext){
53476     if( (p->curFlags & BTCF_Incrblob)!=0
53477      && (isClearTable || p->info.nKey==iRow)
53478     ){
53479       p->eState = CURSOR_INVALID;
53480     }
53481   }
53482 }
53483
53484 #else
53485   /* Stub function when INCRBLOB is omitted */
53486   #define invalidateIncrblobCursors(x,y,z)
53487 #endif /* SQLITE_OMIT_INCRBLOB */
53488
53489 /*
53490 ** Set bit pgno of the BtShared.pHasContent bitvec. This is called 
53491 ** when a page that previously contained data becomes a free-list leaf 
53492 ** page.
53493 **
53494 ** The BtShared.pHasContent bitvec exists to work around an obscure
53495 ** bug caused by the interaction of two useful IO optimizations surrounding
53496 ** free-list leaf pages:
53497 **
53498 **   1) When all data is deleted from a page and the page becomes
53499 **      a free-list leaf page, the page is not written to the database
53500 **      (as free-list leaf pages contain no meaningful data). Sometimes
53501 **      such a page is not even journalled (as it will not be modified,
53502 **      why bother journalling it?).
53503 **
53504 **   2) When a free-list leaf page is reused, its content is not read
53505 **      from the database or written to the journal file (why should it
53506 **      be, if it is not at all meaningful?).
53507 **
53508 ** By themselves, these optimizations work fine and provide a handy
53509 ** performance boost to bulk delete or insert operations. However, if
53510 ** a page is moved to the free-list and then reused within the same
53511 ** transaction, a problem comes up. If the page is not journalled when
53512 ** it is moved to the free-list and it is also not journalled when it
53513 ** is extracted from the free-list and reused, then the original data
53514 ** may be lost. In the event of a rollback, it may not be possible
53515 ** to restore the database to its original configuration.
53516 **
53517 ** The solution is the BtShared.pHasContent bitvec. Whenever a page is 
53518 ** moved to become a free-list leaf page, the corresponding bit is
53519 ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
53520 ** optimization 2 above is omitted if the corresponding bit is already
53521 ** set in BtShared.pHasContent. The contents of the bitvec are cleared
53522 ** at the end of every transaction.
53523 */
53524 static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
53525   int rc = SQLITE_OK;
53526   if( !pBt->pHasContent ){
53527     assert( pgno<=pBt->nPage );
53528     pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
53529     if( !pBt->pHasContent ){
53530       rc = SQLITE_NOMEM;
53531     }
53532   }
53533   if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
53534     rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
53535   }
53536   return rc;
53537 }
53538
53539 /*
53540 ** Query the BtShared.pHasContent vector.
53541 **
53542 ** This function is called when a free-list leaf page is removed from the
53543 ** free-list for reuse. It returns false if it is safe to retrieve the
53544 ** page from the pager layer with the 'no-content' flag set. True otherwise.
53545 */
53546 static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
53547   Bitvec *p = pBt->pHasContent;
53548   return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
53549 }
53550
53551 /*
53552 ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
53553 ** invoked at the conclusion of each write-transaction.
53554 */
53555 static void btreeClearHasContent(BtShared *pBt){
53556   sqlite3BitvecDestroy(pBt->pHasContent);
53557   pBt->pHasContent = 0;
53558 }
53559
53560 /*
53561 ** Release all of the apPage[] pages for a cursor.
53562 */
53563 static void btreeReleaseAllCursorPages(BtCursor *pCur){
53564   int i;
53565   for(i=0; i<=pCur->iPage; i++){
53566     releasePage(pCur->apPage[i]);
53567     pCur->apPage[i] = 0;
53568   }
53569   pCur->iPage = -1;
53570 }
53571
53572
53573 /*
53574 ** Save the current cursor position in the variables BtCursor.nKey 
53575 ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
53576 **
53577 ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
53578 ** prior to calling this routine.  
53579 */
53580 static int saveCursorPosition(BtCursor *pCur){
53581   int rc;
53582
53583   assert( CURSOR_VALID==pCur->eState || CURSOR_SKIPNEXT==pCur->eState );
53584   assert( 0==pCur->pKey );
53585   assert( cursorHoldsMutex(pCur) );
53586
53587   if( pCur->eState==CURSOR_SKIPNEXT ){
53588     pCur->eState = CURSOR_VALID;
53589   }else{
53590     pCur->skipNext = 0;
53591   }
53592   rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
53593   assert( rc==SQLITE_OK );  /* KeySize() cannot fail */
53594
53595   /* If this is an intKey table, then the above call to BtreeKeySize()
53596   ** stores the integer key in pCur->nKey. In this case this value is
53597   ** all that is required. Otherwise, if pCur is not open on an intKey
53598   ** table, then malloc space for and store the pCur->nKey bytes of key 
53599   ** data.
53600   */
53601   if( 0==pCur->apPage[0]->intKey ){
53602     void *pKey = sqlite3Malloc( pCur->nKey );
53603     if( pKey ){
53604       rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
53605       if( rc==SQLITE_OK ){
53606         pCur->pKey = pKey;
53607       }else{
53608         sqlite3_free(pKey);
53609       }
53610     }else{
53611       rc = SQLITE_NOMEM;
53612     }
53613   }
53614   assert( !pCur->apPage[0]->intKey || !pCur->pKey );
53615
53616   if( rc==SQLITE_OK ){
53617     btreeReleaseAllCursorPages(pCur);
53618     pCur->eState = CURSOR_REQUIRESEEK;
53619   }
53620
53621   invalidateOverflowCache(pCur);
53622   return rc;
53623 }
53624
53625 /* Forward reference */
53626 static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
53627
53628 /*
53629 ** Save the positions of all cursors (except pExcept) that are open on
53630 ** the table with root-page iRoot.  "Saving the cursor position" means that
53631 ** the location in the btree is remembered in such a way that it can be
53632 ** moved back to the same spot after the btree has been modified.  This
53633 ** routine is called just before cursor pExcept is used to modify the
53634 ** table, for example in BtreeDelete() or BtreeInsert().
53635 **
53636 ** Implementation note:  This routine merely checks to see if any cursors
53637 ** need to be saved.  It calls out to saveCursorsOnList() in the (unusual)
53638 ** event that cursors are in need to being saved.
53639 */
53640 static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
53641   BtCursor *p;
53642   assert( sqlite3_mutex_held(pBt->mutex) );
53643   assert( pExcept==0 || pExcept->pBt==pBt );
53644   for(p=pBt->pCursor; p; p=p->pNext){
53645     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
53646   }
53647   return p ? saveCursorsOnList(p, iRoot, pExcept) : SQLITE_OK;
53648 }
53649
53650 /* This helper routine to saveAllCursors does the actual work of saving
53651 ** the cursors if and when a cursor is found that actually requires saving.
53652 ** The common case is that no cursors need to be saved, so this routine is
53653 ** broken out from its caller to avoid unnecessary stack pointer movement.
53654 */
53655 static int SQLITE_NOINLINE saveCursorsOnList(
53656   BtCursor *p,         /* The first cursor that needs saving */
53657   Pgno iRoot,          /* Only save cursor with this iRoot. Save all if zero */
53658   BtCursor *pExcept    /* Do not save this cursor */
53659 ){
53660   do{
53661     if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
53662       if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
53663         int rc = saveCursorPosition(p);
53664         if( SQLITE_OK!=rc ){
53665           return rc;
53666         }
53667       }else{
53668         testcase( p->iPage>0 );
53669         btreeReleaseAllCursorPages(p);
53670       }
53671     }
53672     p = p->pNext;
53673   }while( p );
53674   return SQLITE_OK;
53675 }
53676
53677 /*
53678 ** Clear the current cursor position.
53679 */
53680 SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
53681   assert( cursorHoldsMutex(pCur) );
53682   sqlite3_free(pCur->pKey);
53683   pCur->pKey = 0;
53684   pCur->eState = CURSOR_INVALID;
53685 }
53686
53687 /*
53688 ** In this version of BtreeMoveto, pKey is a packed index record
53689 ** such as is generated by the OP_MakeRecord opcode.  Unpack the
53690 ** record and then call BtreeMovetoUnpacked() to do the work.
53691 */
53692 static int btreeMoveto(
53693   BtCursor *pCur,     /* Cursor open on the btree to be searched */
53694   const void *pKey,   /* Packed key if the btree is an index */
53695   i64 nKey,           /* Integer key for tables.  Size of pKey for indices */
53696   int bias,           /* Bias search to the high end */
53697   int *pRes           /* Write search results here */
53698 ){
53699   int rc;                    /* Status code */
53700   UnpackedRecord *pIdxKey;   /* Unpacked index key */
53701   char aSpace[200];          /* Temp space for pIdxKey - to avoid a malloc */
53702   char *pFree = 0;
53703
53704   if( pKey ){
53705     assert( nKey==(i64)(int)nKey );
53706     pIdxKey = sqlite3VdbeAllocUnpackedRecord(
53707         pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
53708     );
53709     if( pIdxKey==0 ) return SQLITE_NOMEM;
53710     sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
53711     if( pIdxKey->nField==0 ){
53712       sqlite3DbFree(pCur->pKeyInfo->db, pFree);
53713       return SQLITE_CORRUPT_BKPT;
53714     }
53715   }else{
53716     pIdxKey = 0;
53717   }
53718   rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
53719   if( pFree ){
53720     sqlite3DbFree(pCur->pKeyInfo->db, pFree);
53721   }
53722   return rc;
53723 }
53724
53725 /*
53726 ** Restore the cursor to the position it was in (or as close to as possible)
53727 ** when saveCursorPosition() was called. Note that this call deletes the 
53728 ** saved position info stored by saveCursorPosition(), so there can be
53729 ** at most one effective restoreCursorPosition() call after each 
53730 ** saveCursorPosition().
53731 */
53732 static int btreeRestoreCursorPosition(BtCursor *pCur){
53733   int rc;
53734   int skipNext;
53735   assert( cursorHoldsMutex(pCur) );
53736   assert( pCur->eState>=CURSOR_REQUIRESEEK );
53737   if( pCur->eState==CURSOR_FAULT ){
53738     return pCur->skipNext;
53739   }
53740   pCur->eState = CURSOR_INVALID;
53741   rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &skipNext);
53742   if( rc==SQLITE_OK ){
53743     sqlite3_free(pCur->pKey);
53744     pCur->pKey = 0;
53745     assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
53746     pCur->skipNext |= skipNext;
53747     if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
53748       pCur->eState = CURSOR_SKIPNEXT;
53749     }
53750   }
53751   return rc;
53752 }
53753
53754 #define restoreCursorPosition(p) \
53755   (p->eState>=CURSOR_REQUIRESEEK ? \
53756          btreeRestoreCursorPosition(p) : \
53757          SQLITE_OK)
53758
53759 /*
53760 ** Determine whether or not a cursor has moved from the position where
53761 ** it was last placed, or has been invalidated for any other reason.
53762 ** Cursors can move when the row they are pointing at is deleted out
53763 ** from under them, for example.  Cursor might also move if a btree
53764 ** is rebalanced.
53765 **
53766 ** Calling this routine with a NULL cursor pointer returns false.
53767 **
53768 ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
53769 ** back to where it ought to be if this routine returns true.
53770 */
53771 SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
53772   return pCur->eState!=CURSOR_VALID;
53773 }
53774
53775 /*
53776 ** This routine restores a cursor back to its original position after it
53777 ** has been moved by some outside activity (such as a btree rebalance or
53778 ** a row having been deleted out from under the cursor).  
53779 **
53780 ** On success, the *pDifferentRow parameter is false if the cursor is left
53781 ** pointing at exactly the same row.  *pDifferntRow is the row the cursor
53782 ** was pointing to has been deleted, forcing the cursor to point to some
53783 ** nearby row.
53784 **
53785 ** This routine should only be called for a cursor that just returned
53786 ** TRUE from sqlite3BtreeCursorHasMoved().
53787 */
53788 SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
53789   int rc;
53790
53791   assert( pCur!=0 );
53792   assert( pCur->eState!=CURSOR_VALID );
53793   rc = restoreCursorPosition(pCur);
53794   if( rc ){
53795     *pDifferentRow = 1;
53796     return rc;
53797   }
53798   if( pCur->eState!=CURSOR_VALID ){
53799     *pDifferentRow = 1;
53800   }else{
53801     assert( pCur->skipNext==0 );
53802     *pDifferentRow = 0;
53803   }
53804   return SQLITE_OK;
53805 }
53806
53807 #ifndef SQLITE_OMIT_AUTOVACUUM
53808 /*
53809 ** Given a page number of a regular database page, return the page
53810 ** number for the pointer-map page that contains the entry for the
53811 ** input page number.
53812 **
53813 ** Return 0 (not a valid page) for pgno==1 since there is
53814 ** no pointer map associated with page 1.  The integrity_check logic
53815 ** requires that ptrmapPageno(*,1)!=1.
53816 */
53817 static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
53818   int nPagesPerMapPage;
53819   Pgno iPtrMap, ret;
53820   assert( sqlite3_mutex_held(pBt->mutex) );
53821   if( pgno<2 ) return 0;
53822   nPagesPerMapPage = (pBt->usableSize/5)+1;
53823   iPtrMap = (pgno-2)/nPagesPerMapPage;
53824   ret = (iPtrMap*nPagesPerMapPage) + 2; 
53825   if( ret==PENDING_BYTE_PAGE(pBt) ){
53826     ret++;
53827   }
53828   return ret;
53829 }
53830
53831 /*
53832 ** Write an entry into the pointer map.
53833 **
53834 ** This routine updates the pointer map entry for page number 'key'
53835 ** so that it maps to type 'eType' and parent page number 'pgno'.
53836 **
53837 ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
53838 ** a no-op.  If an error occurs, the appropriate error code is written
53839 ** into *pRC.
53840 */
53841 static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
53842   DbPage *pDbPage;  /* The pointer map page */
53843   u8 *pPtrmap;      /* The pointer map data */
53844   Pgno iPtrmap;     /* The pointer map page number */
53845   int offset;       /* Offset in pointer map page */
53846   int rc;           /* Return code from subfunctions */
53847
53848   if( *pRC ) return;
53849
53850   assert( sqlite3_mutex_held(pBt->mutex) );
53851   /* The master-journal page number must never be used as a pointer map page */
53852   assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
53853
53854   assert( pBt->autoVacuum );
53855   if( key==0 ){
53856     *pRC = SQLITE_CORRUPT_BKPT;
53857     return;
53858   }
53859   iPtrmap = PTRMAP_PAGENO(pBt, key);
53860   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
53861   if( rc!=SQLITE_OK ){
53862     *pRC = rc;
53863     return;
53864   }
53865   offset = PTRMAP_PTROFFSET(iPtrmap, key);
53866   if( offset<0 ){
53867     *pRC = SQLITE_CORRUPT_BKPT;
53868     goto ptrmap_exit;
53869   }
53870   assert( offset <= (int)pBt->usableSize-5 );
53871   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
53872
53873   if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
53874     TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
53875     *pRC= rc = sqlite3PagerWrite(pDbPage);
53876     if( rc==SQLITE_OK ){
53877       pPtrmap[offset] = eType;
53878       put4byte(&pPtrmap[offset+1], parent);
53879     }
53880   }
53881
53882 ptrmap_exit:
53883   sqlite3PagerUnref(pDbPage);
53884 }
53885
53886 /*
53887 ** Read an entry from the pointer map.
53888 **
53889 ** This routine retrieves the pointer map entry for page 'key', writing
53890 ** the type and parent page number to *pEType and *pPgno respectively.
53891 ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
53892 */
53893 static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
53894   DbPage *pDbPage;   /* The pointer map page */
53895   int iPtrmap;       /* Pointer map page index */
53896   u8 *pPtrmap;       /* Pointer map page data */
53897   int offset;        /* Offset of entry in pointer map */
53898   int rc;
53899
53900   assert( sqlite3_mutex_held(pBt->mutex) );
53901
53902   iPtrmap = PTRMAP_PAGENO(pBt, key);
53903   rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
53904   if( rc!=0 ){
53905     return rc;
53906   }
53907   pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
53908
53909   offset = PTRMAP_PTROFFSET(iPtrmap, key);
53910   if( offset<0 ){
53911     sqlite3PagerUnref(pDbPage);
53912     return SQLITE_CORRUPT_BKPT;
53913   }
53914   assert( offset <= (int)pBt->usableSize-5 );
53915   assert( pEType!=0 );
53916   *pEType = pPtrmap[offset];
53917   if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
53918
53919   sqlite3PagerUnref(pDbPage);
53920   if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
53921   return SQLITE_OK;
53922 }
53923
53924 #else /* if defined SQLITE_OMIT_AUTOVACUUM */
53925   #define ptrmapPut(w,x,y,z,rc)
53926   #define ptrmapGet(w,x,y,z) SQLITE_OK
53927   #define ptrmapPutOvflPtr(x, y, rc)
53928 #endif
53929
53930 /*
53931 ** Given a btree page and a cell index (0 means the first cell on
53932 ** the page, 1 means the second cell, and so forth) return a pointer
53933 ** to the cell content.
53934 **
53935 ** This routine works only for pages that do not contain overflow cells.
53936 */
53937 #define findCell(P,I) \
53938   ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
53939 #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
53940
53941
53942 /*
53943 ** This a more complex version of findCell() that works for
53944 ** pages that do contain overflow cells.
53945 */
53946 static u8 *findOverflowCell(MemPage *pPage, int iCell){
53947   int i;
53948   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53949   for(i=pPage->nOverflow-1; i>=0; i--){
53950     int k;
53951     k = pPage->aiOvfl[i];
53952     if( k<=iCell ){
53953       if( k==iCell ){
53954         return pPage->apOvfl[i];
53955       }
53956       iCell--;
53957     }
53958   }
53959   return findCell(pPage, iCell);
53960 }
53961
53962 /*
53963 ** Parse a cell content block and fill in the CellInfo structure.  There
53964 ** are two versions of this function.  btreeParseCell() takes a 
53965 ** cell index as the second argument and btreeParseCellPtr() 
53966 ** takes a pointer to the body of the cell as its second argument.
53967 */
53968 static void btreeParseCellPtr(
53969   MemPage *pPage,         /* Page containing the cell */
53970   u8 *pCell,              /* Pointer to the cell text. */
53971   CellInfo *pInfo         /* Fill in this structure */
53972 ){
53973   u8 *pIter;              /* For scanning through pCell */
53974   u32 nPayload;           /* Number of bytes of cell payload */
53975
53976   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
53977   assert( pPage->leaf==0 || pPage->leaf==1 );
53978   if( pPage->intKeyLeaf ){
53979     assert( pPage->childPtrSize==0 );
53980     pIter = pCell + getVarint32(pCell, nPayload);
53981     pIter += getVarint(pIter, (u64*)&pInfo->nKey);
53982   }else if( pPage->noPayload ){
53983     assert( pPage->childPtrSize==4 );
53984     pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
53985     pInfo->nPayload = 0;
53986     pInfo->nLocal = 0;
53987     pInfo->iOverflow = 0;
53988     pInfo->pPayload = 0;
53989     return;
53990   }else{
53991     pIter = pCell + pPage->childPtrSize;
53992     pIter += getVarint32(pIter, nPayload);
53993     pInfo->nKey = nPayload;
53994   }
53995   pInfo->nPayload = nPayload;
53996   pInfo->pPayload = pIter;
53997   testcase( nPayload==pPage->maxLocal );
53998   testcase( nPayload==pPage->maxLocal+1 );
53999   if( nPayload<=pPage->maxLocal ){
54000     /* This is the (easy) common case where the entire payload fits
54001     ** on the local page.  No overflow is required.
54002     */
54003     pInfo->nSize = nPayload + (u16)(pIter - pCell);
54004     if( pInfo->nSize<4 ) pInfo->nSize = 4;
54005     pInfo->nLocal = (u16)nPayload;
54006     pInfo->iOverflow = 0;
54007   }else{
54008     /* If the payload will not fit completely on the local page, we have
54009     ** to decide how much to store locally and how much to spill onto
54010     ** overflow pages.  The strategy is to minimize the amount of unused
54011     ** space on overflow pages while keeping the amount of local storage
54012     ** in between minLocal and maxLocal.
54013     **
54014     ** Warning:  changing the way overflow payload is distributed in any
54015     ** way will result in an incompatible file format.
54016     */
54017     int minLocal;  /* Minimum amount of payload held locally */
54018     int maxLocal;  /* Maximum amount of payload held locally */
54019     int surplus;   /* Overflow payload available for local storage */
54020
54021     minLocal = pPage->minLocal;
54022     maxLocal = pPage->maxLocal;
54023     surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
54024     testcase( surplus==maxLocal );
54025     testcase( surplus==maxLocal+1 );
54026     if( surplus <= maxLocal ){
54027       pInfo->nLocal = (u16)surplus;
54028     }else{
54029       pInfo->nLocal = (u16)minLocal;
54030     }
54031     pInfo->iOverflow = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell);
54032     pInfo->nSize = pInfo->iOverflow + 4;
54033   }
54034 }
54035 static void btreeParseCell(
54036   MemPage *pPage,         /* Page containing the cell */
54037   int iCell,              /* The cell index.  First cell is 0 */
54038   CellInfo *pInfo         /* Fill in this structure */
54039 ){
54040   btreeParseCellPtr(pPage, findCell(pPage, iCell), pInfo);
54041 }
54042
54043 /*
54044 ** Compute the total number of bytes that a Cell needs in the cell
54045 ** data area of the btree-page.  The return number includes the cell
54046 ** data header and the local payload, but not any overflow page or
54047 ** the space used by the cell pointer.
54048 */
54049 static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
54050   u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
54051   u8 *pEnd;                                /* End mark for a varint */
54052   u32 nSize;                               /* Size value to return */
54053
54054 #ifdef SQLITE_DEBUG
54055   /* The value returned by this function should always be the same as
54056   ** the (CellInfo.nSize) value found by doing a full parse of the
54057   ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
54058   ** this function verifies that this invariant is not violated. */
54059   CellInfo debuginfo;
54060   btreeParseCellPtr(pPage, pCell, &debuginfo);
54061 #endif
54062
54063   if( pPage->noPayload ){
54064     pEnd = &pIter[9];
54065     while( (*pIter++)&0x80 && pIter<pEnd );
54066     assert( pPage->childPtrSize==4 );
54067     return (u16)(pIter - pCell);
54068   }
54069   nSize = *pIter;
54070   if( nSize>=0x80 ){
54071     pEnd = &pIter[9];
54072     nSize &= 0x7f;
54073     do{
54074       nSize = (nSize<<7) | (*++pIter & 0x7f);
54075     }while( *(pIter)>=0x80 && pIter<pEnd );
54076   }
54077   pIter++;
54078   if( pPage->intKey ){
54079     /* pIter now points at the 64-bit integer key value, a variable length 
54080     ** integer. The following block moves pIter to point at the first byte
54081     ** past the end of the key value. */
54082     pEnd = &pIter[9];
54083     while( (*pIter++)&0x80 && pIter<pEnd );
54084   }
54085   testcase( nSize==pPage->maxLocal );
54086   testcase( nSize==pPage->maxLocal+1 );
54087   if( nSize<=pPage->maxLocal ){
54088     nSize += (u32)(pIter - pCell);
54089     if( nSize<4 ) nSize = 4;
54090   }else{
54091     int minLocal = pPage->minLocal;
54092     nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
54093     testcase( nSize==pPage->maxLocal );
54094     testcase( nSize==pPage->maxLocal+1 );
54095     if( nSize>pPage->maxLocal ){
54096       nSize = minLocal;
54097     }
54098     nSize += 4 + (u16)(pIter - pCell);
54099   }
54100   assert( nSize==debuginfo.nSize || CORRUPT_DB );
54101   return (u16)nSize;
54102 }
54103
54104 #ifdef SQLITE_DEBUG
54105 /* This variation on cellSizePtr() is used inside of assert() statements
54106 ** only. */
54107 static u16 cellSize(MemPage *pPage, int iCell){
54108   return cellSizePtr(pPage, findCell(pPage, iCell));
54109 }
54110 #endif
54111
54112 #ifndef SQLITE_OMIT_AUTOVACUUM
54113 /*
54114 ** If the cell pCell, part of page pPage contains a pointer
54115 ** to an overflow page, insert an entry into the pointer-map
54116 ** for the overflow page.
54117 */
54118 static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
54119   CellInfo info;
54120   if( *pRC ) return;
54121   assert( pCell!=0 );
54122   btreeParseCellPtr(pPage, pCell, &info);
54123   if( info.iOverflow ){
54124     Pgno ovfl = get4byte(&pCell[info.iOverflow]);
54125     ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
54126   }
54127 }
54128 #endif
54129
54130
54131 /*
54132 ** Defragment the page given.  All Cells are moved to the
54133 ** end of the page and all free space is collected into one
54134 ** big FreeBlk that occurs in between the header and cell
54135 ** pointer array and the cell content area.
54136 **
54137 ** EVIDENCE-OF: R-44582-60138 SQLite may from time to time reorganize a
54138 ** b-tree page so that there are no freeblocks or fragment bytes, all
54139 ** unused bytes are contained in the unallocated space region, and all
54140 ** cells are packed tightly at the end of the page.
54141 */
54142 static int defragmentPage(MemPage *pPage){
54143   int i;                     /* Loop counter */
54144   int pc;                    /* Address of the i-th cell */
54145   int hdr;                   /* Offset to the page header */
54146   int size;                  /* Size of a cell */
54147   int usableSize;            /* Number of usable bytes on a page */
54148   int cellOffset;            /* Offset to the cell pointer array */
54149   int cbrk;                  /* Offset to the cell content area */
54150   int nCell;                 /* Number of cells on the page */
54151   unsigned char *data;       /* The page data */
54152   unsigned char *temp;       /* Temp area for cell content */
54153   unsigned char *src;        /* Source of content */
54154   int iCellFirst;            /* First allowable cell index */
54155   int iCellLast;             /* Last possible cell index */
54156
54157
54158   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
54159   assert( pPage->pBt!=0 );
54160   assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
54161   assert( pPage->nOverflow==0 );
54162   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54163   temp = 0;
54164   src = data = pPage->aData;
54165   hdr = pPage->hdrOffset;
54166   cellOffset = pPage->cellOffset;
54167   nCell = pPage->nCell;
54168   assert( nCell==get2byte(&data[hdr+3]) );
54169   usableSize = pPage->pBt->usableSize;
54170   cbrk = usableSize;
54171   iCellFirst = cellOffset + 2*nCell;
54172   iCellLast = usableSize - 4;
54173   for(i=0; i<nCell; i++){
54174     u8 *pAddr;     /* The i-th cell pointer */
54175     pAddr = &data[cellOffset + i*2];
54176     pc = get2byte(pAddr);
54177     testcase( pc==iCellFirst );
54178     testcase( pc==iCellLast );
54179 #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
54180     /* These conditions have already been verified in btreeInitPage()
54181     ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined 
54182     */
54183     if( pc<iCellFirst || pc>iCellLast ){
54184       return SQLITE_CORRUPT_BKPT;
54185     }
54186 #endif
54187     assert( pc>=iCellFirst && pc<=iCellLast );
54188     size = cellSizePtr(pPage, &src[pc]);
54189     cbrk -= size;
54190 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
54191     if( cbrk<iCellFirst ){
54192       return SQLITE_CORRUPT_BKPT;
54193     }
54194 #else
54195     if( cbrk<iCellFirst || pc+size>usableSize ){
54196       return SQLITE_CORRUPT_BKPT;
54197     }
54198 #endif
54199     assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
54200     testcase( cbrk+size==usableSize );
54201     testcase( pc+size==usableSize );
54202     put2byte(pAddr, cbrk);
54203     if( temp==0 ){
54204       int x;
54205       if( cbrk==pc ) continue;
54206       temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
54207       x = get2byte(&data[hdr+5]);
54208       memcpy(&temp[x], &data[x], (cbrk+size) - x);
54209       src = temp;
54210     }
54211     memcpy(&data[cbrk], &src[pc], size);
54212   }
54213   assert( cbrk>=iCellFirst );
54214   put2byte(&data[hdr+5], cbrk);
54215   data[hdr+1] = 0;
54216   data[hdr+2] = 0;
54217   data[hdr+7] = 0;
54218   memset(&data[iCellFirst], 0, cbrk-iCellFirst);
54219   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
54220   if( cbrk-iCellFirst!=pPage->nFree ){
54221     return SQLITE_CORRUPT_BKPT;
54222   }
54223   return SQLITE_OK;
54224 }
54225
54226 /*
54227 ** Search the free-list on page pPg for space to store a cell nByte bytes in
54228 ** size. If one can be found, return a pointer to the space and remove it
54229 ** from the free-list.
54230 **
54231 ** If no suitable space can be found on the free-list, return NULL.
54232 **
54233 ** This function may detect corruption within pPg.  If corruption is
54234 ** detected then *pRc is set to SQLITE_CORRUPT and NULL is returned.
54235 **
54236 ** If a slot of at least nByte bytes is found but cannot be used because 
54237 ** there are already at least 60 fragmented bytes on the page, return NULL.
54238 ** In this case, if pbDefrag parameter is not NULL, set *pbDefrag to true.
54239 */
54240 static u8 *pageFindSlot(MemPage *pPg, int nByte, int *pRc, int *pbDefrag){
54241   const int hdr = pPg->hdrOffset;
54242   u8 * const aData = pPg->aData;
54243   int iAddr;
54244   int pc;
54245   int usableSize = pPg->pBt->usableSize;
54246
54247   for(iAddr=hdr+1; (pc = get2byte(&aData[iAddr]))>0; iAddr=pc){
54248     int size;            /* Size of the free slot */
54249     /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
54250     ** increasing offset. */
54251     if( pc>usableSize-4 || pc<iAddr+4 ){
54252       *pRc = SQLITE_CORRUPT_BKPT;
54253       return 0;
54254     }
54255     /* EVIDENCE-OF: R-22710-53328 The third and fourth bytes of each
54256     ** freeblock form a big-endian integer which is the size of the freeblock
54257     ** in bytes, including the 4-byte header. */
54258     size = get2byte(&aData[pc+2]);
54259     if( size>=nByte ){
54260       int x = size - nByte;
54261       testcase( x==4 );
54262       testcase( x==3 );
54263       if( x<4 ){
54264         /* EVIDENCE-OF: R-11498-58022 In a well-formed b-tree page, the total
54265         ** number of bytes in fragments may not exceed 60. */
54266         if( aData[hdr+7]>=60 ){
54267           if( pbDefrag ) *pbDefrag = 1;
54268           return 0;
54269         }
54270         /* Remove the slot from the free-list. Update the number of
54271         ** fragmented bytes within the page. */
54272         memcpy(&aData[iAddr], &aData[pc], 2);
54273         aData[hdr+7] += (u8)x;
54274       }else if( size+pc > usableSize ){
54275         *pRc = SQLITE_CORRUPT_BKPT;
54276         return 0;
54277       }else{
54278         /* The slot remains on the free-list. Reduce its size to account
54279          ** for the portion used by the new allocation. */
54280         put2byte(&aData[pc+2], x);
54281       }
54282       return &aData[pc + x];
54283     }
54284   }
54285
54286   return 0;
54287 }
54288
54289 /*
54290 ** Allocate nByte bytes of space from within the B-Tree page passed
54291 ** as the first argument. Write into *pIdx the index into pPage->aData[]
54292 ** of the first byte of allocated space. Return either SQLITE_OK or
54293 ** an error code (usually SQLITE_CORRUPT).
54294 **
54295 ** The caller guarantees that there is sufficient space to make the
54296 ** allocation.  This routine might need to defragment in order to bring
54297 ** all the space together, however.  This routine will avoid using
54298 ** the first two bytes past the cell pointer area since presumably this
54299 ** allocation is being made in order to insert a new cell, so we will
54300 ** also end up needing a new cell pointer.
54301 */
54302 static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
54303   const int hdr = pPage->hdrOffset;    /* Local cache of pPage->hdrOffset */
54304   u8 * const data = pPage->aData;      /* Local cache of pPage->aData */
54305   int top;                             /* First byte of cell content area */
54306   int rc = SQLITE_OK;                  /* Integer return code */
54307   int gap;        /* First byte of gap between cell pointers and cell content */
54308   
54309   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
54310   assert( pPage->pBt );
54311   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54312   assert( nByte>=0 );  /* Minimum cell size is 4 */
54313   assert( pPage->nFree>=nByte );
54314   assert( pPage->nOverflow==0 );
54315   assert( nByte < (int)(pPage->pBt->usableSize-8) );
54316
54317   assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
54318   gap = pPage->cellOffset + 2*pPage->nCell;
54319   assert( gap<=65536 );
54320   /* EVIDENCE-OF: R-29356-02391 If the database uses a 65536-byte page size
54321   ** and the reserved space is zero (the usual value for reserved space)
54322   ** then the cell content offset of an empty page wants to be 65536.
54323   ** However, that integer is too large to be stored in a 2-byte unsigned
54324   ** integer, so a value of 0 is used in its place. */
54325   top = get2byteNotZero(&data[hdr+5]);
54326   if( gap>top ) return SQLITE_CORRUPT_BKPT;
54327
54328   /* If there is enough space between gap and top for one more cell pointer
54329   ** array entry offset, and if the freelist is not empty, then search the
54330   ** freelist looking for a free slot big enough to satisfy the request.
54331   */
54332   testcase( gap+2==top );
54333   testcase( gap+1==top );
54334   testcase( gap==top );
54335   if( gap+2<=top && (data[hdr+1] || data[hdr+2]) ){
54336     int bDefrag = 0;
54337     u8 *pSpace = pageFindSlot(pPage, nByte, &rc, &bDefrag);
54338     if( rc ) return rc;
54339     if( bDefrag ) goto defragment_page;
54340     if( pSpace ){
54341       assert( pSpace>=data && (pSpace - data)<65536 );
54342       *pIdx = (int)(pSpace - data);
54343       return SQLITE_OK;
54344     }
54345   }
54346
54347   /* The request could not be fulfilled using a freelist slot.  Check
54348   ** to see if defragmentation is necessary.
54349   */
54350   testcase( gap+2+nByte==top );
54351   if( gap+2+nByte>top ){
54352  defragment_page:
54353     assert( pPage->nCell>0 || CORRUPT_DB );
54354     rc = defragmentPage(pPage);
54355     if( rc ) return rc;
54356     top = get2byteNotZero(&data[hdr+5]);
54357     assert( gap+nByte<=top );
54358   }
54359
54360
54361   /* Allocate memory from the gap in between the cell pointer array
54362   ** and the cell content area.  The btreeInitPage() call has already
54363   ** validated the freelist.  Given that the freelist is valid, there
54364   ** is no way that the allocation can extend off the end of the page.
54365   ** The assert() below verifies the previous sentence.
54366   */
54367   top -= nByte;
54368   put2byte(&data[hdr+5], top);
54369   assert( top+nByte <= (int)pPage->pBt->usableSize );
54370   *pIdx = top;
54371   return SQLITE_OK;
54372 }
54373
54374 /*
54375 ** Return a section of the pPage->aData to the freelist.
54376 ** The first byte of the new free block is pPage->aData[iStart]
54377 ** and the size of the block is iSize bytes.
54378 **
54379 ** Adjacent freeblocks are coalesced.
54380 **
54381 ** Note that even though the freeblock list was checked by btreeInitPage(),
54382 ** that routine will not detect overlap between cells or freeblocks.  Nor
54383 ** does it detect cells or freeblocks that encrouch into the reserved bytes
54384 ** at the end of the page.  So do additional corruption checks inside this
54385 ** routine and return SQLITE_CORRUPT if any problems are found.
54386 */
54387 static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
54388   u16 iPtr;                             /* Address of ptr to next freeblock */
54389   u16 iFreeBlk;                         /* Address of the next freeblock */
54390   u8 hdr;                               /* Page header size.  0 or 100 */
54391   u8 nFrag = 0;                         /* Reduction in fragmentation */
54392   u16 iOrigSize = iSize;                /* Original value of iSize */
54393   u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
54394   u32 iEnd = iStart + iSize;            /* First byte past the iStart buffer */
54395   unsigned char *data = pPage->aData;   /* Page content */
54396
54397   assert( pPage->pBt!=0 );
54398   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
54399   assert( iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
54400   assert( CORRUPT_DB || iEnd <= pPage->pBt->usableSize );
54401   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54402   assert( iSize>=4 );   /* Minimum cell size is 4 */
54403   assert( iStart<=iLast );
54404
54405   /* Overwrite deleted information with zeros when the secure_delete
54406   ** option is enabled */
54407   if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
54408     memset(&data[iStart], 0, iSize);
54409   }
54410
54411   /* The list of freeblocks must be in ascending order.  Find the 
54412   ** spot on the list where iStart should be inserted.
54413   */
54414   hdr = pPage->hdrOffset;
54415   iPtr = hdr + 1;
54416   if( data[iPtr+1]==0 && data[iPtr]==0 ){
54417     iFreeBlk = 0;  /* Shortcut for the case when the freelist is empty */
54418   }else{
54419     while( (iFreeBlk = get2byte(&data[iPtr]))>0 && iFreeBlk<iStart ){
54420       if( iFreeBlk<iPtr+4 ) return SQLITE_CORRUPT_BKPT;
54421       iPtr = iFreeBlk;
54422     }
54423     if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
54424     assert( iFreeBlk>iPtr || iFreeBlk==0 );
54425   
54426     /* At this point:
54427     **    iFreeBlk:   First freeblock after iStart, or zero if none
54428     **    iPtr:       The address of a pointer iFreeBlk
54429     **
54430     ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
54431     */
54432     if( iFreeBlk && iEnd+3>=iFreeBlk ){
54433       nFrag = iFreeBlk - iEnd;
54434       if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
54435       iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
54436       iSize = iEnd - iStart;
54437       iFreeBlk = get2byte(&data[iFreeBlk]);
54438     }
54439   
54440     /* If iPtr is another freeblock (that is, if iPtr is not the freelist
54441     ** pointer in the page header) then check to see if iStart should be
54442     ** coalesced onto the end of iPtr.
54443     */
54444     if( iPtr>hdr+1 ){
54445       int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
54446       if( iPtrEnd+3>=iStart ){
54447         if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
54448         nFrag += iStart - iPtrEnd;
54449         iSize = iEnd - iPtr;
54450         iStart = iPtr;
54451       }
54452     }
54453     if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
54454     data[hdr+7] -= nFrag;
54455   }
54456   if( iStart==get2byte(&data[hdr+5]) ){
54457     /* The new freeblock is at the beginning of the cell content area,
54458     ** so just extend the cell content area rather than create another
54459     ** freelist entry */
54460     if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
54461     put2byte(&data[hdr+1], iFreeBlk);
54462     put2byte(&data[hdr+5], iEnd);
54463   }else{
54464     /* Insert the new freeblock into the freelist */
54465     put2byte(&data[iPtr], iStart);
54466     put2byte(&data[iStart], iFreeBlk);
54467     put2byte(&data[iStart+2], iSize);
54468   }
54469   pPage->nFree += iOrigSize;
54470   return SQLITE_OK;
54471 }
54472
54473 /*
54474 ** Decode the flags byte (the first byte of the header) for a page
54475 ** and initialize fields of the MemPage structure accordingly.
54476 **
54477 ** Only the following combinations are supported.  Anything different
54478 ** indicates a corrupt database files:
54479 **
54480 **         PTF_ZERODATA
54481 **         PTF_ZERODATA | PTF_LEAF
54482 **         PTF_LEAFDATA | PTF_INTKEY
54483 **         PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
54484 */
54485 static int decodeFlags(MemPage *pPage, int flagByte){
54486   BtShared *pBt;     /* A copy of pPage->pBt */
54487
54488   assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
54489   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54490   pPage->leaf = (u8)(flagByte>>3);  assert( PTF_LEAF == 1<<3 );
54491   flagByte &= ~PTF_LEAF;
54492   pPage->childPtrSize = 4-4*pPage->leaf;
54493   pBt = pPage->pBt;
54494   if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
54495     /* EVIDENCE-OF: R-03640-13415 A value of 5 means the page is an interior
54496     ** table b-tree page. */
54497     assert( (PTF_LEAFDATA|PTF_INTKEY)==5 );
54498     /* EVIDENCE-OF: R-20501-61796 A value of 13 means the page is a leaf
54499     ** table b-tree page. */
54500     assert( (PTF_LEAFDATA|PTF_INTKEY|PTF_LEAF)==13 );
54501     pPage->intKey = 1;
54502     pPage->intKeyLeaf = pPage->leaf;
54503     pPage->noPayload = !pPage->leaf;
54504     pPage->maxLocal = pBt->maxLeaf;
54505     pPage->minLocal = pBt->minLeaf;
54506   }else if( flagByte==PTF_ZERODATA ){
54507     /* EVIDENCE-OF: R-27225-53936 A value of 2 means the page is an interior
54508     ** index b-tree page. */
54509     assert( (PTF_ZERODATA)==2 );
54510     /* EVIDENCE-OF: R-16571-11615 A value of 10 means the page is a leaf
54511     ** index b-tree page. */
54512     assert( (PTF_ZERODATA|PTF_LEAF)==10 );
54513     pPage->intKey = 0;
54514     pPage->intKeyLeaf = 0;
54515     pPage->noPayload = 0;
54516     pPage->maxLocal = pBt->maxLocal;
54517     pPage->minLocal = pBt->minLocal;
54518   }else{
54519     /* EVIDENCE-OF: R-47608-56469 Any other value for the b-tree page type is
54520     ** an error. */
54521     return SQLITE_CORRUPT_BKPT;
54522   }
54523   pPage->max1bytePayload = pBt->max1bytePayload;
54524   return SQLITE_OK;
54525 }
54526
54527 /*
54528 ** Initialize the auxiliary information for a disk block.
54529 **
54530 ** Return SQLITE_OK on success.  If we see that the page does
54531 ** not contain a well-formed database page, then return 
54532 ** SQLITE_CORRUPT.  Note that a return of SQLITE_OK does not
54533 ** guarantee that the page is well-formed.  It only shows that
54534 ** we failed to detect any corruption.
54535 */
54536 static int btreeInitPage(MemPage *pPage){
54537
54538   assert( pPage->pBt!=0 );
54539   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54540   assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
54541   assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
54542   assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
54543
54544   if( !pPage->isInit ){
54545     u16 pc;            /* Address of a freeblock within pPage->aData[] */
54546     u8 hdr;            /* Offset to beginning of page header */
54547     u8 *data;          /* Equal to pPage->aData */
54548     BtShared *pBt;        /* The main btree structure */
54549     int usableSize;    /* Amount of usable space on each page */
54550     u16 cellOffset;    /* Offset from start of page to first cell pointer */
54551     int nFree;         /* Number of unused bytes on the page */
54552     int top;           /* First byte of the cell content area */
54553     int iCellFirst;    /* First allowable cell or freeblock offset */
54554     int iCellLast;     /* Last possible cell or freeblock offset */
54555
54556     pBt = pPage->pBt;
54557
54558     hdr = pPage->hdrOffset;
54559     data = pPage->aData;
54560     /* EVIDENCE-OF: R-28594-02890 The one-byte flag at offset 0 indicating
54561     ** the b-tree page type. */
54562     if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
54563     assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
54564     pPage->maskPage = (u16)(pBt->pageSize - 1);
54565     pPage->nOverflow = 0;
54566     usableSize = pBt->usableSize;
54567     pPage->cellOffset = cellOffset = hdr + 8 + pPage->childPtrSize;
54568     pPage->aDataEnd = &data[usableSize];
54569     pPage->aCellIdx = &data[cellOffset];
54570     /* EVIDENCE-OF: R-58015-48175 The two-byte integer at offset 5 designates
54571     ** the start of the cell content area. A zero value for this integer is
54572     ** interpreted as 65536. */
54573     top = get2byteNotZero(&data[hdr+5]);
54574     /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
54575     ** number of cells on the page. */
54576     pPage->nCell = get2byte(&data[hdr+3]);
54577     if( pPage->nCell>MX_CELL(pBt) ){
54578       /* To many cells for a single page.  The page must be corrupt */
54579       return SQLITE_CORRUPT_BKPT;
54580     }
54581     testcase( pPage->nCell==MX_CELL(pBt) );
54582     /* EVIDENCE-OF: R-24089-57979 If a page contains no cells (which is only
54583     ** possible for a root page of a table that contains no rows) then the
54584     ** offset to the cell content area will equal the page size minus the
54585     ** bytes of reserved space. */
54586     assert( pPage->nCell>0 || top==usableSize || CORRUPT_DB );
54587
54588     /* A malformed database page might cause us to read past the end
54589     ** of page when parsing a cell.  
54590     **
54591     ** The following block of code checks early to see if a cell extends
54592     ** past the end of a page boundary and causes SQLITE_CORRUPT to be 
54593     ** returned if it does.
54594     */
54595     iCellFirst = cellOffset + 2*pPage->nCell;
54596     iCellLast = usableSize - 4;
54597 #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
54598     {
54599       int i;            /* Index into the cell pointer array */
54600       int sz;           /* Size of a cell */
54601
54602       if( !pPage->leaf ) iCellLast--;
54603       for(i=0; i<pPage->nCell; i++){
54604         pc = get2byte(&data[cellOffset+i*2]);
54605         testcase( pc==iCellFirst );
54606         testcase( pc==iCellLast );
54607         if( pc<iCellFirst || pc>iCellLast ){
54608           return SQLITE_CORRUPT_BKPT;
54609         }
54610         sz = cellSizePtr(pPage, &data[pc]);
54611         testcase( pc+sz==usableSize );
54612         if( pc+sz>usableSize ){
54613           return SQLITE_CORRUPT_BKPT;
54614         }
54615       }
54616       if( !pPage->leaf ) iCellLast++;
54617     }  
54618 #endif
54619
54620     /* Compute the total free space on the page
54621     ** EVIDENCE-OF: R-23588-34450 The two-byte integer at offset 1 gives the
54622     ** start of the first freeblock on the page, or is zero if there are no
54623     ** freeblocks. */
54624     pc = get2byte(&data[hdr+1]);
54625     nFree = data[hdr+7] + top;  /* Init nFree to non-freeblock free space */
54626     while( pc>0 ){
54627       u16 next, size;
54628       if( pc<iCellFirst || pc>iCellLast ){
54629         /* EVIDENCE-OF: R-55530-52930 In a well-formed b-tree page, there will
54630         ** always be at least one cell before the first freeblock.
54631         **
54632         ** Or, the freeblock is off the end of the page
54633         */
54634         return SQLITE_CORRUPT_BKPT; 
54635       }
54636       next = get2byte(&data[pc]);
54637       size = get2byte(&data[pc+2]);
54638       if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
54639         /* Free blocks must be in ascending order. And the last byte of
54640         ** the free-block must lie on the database page.  */
54641         return SQLITE_CORRUPT_BKPT; 
54642       }
54643       nFree = nFree + size;
54644       pc = next;
54645     }
54646
54647     /* At this point, nFree contains the sum of the offset to the start
54648     ** of the cell-content area plus the number of free bytes within
54649     ** the cell-content area. If this is greater than the usable-size
54650     ** of the page, then the page must be corrupted. This check also
54651     ** serves to verify that the offset to the start of the cell-content
54652     ** area, according to the page header, lies within the page.
54653     */
54654     if( nFree>usableSize ){
54655       return SQLITE_CORRUPT_BKPT; 
54656     }
54657     pPage->nFree = (u16)(nFree - iCellFirst);
54658     pPage->isInit = 1;
54659   }
54660   return SQLITE_OK;
54661 }
54662
54663 /*
54664 ** Set up a raw page so that it looks like a database page holding
54665 ** no entries.
54666 */
54667 static void zeroPage(MemPage *pPage, int flags){
54668   unsigned char *data = pPage->aData;
54669   BtShared *pBt = pPage->pBt;
54670   u8 hdr = pPage->hdrOffset;
54671   u16 first;
54672
54673   assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
54674   assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
54675   assert( sqlite3PagerGetData(pPage->pDbPage) == data );
54676   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
54677   assert( sqlite3_mutex_held(pBt->mutex) );
54678   if( pBt->btsFlags & BTS_SECURE_DELETE ){
54679     memset(&data[hdr], 0, pBt->usableSize - hdr);
54680   }
54681   data[hdr] = (char)flags;
54682   first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
54683   memset(&data[hdr+1], 0, 4);
54684   data[hdr+7] = 0;
54685   put2byte(&data[hdr+5], pBt->usableSize);
54686   pPage->nFree = (u16)(pBt->usableSize - first);
54687   decodeFlags(pPage, flags);
54688   pPage->cellOffset = first;
54689   pPage->aDataEnd = &data[pBt->usableSize];
54690   pPage->aCellIdx = &data[first];
54691   pPage->nOverflow = 0;
54692   assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
54693   pPage->maskPage = (u16)(pBt->pageSize - 1);
54694   pPage->nCell = 0;
54695   pPage->isInit = 1;
54696 }
54697
54698
54699 /*
54700 ** Convert a DbPage obtained from the pager into a MemPage used by
54701 ** the btree layer.
54702 */
54703 static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
54704   MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
54705   pPage->aData = sqlite3PagerGetData(pDbPage);
54706   pPage->pDbPage = pDbPage;
54707   pPage->pBt = pBt;
54708   pPage->pgno = pgno;
54709   pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
54710   return pPage; 
54711 }
54712
54713 /*
54714 ** Get a page from the pager.  Initialize the MemPage.pBt and
54715 ** MemPage.aData elements if needed.
54716 **
54717 ** If the noContent flag is set, it means that we do not care about
54718 ** the content of the page at this time.  So do not go to the disk
54719 ** to fetch the content.  Just fill in the content with zeros for now.
54720 ** If in the future we call sqlite3PagerWrite() on this page, that
54721 ** means we have started to be concerned about content and the disk
54722 ** read should occur at that point.
54723 */
54724 static int btreeGetPage(
54725   BtShared *pBt,       /* The btree */
54726   Pgno pgno,           /* Number of the page to fetch */
54727   MemPage **ppPage,    /* Return the page in this parameter */
54728   int flags            /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
54729 ){
54730   int rc;
54731   DbPage *pDbPage;
54732
54733   assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
54734   assert( sqlite3_mutex_held(pBt->mutex) );
54735   rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
54736   if( rc ) return rc;
54737   *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
54738   return SQLITE_OK;
54739 }
54740
54741 /*
54742 ** Retrieve a page from the pager cache. If the requested page is not
54743 ** already in the pager cache return NULL. Initialize the MemPage.pBt and
54744 ** MemPage.aData elements if needed.
54745 */
54746 static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
54747   DbPage *pDbPage;
54748   assert( sqlite3_mutex_held(pBt->mutex) );
54749   pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
54750   if( pDbPage ){
54751     return btreePageFromDbPage(pDbPage, pgno, pBt);
54752   }
54753   return 0;
54754 }
54755
54756 /*
54757 ** Return the size of the database file in pages. If there is any kind of
54758 ** error, return ((unsigned int)-1).
54759 */
54760 static Pgno btreePagecount(BtShared *pBt){
54761   return pBt->nPage;
54762 }
54763 SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
54764   assert( sqlite3BtreeHoldsMutex(p) );
54765   assert( ((p->pBt->nPage)&0x8000000)==0 );
54766   return btreePagecount(p->pBt);
54767 }
54768
54769 /*
54770 ** Get a page from the pager and initialize it.  This routine is just a
54771 ** convenience wrapper around separate calls to btreeGetPage() and 
54772 ** btreeInitPage().
54773 **
54774 ** If an error occurs, then the value *ppPage is set to is undefined. It
54775 ** may remain unchanged, or it may be set to an invalid value.
54776 */
54777 static int getAndInitPage(
54778   BtShared *pBt,                  /* The database file */
54779   Pgno pgno,                      /* Number of the page to get */
54780   MemPage **ppPage,               /* Write the page pointer here */
54781   int bReadonly                   /* PAGER_GET_READONLY or 0 */
54782 ){
54783   int rc;
54784   assert( sqlite3_mutex_held(pBt->mutex) );
54785   assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 );
54786
54787   if( pgno>btreePagecount(pBt) ){
54788     rc = SQLITE_CORRUPT_BKPT;
54789   }else{
54790     rc = btreeGetPage(pBt, pgno, ppPage, bReadonly);
54791     if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
54792       rc = btreeInitPage(*ppPage);
54793       if( rc!=SQLITE_OK ){
54794         releasePage(*ppPage);
54795       }
54796     }
54797   }
54798
54799   testcase( pgno==0 );
54800   assert( pgno!=0 || rc==SQLITE_CORRUPT );
54801   return rc;
54802 }
54803
54804 /*
54805 ** Release a MemPage.  This should be called once for each prior
54806 ** call to btreeGetPage.
54807 */
54808 static void releasePage(MemPage *pPage){
54809   if( pPage ){
54810     assert( pPage->aData );
54811     assert( pPage->pBt );
54812     assert( pPage->pDbPage!=0 );
54813     assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
54814     assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
54815     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54816     sqlite3PagerUnrefNotNull(pPage->pDbPage);
54817   }
54818 }
54819
54820 /*
54821 ** During a rollback, when the pager reloads information into the cache
54822 ** so that the cache is restored to its original state at the start of
54823 ** the transaction, for each page restored this routine is called.
54824 **
54825 ** This routine needs to reset the extra data section at the end of the
54826 ** page to agree with the restored data.
54827 */
54828 static void pageReinit(DbPage *pData){
54829   MemPage *pPage;
54830   pPage = (MemPage *)sqlite3PagerGetExtra(pData);
54831   assert( sqlite3PagerPageRefcount(pData)>0 );
54832   if( pPage->isInit ){
54833     assert( sqlite3_mutex_held(pPage->pBt->mutex) );
54834     pPage->isInit = 0;
54835     if( sqlite3PagerPageRefcount(pData)>1 ){
54836       /* pPage might not be a btree page;  it might be an overflow page
54837       ** or ptrmap page or a free page.  In those cases, the following
54838       ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
54839       ** But no harm is done by this.  And it is very important that
54840       ** btreeInitPage() be called on every btree page so we make
54841       ** the call for every page that comes in for re-initing. */
54842       btreeInitPage(pPage);
54843     }
54844   }
54845 }
54846
54847 /*
54848 ** Invoke the busy handler for a btree.
54849 */
54850 static int btreeInvokeBusyHandler(void *pArg){
54851   BtShared *pBt = (BtShared*)pArg;
54852   assert( pBt->db );
54853   assert( sqlite3_mutex_held(pBt->db->mutex) );
54854   return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
54855 }
54856
54857 /*
54858 ** Open a database file.
54859 ** 
54860 ** zFilename is the name of the database file.  If zFilename is NULL
54861 ** then an ephemeral database is created.  The ephemeral database might
54862 ** be exclusively in memory, or it might use a disk-based memory cache.
54863 ** Either way, the ephemeral database will be automatically deleted 
54864 ** when sqlite3BtreeClose() is called.
54865 **
54866 ** If zFilename is ":memory:" then an in-memory database is created
54867 ** that is automatically destroyed when it is closed.
54868 **
54869 ** The "flags" parameter is a bitmask that might contain bits like
54870 ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
54871 **
54872 ** If the database is already opened in the same database connection
54873 ** and we are in shared cache mode, then the open will fail with an
54874 ** SQLITE_CONSTRAINT error.  We cannot allow two or more BtShared
54875 ** objects in the same database connection since doing so will lead
54876 ** to problems with locking.
54877 */
54878 SQLITE_PRIVATE int sqlite3BtreeOpen(
54879   sqlite3_vfs *pVfs,      /* VFS to use for this b-tree */
54880   const char *zFilename,  /* Name of the file containing the BTree database */
54881   sqlite3 *db,            /* Associated database handle */
54882   Btree **ppBtree,        /* Pointer to new Btree object written here */
54883   int flags,              /* Options */
54884   int vfsFlags            /* Flags passed through to sqlite3_vfs.xOpen() */
54885 ){
54886   BtShared *pBt = 0;             /* Shared part of btree structure */
54887   Btree *p;                      /* Handle to return */
54888   sqlite3_mutex *mutexOpen = 0;  /* Prevents a race condition. Ticket #3537 */
54889   int rc = SQLITE_OK;            /* Result code from this function */
54890   u8 nReserve;                   /* Byte of unused space on each page */
54891   unsigned char zDbHeader[100];  /* Database header content */
54892
54893   /* True if opening an ephemeral, temporary database */
54894   const int isTempDb = zFilename==0 || zFilename[0]==0;
54895
54896   /* Set the variable isMemdb to true for an in-memory database, or 
54897   ** false for a file-based database.
54898   */
54899 #ifdef SQLITE_OMIT_MEMORYDB
54900   const int isMemdb = 0;
54901 #else
54902   const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
54903                        || (isTempDb && sqlite3TempInMemory(db))
54904                        || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
54905 #endif
54906
54907   assert( db!=0 );
54908   assert( pVfs!=0 );
54909   assert( sqlite3_mutex_held(db->mutex) );
54910   assert( (flags&0xff)==flags );   /* flags fit in 8 bits */
54911
54912   /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
54913   assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
54914
54915   /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
54916   assert( (flags & BTREE_SINGLE)==0 || isTempDb );
54917
54918   if( isMemdb ){
54919     flags |= BTREE_MEMORY;
54920   }
54921   if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
54922     vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
54923   }
54924   p = sqlite3MallocZero(sizeof(Btree));
54925   if( !p ){
54926     return SQLITE_NOMEM;
54927   }
54928   p->inTrans = TRANS_NONE;
54929   p->db = db;
54930 #ifndef SQLITE_OMIT_SHARED_CACHE
54931   p->lock.pBtree = p;
54932   p->lock.iTable = 1;
54933 #endif
54934
54935 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
54936   /*
54937   ** If this Btree is a candidate for shared cache, try to find an
54938   ** existing BtShared object that we can share with
54939   */
54940   if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
54941     if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
54942       int nFilename = sqlite3Strlen30(zFilename)+1;
54943       int nFullPathname = pVfs->mxPathname+1;
54944       char *zFullPathname = sqlite3Malloc(MAX(nFullPathname,nFilename));
54945       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
54946
54947       p->sharable = 1;
54948       if( !zFullPathname ){
54949         sqlite3_free(p);
54950         return SQLITE_NOMEM;
54951       }
54952       if( isMemdb ){
54953         memcpy(zFullPathname, zFilename, nFilename);
54954       }else{
54955         rc = sqlite3OsFullPathname(pVfs, zFilename,
54956                                    nFullPathname, zFullPathname);
54957         if( rc ){
54958           sqlite3_free(zFullPathname);
54959           sqlite3_free(p);
54960           return rc;
54961         }
54962       }
54963 #if SQLITE_THREADSAFE
54964       mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
54965       sqlite3_mutex_enter(mutexOpen);
54966       mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
54967       sqlite3_mutex_enter(mutexShared);
54968 #endif
54969       for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
54970         assert( pBt->nRef>0 );
54971         if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
54972                  && sqlite3PagerVfs(pBt->pPager)==pVfs ){
54973           int iDb;
54974           for(iDb=db->nDb-1; iDb>=0; iDb--){
54975             Btree *pExisting = db->aDb[iDb].pBt;
54976             if( pExisting && pExisting->pBt==pBt ){
54977               sqlite3_mutex_leave(mutexShared);
54978               sqlite3_mutex_leave(mutexOpen);
54979               sqlite3_free(zFullPathname);
54980               sqlite3_free(p);
54981               return SQLITE_CONSTRAINT;
54982             }
54983           }
54984           p->pBt = pBt;
54985           pBt->nRef++;
54986           break;
54987         }
54988       }
54989       sqlite3_mutex_leave(mutexShared);
54990       sqlite3_free(zFullPathname);
54991     }
54992 #ifdef SQLITE_DEBUG
54993     else{
54994       /* In debug mode, we mark all persistent databases as sharable
54995       ** even when they are not.  This exercises the locking code and
54996       ** gives more opportunity for asserts(sqlite3_mutex_held())
54997       ** statements to find locking problems.
54998       */
54999       p->sharable = 1;
55000     }
55001 #endif
55002   }
55003 #endif
55004   if( pBt==0 ){
55005     /*
55006     ** The following asserts make sure that structures used by the btree are
55007     ** the right size.  This is to guard against size changes that result
55008     ** when compiling on a different architecture.
55009     */
55010     assert( sizeof(i64)==8 );
55011     assert( sizeof(u64)==8 );
55012     assert( sizeof(u32)==4 );
55013     assert( sizeof(u16)==2 );
55014     assert( sizeof(Pgno)==4 );
55015   
55016     pBt = sqlite3MallocZero( sizeof(*pBt) );
55017     if( pBt==0 ){
55018       rc = SQLITE_NOMEM;
55019       goto btree_open_out;
55020     }
55021     rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
55022                           EXTRA_SIZE, flags, vfsFlags, pageReinit);
55023     if( rc==SQLITE_OK ){
55024       sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
55025       rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
55026     }
55027     if( rc!=SQLITE_OK ){
55028       goto btree_open_out;
55029     }
55030     pBt->openFlags = (u8)flags;
55031     pBt->db = db;
55032     sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
55033     p->pBt = pBt;
55034   
55035     pBt->pCursor = 0;
55036     pBt->pPage1 = 0;
55037     if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
55038 #ifdef SQLITE_SECURE_DELETE
55039     pBt->btsFlags |= BTS_SECURE_DELETE;
55040 #endif
55041     /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
55042     ** determined by the 2-byte integer located at an offset of 16 bytes from
55043     ** the beginning of the database file. */
55044     pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
55045     if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
55046          || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
55047       pBt->pageSize = 0;
55048 #ifndef SQLITE_OMIT_AUTOVACUUM
55049       /* If the magic name ":memory:" will create an in-memory database, then
55050       ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
55051       ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
55052       ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
55053       ** regular file-name. In this case the auto-vacuum applies as per normal.
55054       */
55055       if( zFilename && !isMemdb ){
55056         pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
55057         pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
55058       }
55059 #endif
55060       nReserve = 0;
55061     }else{
55062       /* EVIDENCE-OF: R-37497-42412 The size of the reserved region is
55063       ** determined by the one-byte unsigned integer found at an offset of 20
55064       ** into the database file header. */
55065       nReserve = zDbHeader[20];
55066       pBt->btsFlags |= BTS_PAGESIZE_FIXED;
55067 #ifndef SQLITE_OMIT_AUTOVACUUM
55068       pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
55069       pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
55070 #endif
55071     }
55072     rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
55073     if( rc ) goto btree_open_out;
55074     pBt->usableSize = pBt->pageSize - nReserve;
55075     assert( (pBt->pageSize & 7)==0 );  /* 8-byte alignment of pageSize */
55076    
55077 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
55078     /* Add the new BtShared object to the linked list sharable BtShareds.
55079     */
55080     if( p->sharable ){
55081       MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
55082       pBt->nRef = 1;
55083       MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
55084       if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
55085         pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
55086         if( pBt->mutex==0 ){
55087           rc = SQLITE_NOMEM;
55088           db->mallocFailed = 0;
55089           goto btree_open_out;
55090         }
55091       }
55092       sqlite3_mutex_enter(mutexShared);
55093       pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
55094       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
55095       sqlite3_mutex_leave(mutexShared);
55096     }
55097 #endif
55098   }
55099
55100 #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
55101   /* If the new Btree uses a sharable pBtShared, then link the new
55102   ** Btree into the list of all sharable Btrees for the same connection.
55103   ** The list is kept in ascending order by pBt address.
55104   */
55105   if( p->sharable ){
55106     int i;
55107     Btree *pSib;
55108     for(i=0; i<db->nDb; i++){
55109       if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
55110         while( pSib->pPrev ){ pSib = pSib->pPrev; }
55111         if( p->pBt<pSib->pBt ){
55112           p->pNext = pSib;
55113           p->pPrev = 0;
55114           pSib->pPrev = p;
55115         }else{
55116           while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
55117             pSib = pSib->pNext;
55118           }
55119           p->pNext = pSib->pNext;
55120           p->pPrev = pSib;
55121           if( p->pNext ){
55122             p->pNext->pPrev = p;
55123           }
55124           pSib->pNext = p;
55125         }
55126         break;
55127       }
55128     }
55129   }
55130 #endif
55131   *ppBtree = p;
55132
55133 btree_open_out:
55134   if( rc!=SQLITE_OK ){
55135     if( pBt && pBt->pPager ){
55136       sqlite3PagerClose(pBt->pPager);
55137     }
55138     sqlite3_free(pBt);
55139     sqlite3_free(p);
55140     *ppBtree = 0;
55141   }else{
55142     /* If the B-Tree was successfully opened, set the pager-cache size to the
55143     ** default value. Except, when opening on an existing shared pager-cache,
55144     ** do not change the pager-cache size.
55145     */
55146     if( sqlite3BtreeSchema(p, 0, 0)==0 ){
55147       sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
55148     }
55149   }
55150   if( mutexOpen ){
55151     assert( sqlite3_mutex_held(mutexOpen) );
55152     sqlite3_mutex_leave(mutexOpen);
55153   }
55154   return rc;
55155 }
55156
55157 /*
55158 ** Decrement the BtShared.nRef counter.  When it reaches zero,
55159 ** remove the BtShared structure from the sharing list.  Return
55160 ** true if the BtShared.nRef counter reaches zero and return
55161 ** false if it is still positive.
55162 */
55163 static int removeFromSharingList(BtShared *pBt){
55164 #ifndef SQLITE_OMIT_SHARED_CACHE
55165   MUTEX_LOGIC( sqlite3_mutex *pMaster; )
55166   BtShared *pList;
55167   int removed = 0;
55168
55169   assert( sqlite3_mutex_notheld(pBt->mutex) );
55170   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
55171   sqlite3_mutex_enter(pMaster);
55172   pBt->nRef--;
55173   if( pBt->nRef<=0 ){
55174     if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
55175       GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
55176     }else{
55177       pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
55178       while( ALWAYS(pList) && pList->pNext!=pBt ){
55179         pList=pList->pNext;
55180       }
55181       if( ALWAYS(pList) ){
55182         pList->pNext = pBt->pNext;
55183       }
55184     }
55185     if( SQLITE_THREADSAFE ){
55186       sqlite3_mutex_free(pBt->mutex);
55187     }
55188     removed = 1;
55189   }
55190   sqlite3_mutex_leave(pMaster);
55191   return removed;
55192 #else
55193   return 1;
55194 #endif
55195 }
55196
55197 /*
55198 ** Make sure pBt->pTmpSpace points to an allocation of 
55199 ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
55200 ** pointer.
55201 */
55202 static void allocateTempSpace(BtShared *pBt){
55203   if( !pBt->pTmpSpace ){
55204     pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
55205
55206     /* One of the uses of pBt->pTmpSpace is to format cells before
55207     ** inserting them into a leaf page (function fillInCell()). If
55208     ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
55209     ** by the various routines that manipulate binary cells. Which
55210     ** can mean that fillInCell() only initializes the first 2 or 3
55211     ** bytes of pTmpSpace, but that the first 4 bytes are copied from
55212     ** it into a database page. This is not actually a problem, but it
55213     ** does cause a valgrind error when the 1 or 2 bytes of unitialized 
55214     ** data is passed to system call write(). So to avoid this error,
55215     ** zero the first 4 bytes of temp space here.
55216     **
55217     ** Also:  Provide four bytes of initialized space before the
55218     ** beginning of pTmpSpace as an area available to prepend the
55219     ** left-child pointer to the beginning of a cell.
55220     */
55221     if( pBt->pTmpSpace ){
55222       memset(pBt->pTmpSpace, 0, 8);
55223       pBt->pTmpSpace += 4;
55224     }
55225   }
55226 }
55227
55228 /*
55229 ** Free the pBt->pTmpSpace allocation
55230 */
55231 static void freeTempSpace(BtShared *pBt){
55232   if( pBt->pTmpSpace ){
55233     pBt->pTmpSpace -= 4;
55234     sqlite3PageFree(pBt->pTmpSpace);
55235     pBt->pTmpSpace = 0;
55236   }
55237 }
55238
55239 /*
55240 ** Close an open database and invalidate all cursors.
55241 */
55242 SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
55243   BtShared *pBt = p->pBt;
55244   BtCursor *pCur;
55245
55246   /* Close all cursors opened via this handle.  */
55247   assert( sqlite3_mutex_held(p->db->mutex) );
55248   sqlite3BtreeEnter(p);
55249   pCur = pBt->pCursor;
55250   while( pCur ){
55251     BtCursor *pTmp = pCur;
55252     pCur = pCur->pNext;
55253     if( pTmp->pBtree==p ){
55254       sqlite3BtreeCloseCursor(pTmp);
55255     }
55256   }
55257
55258   /* Rollback any active transaction and free the handle structure.
55259   ** The call to sqlite3BtreeRollback() drops any table-locks held by
55260   ** this handle.
55261   */
55262   sqlite3BtreeRollback(p, SQLITE_OK, 0);
55263   sqlite3BtreeLeave(p);
55264
55265   /* If there are still other outstanding references to the shared-btree
55266   ** structure, return now. The remainder of this procedure cleans 
55267   ** up the shared-btree.
55268   */
55269   assert( p->wantToLock==0 && p->locked==0 );
55270   if( !p->sharable || removeFromSharingList(pBt) ){
55271     /* The pBt is no longer on the sharing list, so we can access
55272     ** it without having to hold the mutex.
55273     **
55274     ** Clean out and delete the BtShared object.
55275     */
55276     assert( !pBt->pCursor );
55277     sqlite3PagerClose(pBt->pPager);
55278     if( pBt->xFreeSchema && pBt->pSchema ){
55279       pBt->xFreeSchema(pBt->pSchema);
55280     }
55281     sqlite3DbFree(0, pBt->pSchema);
55282     freeTempSpace(pBt);
55283     sqlite3_free(pBt);
55284   }
55285
55286 #ifndef SQLITE_OMIT_SHARED_CACHE
55287   assert( p->wantToLock==0 );
55288   assert( p->locked==0 );
55289   if( p->pPrev ) p->pPrev->pNext = p->pNext;
55290   if( p->pNext ) p->pNext->pPrev = p->pPrev;
55291 #endif
55292
55293   sqlite3_free(p);
55294   return SQLITE_OK;
55295 }
55296
55297 /*
55298 ** Change the limit on the number of pages allowed in the cache.
55299 **
55300 ** The maximum number of cache pages is set to the absolute
55301 ** value of mxPage.  If mxPage is negative, the pager will
55302 ** operate asynchronously - it will not stop to do fsync()s
55303 ** to insure data is written to the disk surface before
55304 ** continuing.  Transactions still work if synchronous is off,
55305 ** and the database cannot be corrupted if this program
55306 ** crashes.  But if the operating system crashes or there is
55307 ** an abrupt power failure when synchronous is off, the database
55308 ** could be left in an inconsistent and unrecoverable state.
55309 ** Synchronous is on by default so database corruption is not
55310 ** normally a worry.
55311 */
55312 SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
55313   BtShared *pBt = p->pBt;
55314   assert( sqlite3_mutex_held(p->db->mutex) );
55315   sqlite3BtreeEnter(p);
55316   sqlite3PagerSetCachesize(pBt->pPager, mxPage);
55317   sqlite3BtreeLeave(p);
55318   return SQLITE_OK;
55319 }
55320
55321 #if SQLITE_MAX_MMAP_SIZE>0
55322 /*
55323 ** Change the limit on the amount of the database file that may be
55324 ** memory mapped.
55325 */
55326 SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
55327   BtShared *pBt = p->pBt;
55328   assert( sqlite3_mutex_held(p->db->mutex) );
55329   sqlite3BtreeEnter(p);
55330   sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
55331   sqlite3BtreeLeave(p);
55332   return SQLITE_OK;
55333 }
55334 #endif /* SQLITE_MAX_MMAP_SIZE>0 */
55335
55336 /*
55337 ** Change the way data is synced to disk in order to increase or decrease
55338 ** how well the database resists damage due to OS crashes and power
55339 ** failures.  Level 1 is the same as asynchronous (no syncs() occur and
55340 ** there is a high probability of damage)  Level 2 is the default.  There
55341 ** is a very low but non-zero probability of damage.  Level 3 reduces the
55342 ** probability of damage to near zero but with a write performance reduction.
55343 */
55344 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
55345 SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
55346   Btree *p,              /* The btree to set the safety level on */
55347   unsigned pgFlags       /* Various PAGER_* flags */
55348 ){
55349   BtShared *pBt = p->pBt;
55350   assert( sqlite3_mutex_held(p->db->mutex) );
55351   sqlite3BtreeEnter(p);
55352   sqlite3PagerSetFlags(pBt->pPager, pgFlags);
55353   sqlite3BtreeLeave(p);
55354   return SQLITE_OK;
55355 }
55356 #endif
55357
55358 /*
55359 ** Return TRUE if the given btree is set to safety level 1.  In other
55360 ** words, return TRUE if no sync() occurs on the disk files.
55361 */
55362 SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
55363   BtShared *pBt = p->pBt;
55364   int rc;
55365   assert( sqlite3_mutex_held(p->db->mutex) );  
55366   sqlite3BtreeEnter(p);
55367   assert( pBt && pBt->pPager );
55368   rc = sqlite3PagerNosync(pBt->pPager);
55369   sqlite3BtreeLeave(p);
55370   return rc;
55371 }
55372
55373 /*
55374 ** Change the default pages size and the number of reserved bytes per page.
55375 ** Or, if the page size has already been fixed, return SQLITE_READONLY 
55376 ** without changing anything.
55377 **
55378 ** The page size must be a power of 2 between 512 and 65536.  If the page
55379 ** size supplied does not meet this constraint then the page size is not
55380 ** changed.
55381 **
55382 ** Page sizes are constrained to be a power of two so that the region
55383 ** of the database file used for locking (beginning at PENDING_BYTE,
55384 ** the first byte past the 1GB boundary, 0x40000000) needs to occur
55385 ** at the beginning of a page.
55386 **
55387 ** If parameter nReserve is less than zero, then the number of reserved
55388 ** bytes per page is left unchanged.
55389 **
55390 ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
55391 ** and autovacuum mode can no longer be changed.
55392 */
55393 SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
55394   int rc = SQLITE_OK;
55395   BtShared *pBt = p->pBt;
55396   assert( nReserve>=-1 && nReserve<=255 );
55397   sqlite3BtreeEnter(p);
55398 #if SQLITE_HAS_CODEC
55399   if( nReserve>pBt->optimalReserve ) pBt->optimalReserve = (u8)nReserve;
55400 #endif
55401   if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
55402     sqlite3BtreeLeave(p);
55403     return SQLITE_READONLY;
55404   }
55405   if( nReserve<0 ){
55406     nReserve = pBt->pageSize - pBt->usableSize;
55407   }
55408   assert( nReserve>=0 && nReserve<=255 );
55409   if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
55410         ((pageSize-1)&pageSize)==0 ){
55411     assert( (pageSize & 7)==0 );
55412     assert( !pBt->pPage1 && !pBt->pCursor );
55413     pBt->pageSize = (u32)pageSize;
55414     freeTempSpace(pBt);
55415   }
55416   rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
55417   pBt->usableSize = pBt->pageSize - (u16)nReserve;
55418   if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
55419   sqlite3BtreeLeave(p);
55420   return rc;
55421 }
55422
55423 /*
55424 ** Return the currently defined page size
55425 */
55426 SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
55427   return p->pBt->pageSize;
55428 }
55429
55430 /*
55431 ** This function is similar to sqlite3BtreeGetReserve(), except that it
55432 ** may only be called if it is guaranteed that the b-tree mutex is already
55433 ** held.
55434 **
55435 ** This is useful in one special case in the backup API code where it is
55436 ** known that the shared b-tree mutex is held, but the mutex on the 
55437 ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
55438 ** were to be called, it might collide with some other operation on the
55439 ** database handle that owns *p, causing undefined behavior.
55440 */
55441 SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
55442   int n;
55443   assert( sqlite3_mutex_held(p->pBt->mutex) );
55444   n = p->pBt->pageSize - p->pBt->usableSize;
55445   return n;
55446 }
55447
55448 /*
55449 ** Return the number of bytes of space at the end of every page that
55450 ** are intentually left unused.  This is the "reserved" space that is
55451 ** sometimes used by extensions.
55452 **
55453 ** If SQLITE_HAS_MUTEX is defined then the number returned is the
55454 ** greater of the current reserved space and the maximum requested
55455 ** reserve space.
55456 */
55457 SQLITE_PRIVATE int sqlite3BtreeGetOptimalReserve(Btree *p){
55458   int n;
55459   sqlite3BtreeEnter(p);
55460   n = sqlite3BtreeGetReserveNoMutex(p);
55461 #ifdef SQLITE_HAS_CODEC
55462   if( n<p->pBt->optimalReserve ) n = p->pBt->optimalReserve;
55463 #endif
55464   sqlite3BtreeLeave(p);
55465   return n;
55466 }
55467
55468
55469 /*
55470 ** Set the maximum page count for a database if mxPage is positive.
55471 ** No changes are made if mxPage is 0 or negative.
55472 ** Regardless of the value of mxPage, return the maximum page count.
55473 */
55474 SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
55475   int n;
55476   sqlite3BtreeEnter(p);
55477   n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
55478   sqlite3BtreeLeave(p);
55479   return n;
55480 }
55481
55482 /*
55483 ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1.  If newFlag is -1,
55484 ** then make no changes.  Always return the value of the BTS_SECURE_DELETE
55485 ** setting after the change.
55486 */
55487 SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
55488   int b;
55489   if( p==0 ) return 0;
55490   sqlite3BtreeEnter(p);
55491   if( newFlag>=0 ){
55492     p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
55493     if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
55494   } 
55495   b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
55496   sqlite3BtreeLeave(p);
55497   return b;
55498 }
55499
55500 /*
55501 ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
55502 ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
55503 ** is disabled. The default value for the auto-vacuum property is 
55504 ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
55505 */
55506 SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
55507 #ifdef SQLITE_OMIT_AUTOVACUUM
55508   return SQLITE_READONLY;
55509 #else
55510   BtShared *pBt = p->pBt;
55511   int rc = SQLITE_OK;
55512   u8 av = (u8)autoVacuum;
55513
55514   sqlite3BtreeEnter(p);
55515   if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
55516     rc = SQLITE_READONLY;
55517   }else{
55518     pBt->autoVacuum = av ?1:0;
55519     pBt->incrVacuum = av==2 ?1:0;
55520   }
55521   sqlite3BtreeLeave(p);
55522   return rc;
55523 #endif
55524 }
55525
55526 /*
55527 ** Return the value of the 'auto-vacuum' property. If auto-vacuum is 
55528 ** enabled 1 is returned. Otherwise 0.
55529 */
55530 SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
55531 #ifdef SQLITE_OMIT_AUTOVACUUM
55532   return BTREE_AUTOVACUUM_NONE;
55533 #else
55534   int rc;
55535   sqlite3BtreeEnter(p);
55536   rc = (
55537     (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
55538     (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
55539     BTREE_AUTOVACUUM_INCR
55540   );
55541   sqlite3BtreeLeave(p);
55542   return rc;
55543 #endif
55544 }
55545
55546
55547 /*
55548 ** Get a reference to pPage1 of the database file.  This will
55549 ** also acquire a readlock on that file.
55550 **
55551 ** SQLITE_OK is returned on success.  If the file is not a
55552 ** well-formed database file, then SQLITE_CORRUPT is returned.
55553 ** SQLITE_BUSY is returned if the database is locked.  SQLITE_NOMEM
55554 ** is returned if we run out of memory. 
55555 */
55556 static int lockBtree(BtShared *pBt){
55557   int rc;              /* Result code from subfunctions */
55558   MemPage *pPage1;     /* Page 1 of the database file */
55559   int nPage;           /* Number of pages in the database */
55560   int nPageFile = 0;   /* Number of pages in the database file */
55561   int nPageHeader;     /* Number of pages in the database according to hdr */
55562
55563   assert( sqlite3_mutex_held(pBt->mutex) );
55564   assert( pBt->pPage1==0 );
55565   rc = sqlite3PagerSharedLock(pBt->pPager);
55566   if( rc!=SQLITE_OK ) return rc;
55567   rc = btreeGetPage(pBt, 1, &pPage1, 0);
55568   if( rc!=SQLITE_OK ) return rc;
55569
55570   /* Do some checking to help insure the file we opened really is
55571   ** a valid database file. 
55572   */
55573   nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
55574   sqlite3PagerPagecount(pBt->pPager, &nPageFile);
55575   if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
55576     nPage = nPageFile;
55577   }
55578   if( nPage>0 ){
55579     u32 pageSize;
55580     u32 usableSize;
55581     u8 *page1 = pPage1->aData;
55582     rc = SQLITE_NOTADB;
55583     /* EVIDENCE-OF: R-43737-39999 Every valid SQLite database file begins
55584     ** with the following 16 bytes (in hex): 53 51 4c 69 74 65 20 66 6f 72 6d
55585     ** 61 74 20 33 00. */
55586     if( memcmp(page1, zMagicHeader, 16)!=0 ){
55587       goto page1_init_failed;
55588     }
55589
55590 #ifdef SQLITE_OMIT_WAL
55591     if( page1[18]>1 ){
55592       pBt->btsFlags |= BTS_READ_ONLY;
55593     }
55594     if( page1[19]>1 ){
55595       goto page1_init_failed;
55596     }
55597 #else
55598     if( page1[18]>2 ){
55599       pBt->btsFlags |= BTS_READ_ONLY;
55600     }
55601     if( page1[19]>2 ){
55602       goto page1_init_failed;
55603     }
55604
55605     /* If the write version is set to 2, this database should be accessed
55606     ** in WAL mode. If the log is not already open, open it now. Then 
55607     ** return SQLITE_OK and return without populating BtShared.pPage1.
55608     ** The caller detects this and calls this function again. This is
55609     ** required as the version of page 1 currently in the page1 buffer
55610     ** may not be the latest version - there may be a newer one in the log
55611     ** file.
55612     */
55613     if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
55614       int isOpen = 0;
55615       rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
55616       if( rc!=SQLITE_OK ){
55617         goto page1_init_failed;
55618       }else if( isOpen==0 ){
55619         releasePage(pPage1);
55620         return SQLITE_OK;
55621       }
55622       rc = SQLITE_NOTADB;
55623     }
55624 #endif
55625
55626     /* EVIDENCE-OF: R-15465-20813 The maximum and minimum embedded payload
55627     ** fractions and the leaf payload fraction values must be 64, 32, and 32.
55628     **
55629     ** The original design allowed these amounts to vary, but as of
55630     ** version 3.6.0, we require them to be fixed.
55631     */
55632     if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
55633       goto page1_init_failed;
55634     }
55635     /* EVIDENCE-OF: R-51873-39618 The page size for a database file is
55636     ** determined by the 2-byte integer located at an offset of 16 bytes from
55637     ** the beginning of the database file. */
55638     pageSize = (page1[16]<<8) | (page1[17]<<16);
55639     /* EVIDENCE-OF: R-25008-21688 The size of a page is a power of two
55640     ** between 512 and 65536 inclusive. */
55641     if( ((pageSize-1)&pageSize)!=0
55642      || pageSize>SQLITE_MAX_PAGE_SIZE 
55643      || pageSize<=256 
55644     ){
55645       goto page1_init_failed;
55646     }
55647     assert( (pageSize & 7)==0 );
55648     /* EVIDENCE-OF: R-59310-51205 The "reserved space" size in the 1-byte
55649     ** integer at offset 20 is the number of bytes of space at the end of
55650     ** each page to reserve for extensions. 
55651     **
55652     ** EVIDENCE-OF: R-37497-42412 The size of the reserved region is
55653     ** determined by the one-byte unsigned integer found at an offset of 20
55654     ** into the database file header. */
55655     usableSize = pageSize - page1[20];
55656     if( (u32)pageSize!=pBt->pageSize ){
55657       /* After reading the first page of the database assuming a page size
55658       ** of BtShared.pageSize, we have discovered that the page-size is
55659       ** actually pageSize. Unlock the database, leave pBt->pPage1 at
55660       ** zero and return SQLITE_OK. The caller will call this function
55661       ** again with the correct page-size.
55662       */
55663       releasePage(pPage1);
55664       pBt->usableSize = usableSize;
55665       pBt->pageSize = pageSize;
55666       freeTempSpace(pBt);
55667       rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
55668                                    pageSize-usableSize);
55669       return rc;
55670     }
55671     if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
55672       rc = SQLITE_CORRUPT_BKPT;
55673       goto page1_init_failed;
55674     }
55675     /* EVIDENCE-OF: R-28312-64704 However, the usable size is not allowed to
55676     ** be less than 480. In other words, if the page size is 512, then the
55677     ** reserved space size cannot exceed 32. */
55678     if( usableSize<480 ){
55679       goto page1_init_failed;
55680     }
55681     pBt->pageSize = pageSize;
55682     pBt->usableSize = usableSize;
55683 #ifndef SQLITE_OMIT_AUTOVACUUM
55684     pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
55685     pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
55686 #endif
55687   }
55688
55689   /* maxLocal is the maximum amount of payload to store locally for
55690   ** a cell.  Make sure it is small enough so that at least minFanout
55691   ** cells can will fit on one page.  We assume a 10-byte page header.
55692   ** Besides the payload, the cell must store:
55693   **     2-byte pointer to the cell
55694   **     4-byte child pointer
55695   **     9-byte nKey value
55696   **     4-byte nData value
55697   **     4-byte overflow page pointer
55698   ** So a cell consists of a 2-byte pointer, a header which is as much as
55699   ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
55700   ** page pointer.
55701   */
55702   pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
55703   pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
55704   pBt->maxLeaf = (u16)(pBt->usableSize - 35);
55705   pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
55706   if( pBt->maxLocal>127 ){
55707     pBt->max1bytePayload = 127;
55708   }else{
55709     pBt->max1bytePayload = (u8)pBt->maxLocal;
55710   }
55711   assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
55712   pBt->pPage1 = pPage1;
55713   pBt->nPage = nPage;
55714   return SQLITE_OK;
55715
55716 page1_init_failed:
55717   releasePage(pPage1);
55718   pBt->pPage1 = 0;
55719   return rc;
55720 }
55721
55722 #ifndef NDEBUG
55723 /*
55724 ** Return the number of cursors open on pBt. This is for use
55725 ** in assert() expressions, so it is only compiled if NDEBUG is not
55726 ** defined.
55727 **
55728 ** Only write cursors are counted if wrOnly is true.  If wrOnly is
55729 ** false then all cursors are counted.
55730 **
55731 ** For the purposes of this routine, a cursor is any cursor that
55732 ** is capable of reading or writing to the database.  Cursors that
55733 ** have been tripped into the CURSOR_FAULT state are not counted.
55734 */
55735 static int countValidCursors(BtShared *pBt, int wrOnly){
55736   BtCursor *pCur;
55737   int r = 0;
55738   for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
55739     if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
55740      && pCur->eState!=CURSOR_FAULT ) r++; 
55741   }
55742   return r;
55743 }
55744 #endif
55745
55746 /*
55747 ** If there are no outstanding cursors and we are not in the middle
55748 ** of a transaction but there is a read lock on the database, then
55749 ** this routine unrefs the first page of the database file which 
55750 ** has the effect of releasing the read lock.
55751 **
55752 ** If there is a transaction in progress, this routine is a no-op.
55753 */
55754 static void unlockBtreeIfUnused(BtShared *pBt){
55755   assert( sqlite3_mutex_held(pBt->mutex) );
55756   assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
55757   if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
55758     MemPage *pPage1 = pBt->pPage1;
55759     assert( pPage1->aData );
55760     assert( sqlite3PagerRefcount(pBt->pPager)==1 );
55761     pBt->pPage1 = 0;
55762     releasePage(pPage1);
55763   }
55764 }
55765
55766 /*
55767 ** If pBt points to an empty file then convert that empty file
55768 ** into a new empty database by initializing the first page of
55769 ** the database.
55770 */
55771 static int newDatabase(BtShared *pBt){
55772   MemPage *pP1;
55773   unsigned char *data;
55774   int rc;
55775
55776   assert( sqlite3_mutex_held(pBt->mutex) );
55777   if( pBt->nPage>0 ){
55778     return SQLITE_OK;
55779   }
55780   pP1 = pBt->pPage1;
55781   assert( pP1!=0 );
55782   data = pP1->aData;
55783   rc = sqlite3PagerWrite(pP1->pDbPage);
55784   if( rc ) return rc;
55785   memcpy(data, zMagicHeader, sizeof(zMagicHeader));
55786   assert( sizeof(zMagicHeader)==16 );
55787   data[16] = (u8)((pBt->pageSize>>8)&0xff);
55788   data[17] = (u8)((pBt->pageSize>>16)&0xff);
55789   data[18] = 1;
55790   data[19] = 1;
55791   assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
55792   data[20] = (u8)(pBt->pageSize - pBt->usableSize);
55793   data[21] = 64;
55794   data[22] = 32;
55795   data[23] = 32;
55796   memset(&data[24], 0, 100-24);
55797   zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
55798   pBt->btsFlags |= BTS_PAGESIZE_FIXED;
55799 #ifndef SQLITE_OMIT_AUTOVACUUM
55800   assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
55801   assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
55802   put4byte(&data[36 + 4*4], pBt->autoVacuum);
55803   put4byte(&data[36 + 7*4], pBt->incrVacuum);
55804 #endif
55805   pBt->nPage = 1;
55806   data[31] = 1;
55807   return SQLITE_OK;
55808 }
55809
55810 /*
55811 ** Initialize the first page of the database file (creating a database
55812 ** consisting of a single page and no schema objects). Return SQLITE_OK
55813 ** if successful, or an SQLite error code otherwise.
55814 */
55815 SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
55816   int rc;
55817   sqlite3BtreeEnter(p);
55818   p->pBt->nPage = 0;
55819   rc = newDatabase(p->pBt);
55820   sqlite3BtreeLeave(p);
55821   return rc;
55822 }
55823
55824 /*
55825 ** Attempt to start a new transaction. A write-transaction
55826 ** is started if the second argument is nonzero, otherwise a read-
55827 ** transaction.  If the second argument is 2 or more and exclusive
55828 ** transaction is started, meaning that no other process is allowed
55829 ** to access the database.  A preexisting transaction may not be
55830 ** upgraded to exclusive by calling this routine a second time - the
55831 ** exclusivity flag only works for a new transaction.
55832 **
55833 ** A write-transaction must be started before attempting any 
55834 ** changes to the database.  None of the following routines 
55835 ** will work unless a transaction is started first:
55836 **
55837 **      sqlite3BtreeCreateTable()
55838 **      sqlite3BtreeCreateIndex()
55839 **      sqlite3BtreeClearTable()
55840 **      sqlite3BtreeDropTable()
55841 **      sqlite3BtreeInsert()
55842 **      sqlite3BtreeDelete()
55843 **      sqlite3BtreeUpdateMeta()
55844 **
55845 ** If an initial attempt to acquire the lock fails because of lock contention
55846 ** and the database was previously unlocked, then invoke the busy handler
55847 ** if there is one.  But if there was previously a read-lock, do not
55848 ** invoke the busy handler - just return SQLITE_BUSY.  SQLITE_BUSY is 
55849 ** returned when there is already a read-lock in order to avoid a deadlock.
55850 **
55851 ** Suppose there are two processes A and B.  A has a read lock and B has
55852 ** a reserved lock.  B tries to promote to exclusive but is blocked because
55853 ** of A's read lock.  A tries to promote to reserved but is blocked by B.
55854 ** One or the other of the two processes must give way or there can be
55855 ** no progress.  By returning SQLITE_BUSY and not invoking the busy callback
55856 ** when A already has a read lock, we encourage A to give up and let B
55857 ** proceed.
55858 */
55859 SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
55860   sqlite3 *pBlock = 0;
55861   BtShared *pBt = p->pBt;
55862   int rc = SQLITE_OK;
55863
55864   sqlite3BtreeEnter(p);
55865   btreeIntegrity(p);
55866
55867   /* If the btree is already in a write-transaction, or it
55868   ** is already in a read-transaction and a read-transaction
55869   ** is requested, this is a no-op.
55870   */
55871   if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
55872     goto trans_begun;
55873   }
55874   assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
55875
55876   /* Write transactions are not possible on a read-only database */
55877   if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
55878     rc = SQLITE_READONLY;
55879     goto trans_begun;
55880   }
55881
55882 #ifndef SQLITE_OMIT_SHARED_CACHE
55883   /* If another database handle has already opened a write transaction 
55884   ** on this shared-btree structure and a second write transaction is
55885   ** requested, return SQLITE_LOCKED.
55886   */
55887   if( (wrflag && pBt->inTransaction==TRANS_WRITE)
55888    || (pBt->btsFlags & BTS_PENDING)!=0
55889   ){
55890     pBlock = pBt->pWriter->db;
55891   }else if( wrflag>1 ){
55892     BtLock *pIter;
55893     for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
55894       if( pIter->pBtree!=p ){
55895         pBlock = pIter->pBtree->db;
55896         break;
55897       }
55898     }
55899   }
55900   if( pBlock ){
55901     sqlite3ConnectionBlocked(p->db, pBlock);
55902     rc = SQLITE_LOCKED_SHAREDCACHE;
55903     goto trans_begun;
55904   }
55905 #endif
55906
55907   /* Any read-only or read-write transaction implies a read-lock on 
55908   ** page 1. So if some other shared-cache client already has a write-lock 
55909   ** on page 1, the transaction cannot be opened. */
55910   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
55911   if( SQLITE_OK!=rc ) goto trans_begun;
55912
55913   pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
55914   if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
55915   do {
55916     /* Call lockBtree() until either pBt->pPage1 is populated or
55917     ** lockBtree() returns something other than SQLITE_OK. lockBtree()
55918     ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
55919     ** reading page 1 it discovers that the page-size of the database 
55920     ** file is not pBt->pageSize. In this case lockBtree() will update
55921     ** pBt->pageSize to the page-size of the file on disk.
55922     */
55923     while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
55924
55925     if( rc==SQLITE_OK && wrflag ){
55926       if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
55927         rc = SQLITE_READONLY;
55928       }else{
55929         rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
55930         if( rc==SQLITE_OK ){
55931           rc = newDatabase(pBt);
55932         }
55933       }
55934     }
55935   
55936     if( rc!=SQLITE_OK ){
55937       unlockBtreeIfUnused(pBt);
55938     }
55939   }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
55940           btreeInvokeBusyHandler(pBt) );
55941
55942   if( rc==SQLITE_OK ){
55943     if( p->inTrans==TRANS_NONE ){
55944       pBt->nTransaction++;
55945 #ifndef SQLITE_OMIT_SHARED_CACHE
55946       if( p->sharable ){
55947         assert( p->lock.pBtree==p && p->lock.iTable==1 );
55948         p->lock.eLock = READ_LOCK;
55949         p->lock.pNext = pBt->pLock;
55950         pBt->pLock = &p->lock;
55951       }
55952 #endif
55953     }
55954     p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
55955     if( p->inTrans>pBt->inTransaction ){
55956       pBt->inTransaction = p->inTrans;
55957     }
55958     if( wrflag ){
55959       MemPage *pPage1 = pBt->pPage1;
55960 #ifndef SQLITE_OMIT_SHARED_CACHE
55961       assert( !pBt->pWriter );
55962       pBt->pWriter = p;
55963       pBt->btsFlags &= ~BTS_EXCLUSIVE;
55964       if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
55965 #endif
55966
55967       /* If the db-size header field is incorrect (as it may be if an old
55968       ** client has been writing the database file), update it now. Doing
55969       ** this sooner rather than later means the database size can safely 
55970       ** re-read the database size from page 1 if a savepoint or transaction
55971       ** rollback occurs within the transaction.
55972       */
55973       if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
55974         rc = sqlite3PagerWrite(pPage1->pDbPage);
55975         if( rc==SQLITE_OK ){
55976           put4byte(&pPage1->aData[28], pBt->nPage);
55977         }
55978       }
55979     }
55980   }
55981
55982
55983 trans_begun:
55984   if( rc==SQLITE_OK && wrflag ){
55985     /* This call makes sure that the pager has the correct number of
55986     ** open savepoints. If the second parameter is greater than 0 and
55987     ** the sub-journal is not already open, then it will be opened here.
55988     */
55989     rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
55990   }
55991
55992   btreeIntegrity(p);
55993   sqlite3BtreeLeave(p);
55994   return rc;
55995 }
55996
55997 #ifndef SQLITE_OMIT_AUTOVACUUM
55998
55999 /*
56000 ** Set the pointer-map entries for all children of page pPage. Also, if
56001 ** pPage contains cells that point to overflow pages, set the pointer
56002 ** map entries for the overflow pages as well.
56003 */
56004 static int setChildPtrmaps(MemPage *pPage){
56005   int i;                             /* Counter variable */
56006   int nCell;                         /* Number of cells in page pPage */
56007   int rc;                            /* Return code */
56008   BtShared *pBt = pPage->pBt;
56009   u8 isInitOrig = pPage->isInit;
56010   Pgno pgno = pPage->pgno;
56011
56012   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56013   rc = btreeInitPage(pPage);
56014   if( rc!=SQLITE_OK ){
56015     goto set_child_ptrmaps_out;
56016   }
56017   nCell = pPage->nCell;
56018
56019   for(i=0; i<nCell; i++){
56020     u8 *pCell = findCell(pPage, i);
56021
56022     ptrmapPutOvflPtr(pPage, pCell, &rc);
56023
56024     if( !pPage->leaf ){
56025       Pgno childPgno = get4byte(pCell);
56026       ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
56027     }
56028   }
56029
56030   if( !pPage->leaf ){
56031     Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
56032     ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
56033   }
56034
56035 set_child_ptrmaps_out:
56036   pPage->isInit = isInitOrig;
56037   return rc;
56038 }
56039
56040 /*
56041 ** Somewhere on pPage is a pointer to page iFrom.  Modify this pointer so
56042 ** that it points to iTo. Parameter eType describes the type of pointer to
56043 ** be modified, as  follows:
56044 **
56045 ** PTRMAP_BTREE:     pPage is a btree-page. The pointer points at a child 
56046 **                   page of pPage.
56047 **
56048 ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
56049 **                   page pointed to by one of the cells on pPage.
56050 **
56051 ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
56052 **                   overflow page in the list.
56053 */
56054 static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
56055   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
56056   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
56057   if( eType==PTRMAP_OVERFLOW2 ){
56058     /* The pointer is always the first 4 bytes of the page in this case.  */
56059     if( get4byte(pPage->aData)!=iFrom ){
56060       return SQLITE_CORRUPT_BKPT;
56061     }
56062     put4byte(pPage->aData, iTo);
56063   }else{
56064     u8 isInitOrig = pPage->isInit;
56065     int i;
56066     int nCell;
56067
56068     btreeInitPage(pPage);
56069     nCell = pPage->nCell;
56070
56071     for(i=0; i<nCell; i++){
56072       u8 *pCell = findCell(pPage, i);
56073       if( eType==PTRMAP_OVERFLOW1 ){
56074         CellInfo info;
56075         btreeParseCellPtr(pPage, pCell, &info);
56076         if( info.iOverflow
56077          && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
56078          && iFrom==get4byte(&pCell[info.iOverflow])
56079         ){
56080           put4byte(&pCell[info.iOverflow], iTo);
56081           break;
56082         }
56083       }else{
56084         if( get4byte(pCell)==iFrom ){
56085           put4byte(pCell, iTo);
56086           break;
56087         }
56088       }
56089     }
56090   
56091     if( i==nCell ){
56092       if( eType!=PTRMAP_BTREE || 
56093           get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
56094         return SQLITE_CORRUPT_BKPT;
56095       }
56096       put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
56097     }
56098
56099     pPage->isInit = isInitOrig;
56100   }
56101   return SQLITE_OK;
56102 }
56103
56104
56105 /*
56106 ** Move the open database page pDbPage to location iFreePage in the 
56107 ** database. The pDbPage reference remains valid.
56108 **
56109 ** The isCommit flag indicates that there is no need to remember that
56110 ** the journal needs to be sync()ed before database page pDbPage->pgno 
56111 ** can be written to. The caller has already promised not to write to that
56112 ** page.
56113 */
56114 static int relocatePage(
56115   BtShared *pBt,           /* Btree */
56116   MemPage *pDbPage,        /* Open page to move */
56117   u8 eType,                /* Pointer map 'type' entry for pDbPage */
56118   Pgno iPtrPage,           /* Pointer map 'page-no' entry for pDbPage */
56119   Pgno iFreePage,          /* The location to move pDbPage to */
56120   int isCommit             /* isCommit flag passed to sqlite3PagerMovepage */
56121 ){
56122   MemPage *pPtrPage;   /* The page that contains a pointer to pDbPage */
56123   Pgno iDbPage = pDbPage->pgno;
56124   Pager *pPager = pBt->pPager;
56125   int rc;
56126
56127   assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 || 
56128       eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
56129   assert( sqlite3_mutex_held(pBt->mutex) );
56130   assert( pDbPage->pBt==pBt );
56131
56132   /* Move page iDbPage from its current location to page number iFreePage */
56133   TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n", 
56134       iDbPage, iFreePage, iPtrPage, eType));
56135   rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
56136   if( rc!=SQLITE_OK ){
56137     return rc;
56138   }
56139   pDbPage->pgno = iFreePage;
56140
56141   /* If pDbPage was a btree-page, then it may have child pages and/or cells
56142   ** that point to overflow pages. The pointer map entries for all these
56143   ** pages need to be changed.
56144   **
56145   ** If pDbPage is an overflow page, then the first 4 bytes may store a
56146   ** pointer to a subsequent overflow page. If this is the case, then
56147   ** the pointer map needs to be updated for the subsequent overflow page.
56148   */
56149   if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
56150     rc = setChildPtrmaps(pDbPage);
56151     if( rc!=SQLITE_OK ){
56152       return rc;
56153     }
56154   }else{
56155     Pgno nextOvfl = get4byte(pDbPage->aData);
56156     if( nextOvfl!=0 ){
56157       ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
56158       if( rc!=SQLITE_OK ){
56159         return rc;
56160       }
56161     }
56162   }
56163
56164   /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
56165   ** that it points at iFreePage. Also fix the pointer map entry for
56166   ** iPtrPage.
56167   */
56168   if( eType!=PTRMAP_ROOTPAGE ){
56169     rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
56170     if( rc!=SQLITE_OK ){
56171       return rc;
56172     }
56173     rc = sqlite3PagerWrite(pPtrPage->pDbPage);
56174     if( rc!=SQLITE_OK ){
56175       releasePage(pPtrPage);
56176       return rc;
56177     }
56178     rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
56179     releasePage(pPtrPage);
56180     if( rc==SQLITE_OK ){
56181       ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
56182     }
56183   }
56184   return rc;
56185 }
56186
56187 /* Forward declaration required by incrVacuumStep(). */
56188 static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
56189
56190 /*
56191 ** Perform a single step of an incremental-vacuum. If successful, return
56192 ** SQLITE_OK. If there is no work to do (and therefore no point in 
56193 ** calling this function again), return SQLITE_DONE. Or, if an error 
56194 ** occurs, return some other error code.
56195 **
56196 ** More specifically, this function attempts to re-organize the database so 
56197 ** that the last page of the file currently in use is no longer in use.
56198 **
56199 ** Parameter nFin is the number of pages that this database would contain
56200 ** were this function called until it returns SQLITE_DONE.
56201 **
56202 ** If the bCommit parameter is non-zero, this function assumes that the 
56203 ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE 
56204 ** or an error. bCommit is passed true for an auto-vacuum-on-commit 
56205 ** operation, or false for an incremental vacuum.
56206 */
56207 static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
56208   Pgno nFreeList;           /* Number of pages still on the free-list */
56209   int rc;
56210
56211   assert( sqlite3_mutex_held(pBt->mutex) );
56212   assert( iLastPg>nFin );
56213
56214   if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
56215     u8 eType;
56216     Pgno iPtrPage;
56217
56218     nFreeList = get4byte(&pBt->pPage1->aData[36]);
56219     if( nFreeList==0 ){
56220       return SQLITE_DONE;
56221     }
56222
56223     rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
56224     if( rc!=SQLITE_OK ){
56225       return rc;
56226     }
56227     if( eType==PTRMAP_ROOTPAGE ){
56228       return SQLITE_CORRUPT_BKPT;
56229     }
56230
56231     if( eType==PTRMAP_FREEPAGE ){
56232       if( bCommit==0 ){
56233         /* Remove the page from the files free-list. This is not required
56234         ** if bCommit is non-zero. In that case, the free-list will be
56235         ** truncated to zero after this function returns, so it doesn't 
56236         ** matter if it still contains some garbage entries.
56237         */
56238         Pgno iFreePg;
56239         MemPage *pFreePg;
56240         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
56241         if( rc!=SQLITE_OK ){
56242           return rc;
56243         }
56244         assert( iFreePg==iLastPg );
56245         releasePage(pFreePg);
56246       }
56247     } else {
56248       Pgno iFreePg;             /* Index of free page to move pLastPg to */
56249       MemPage *pLastPg;
56250       u8 eMode = BTALLOC_ANY;   /* Mode parameter for allocateBtreePage() */
56251       Pgno iNear = 0;           /* nearby parameter for allocateBtreePage() */
56252
56253       rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
56254       if( rc!=SQLITE_OK ){
56255         return rc;
56256       }
56257
56258       /* If bCommit is zero, this loop runs exactly once and page pLastPg
56259       ** is swapped with the first free page pulled off the free list.
56260       **
56261       ** On the other hand, if bCommit is greater than zero, then keep
56262       ** looping until a free-page located within the first nFin pages
56263       ** of the file is found.
56264       */
56265       if( bCommit==0 ){
56266         eMode = BTALLOC_LE;
56267         iNear = nFin;
56268       }
56269       do {
56270         MemPage *pFreePg;
56271         rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
56272         if( rc!=SQLITE_OK ){
56273           releasePage(pLastPg);
56274           return rc;
56275         }
56276         releasePage(pFreePg);
56277       }while( bCommit && iFreePg>nFin );
56278       assert( iFreePg<iLastPg );
56279       
56280       rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
56281       releasePage(pLastPg);
56282       if( rc!=SQLITE_OK ){
56283         return rc;
56284       }
56285     }
56286   }
56287
56288   if( bCommit==0 ){
56289     do {
56290       iLastPg--;
56291     }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
56292     pBt->bDoTruncate = 1;
56293     pBt->nPage = iLastPg;
56294   }
56295   return SQLITE_OK;
56296 }
56297
56298 /*
56299 ** The database opened by the first argument is an auto-vacuum database
56300 ** nOrig pages in size containing nFree free pages. Return the expected 
56301 ** size of the database in pages following an auto-vacuum operation.
56302 */
56303 static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
56304   int nEntry;                     /* Number of entries on one ptrmap page */
56305   Pgno nPtrmap;                   /* Number of PtrMap pages to be freed */
56306   Pgno nFin;                      /* Return value */
56307
56308   nEntry = pBt->usableSize/5;
56309   nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
56310   nFin = nOrig - nFree - nPtrmap;
56311   if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
56312     nFin--;
56313   }
56314   while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
56315     nFin--;
56316   }
56317
56318   return nFin;
56319 }
56320
56321 /*
56322 ** A write-transaction must be opened before calling this function.
56323 ** It performs a single unit of work towards an incremental vacuum.
56324 **
56325 ** If the incremental vacuum is finished after this function has run,
56326 ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
56327 ** SQLITE_OK is returned. Otherwise an SQLite error code. 
56328 */
56329 SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
56330   int rc;
56331   BtShared *pBt = p->pBt;
56332
56333   sqlite3BtreeEnter(p);
56334   assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
56335   if( !pBt->autoVacuum ){
56336     rc = SQLITE_DONE;
56337   }else{
56338     Pgno nOrig = btreePagecount(pBt);
56339     Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
56340     Pgno nFin = finalDbSize(pBt, nOrig, nFree);
56341
56342     if( nOrig<nFin ){
56343       rc = SQLITE_CORRUPT_BKPT;
56344     }else if( nFree>0 ){
56345       rc = saveAllCursors(pBt, 0, 0);
56346       if( rc==SQLITE_OK ){
56347         invalidateAllOverflowCache(pBt);
56348         rc = incrVacuumStep(pBt, nFin, nOrig, 0);
56349       }
56350       if( rc==SQLITE_OK ){
56351         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
56352         put4byte(&pBt->pPage1->aData[28], pBt->nPage);
56353       }
56354     }else{
56355       rc = SQLITE_DONE;
56356     }
56357   }
56358   sqlite3BtreeLeave(p);
56359   return rc;
56360 }
56361
56362 /*
56363 ** This routine is called prior to sqlite3PagerCommit when a transaction
56364 ** is committed for an auto-vacuum database.
56365 **
56366 ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
56367 ** the database file should be truncated to during the commit process. 
56368 ** i.e. the database has been reorganized so that only the first *pnTrunc
56369 ** pages are in use.
56370 */
56371 static int autoVacuumCommit(BtShared *pBt){
56372   int rc = SQLITE_OK;
56373   Pager *pPager = pBt->pPager;
56374   VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
56375
56376   assert( sqlite3_mutex_held(pBt->mutex) );
56377   invalidateAllOverflowCache(pBt);
56378   assert(pBt->autoVacuum);
56379   if( !pBt->incrVacuum ){
56380     Pgno nFin;         /* Number of pages in database after autovacuuming */
56381     Pgno nFree;        /* Number of pages on the freelist initially */
56382     Pgno iFree;        /* The next page to be freed */
56383     Pgno nOrig;        /* Database size before freeing */
56384
56385     nOrig = btreePagecount(pBt);
56386     if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
56387       /* It is not possible to create a database for which the final page
56388       ** is either a pointer-map page or the pending-byte page. If one
56389       ** is encountered, this indicates corruption.
56390       */
56391       return SQLITE_CORRUPT_BKPT;
56392     }
56393
56394     nFree = get4byte(&pBt->pPage1->aData[36]);
56395     nFin = finalDbSize(pBt, nOrig, nFree);
56396     if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
56397     if( nFin<nOrig ){
56398       rc = saveAllCursors(pBt, 0, 0);
56399     }
56400     for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
56401       rc = incrVacuumStep(pBt, nFin, iFree, 1);
56402     }
56403     if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
56404       rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
56405       put4byte(&pBt->pPage1->aData[32], 0);
56406       put4byte(&pBt->pPage1->aData[36], 0);
56407       put4byte(&pBt->pPage1->aData[28], nFin);
56408       pBt->bDoTruncate = 1;
56409       pBt->nPage = nFin;
56410     }
56411     if( rc!=SQLITE_OK ){
56412       sqlite3PagerRollback(pPager);
56413     }
56414   }
56415
56416   assert( nRef>=sqlite3PagerRefcount(pPager) );
56417   return rc;
56418 }
56419
56420 #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
56421 # define setChildPtrmaps(x) SQLITE_OK
56422 #endif
56423
56424 /*
56425 ** This routine does the first phase of a two-phase commit.  This routine
56426 ** causes a rollback journal to be created (if it does not already exist)
56427 ** and populated with enough information so that if a power loss occurs
56428 ** the database can be restored to its original state by playing back
56429 ** the journal.  Then the contents of the journal are flushed out to
56430 ** the disk.  After the journal is safely on oxide, the changes to the
56431 ** database are written into the database file and flushed to oxide.
56432 ** At the end of this call, the rollback journal still exists on the
56433 ** disk and we are still holding all locks, so the transaction has not
56434 ** committed.  See sqlite3BtreeCommitPhaseTwo() for the second phase of the
56435 ** commit process.
56436 **
56437 ** This call is a no-op if no write-transaction is currently active on pBt.
56438 **
56439 ** Otherwise, sync the database file for the btree pBt. zMaster points to
56440 ** the name of a master journal file that should be written into the
56441 ** individual journal file, or is NULL, indicating no master journal file 
56442 ** (single database transaction).
56443 **
56444 ** When this is called, the master journal should already have been
56445 ** created, populated with this journal pointer and synced to disk.
56446 **
56447 ** Once this is routine has returned, the only thing required to commit
56448 ** the write-transaction for this database file is to delete the journal.
56449 */
56450 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
56451   int rc = SQLITE_OK;
56452   if( p->inTrans==TRANS_WRITE ){
56453     BtShared *pBt = p->pBt;
56454     sqlite3BtreeEnter(p);
56455 #ifndef SQLITE_OMIT_AUTOVACUUM
56456     if( pBt->autoVacuum ){
56457       rc = autoVacuumCommit(pBt);
56458       if( rc!=SQLITE_OK ){
56459         sqlite3BtreeLeave(p);
56460         return rc;
56461       }
56462     }
56463     if( pBt->bDoTruncate ){
56464       sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
56465     }
56466 #endif
56467     rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
56468     sqlite3BtreeLeave(p);
56469   }
56470   return rc;
56471 }
56472
56473 /*
56474 ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
56475 ** at the conclusion of a transaction.
56476 */
56477 static void btreeEndTransaction(Btree *p){
56478   BtShared *pBt = p->pBt;
56479   sqlite3 *db = p->db;
56480   assert( sqlite3BtreeHoldsMutex(p) );
56481
56482 #ifndef SQLITE_OMIT_AUTOVACUUM
56483   pBt->bDoTruncate = 0;
56484 #endif
56485   if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
56486     /* If there are other active statements that belong to this database
56487     ** handle, downgrade to a read-only transaction. The other statements
56488     ** may still be reading from the database.  */
56489     downgradeAllSharedCacheTableLocks(p);
56490     p->inTrans = TRANS_READ;
56491   }else{
56492     /* If the handle had any kind of transaction open, decrement the 
56493     ** transaction count of the shared btree. If the transaction count 
56494     ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
56495     ** call below will unlock the pager.  */
56496     if( p->inTrans!=TRANS_NONE ){
56497       clearAllSharedCacheTableLocks(p);
56498       pBt->nTransaction--;
56499       if( 0==pBt->nTransaction ){
56500         pBt->inTransaction = TRANS_NONE;
56501       }
56502     }
56503
56504     /* Set the current transaction state to TRANS_NONE and unlock the 
56505     ** pager if this call closed the only read or write transaction.  */
56506     p->inTrans = TRANS_NONE;
56507     unlockBtreeIfUnused(pBt);
56508   }
56509
56510   btreeIntegrity(p);
56511 }
56512
56513 /*
56514 ** Commit the transaction currently in progress.
56515 **
56516 ** This routine implements the second phase of a 2-phase commit.  The
56517 ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
56518 ** be invoked prior to calling this routine.  The sqlite3BtreeCommitPhaseOne()
56519 ** routine did all the work of writing information out to disk and flushing the
56520 ** contents so that they are written onto the disk platter.  All this
56521 ** routine has to do is delete or truncate or zero the header in the
56522 ** the rollback journal (which causes the transaction to commit) and
56523 ** drop locks.
56524 **
56525 ** Normally, if an error occurs while the pager layer is attempting to 
56526 ** finalize the underlying journal file, this function returns an error and
56527 ** the upper layer will attempt a rollback. However, if the second argument
56528 ** is non-zero then this b-tree transaction is part of a multi-file 
56529 ** transaction. In this case, the transaction has already been committed 
56530 ** (by deleting a master journal file) and the caller will ignore this 
56531 ** functions return code. So, even if an error occurs in the pager layer,
56532 ** reset the b-tree objects internal state to indicate that the write
56533 ** transaction has been closed. This is quite safe, as the pager will have
56534 ** transitioned to the error state.
56535 **
56536 ** This will release the write lock on the database file.  If there
56537 ** are no active cursors, it also releases the read lock.
56538 */
56539 SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
56540
56541   if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
56542   sqlite3BtreeEnter(p);
56543   btreeIntegrity(p);
56544
56545   /* If the handle has a write-transaction open, commit the shared-btrees 
56546   ** transaction and set the shared state to TRANS_READ.
56547   */
56548   if( p->inTrans==TRANS_WRITE ){
56549     int rc;
56550     BtShared *pBt = p->pBt;
56551     assert( pBt->inTransaction==TRANS_WRITE );
56552     assert( pBt->nTransaction>0 );
56553     rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
56554     if( rc!=SQLITE_OK && bCleanup==0 ){
56555       sqlite3BtreeLeave(p);
56556       return rc;
56557     }
56558     p->iDataVersion--;  /* Compensate for pPager->iDataVersion++; */
56559     pBt->inTransaction = TRANS_READ;
56560     btreeClearHasContent(pBt);
56561   }
56562
56563   btreeEndTransaction(p);
56564   sqlite3BtreeLeave(p);
56565   return SQLITE_OK;
56566 }
56567
56568 /*
56569 ** Do both phases of a commit.
56570 */
56571 SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
56572   int rc;
56573   sqlite3BtreeEnter(p);
56574   rc = sqlite3BtreeCommitPhaseOne(p, 0);
56575   if( rc==SQLITE_OK ){
56576     rc = sqlite3BtreeCommitPhaseTwo(p, 0);
56577   }
56578   sqlite3BtreeLeave(p);
56579   return rc;
56580 }
56581
56582 /*
56583 ** This routine sets the state to CURSOR_FAULT and the error
56584 ** code to errCode for every cursor on any BtShared that pBtree
56585 ** references.  Or if the writeOnly flag is set to 1, then only
56586 ** trip write cursors and leave read cursors unchanged.
56587 **
56588 ** Every cursor is a candidate to be tripped, including cursors
56589 ** that belong to other database connections that happen to be
56590 ** sharing the cache with pBtree.
56591 **
56592 ** This routine gets called when a rollback occurs. If the writeOnly
56593 ** flag is true, then only write-cursors need be tripped - read-only
56594 ** cursors save their current positions so that they may continue 
56595 ** following the rollback. Or, if writeOnly is false, all cursors are 
56596 ** tripped. In general, writeOnly is false if the transaction being
56597 ** rolled back modified the database schema. In this case b-tree root
56598 ** pages may be moved or deleted from the database altogether, making
56599 ** it unsafe for read cursors to continue.
56600 **
56601 ** If the writeOnly flag is true and an error is encountered while 
56602 ** saving the current position of a read-only cursor, all cursors, 
56603 ** including all read-cursors are tripped.
56604 **
56605 ** SQLITE_OK is returned if successful, or if an error occurs while
56606 ** saving a cursor position, an SQLite error code.
56607 */
56608 SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
56609   BtCursor *p;
56610   int rc = SQLITE_OK;
56611
56612   assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
56613   if( pBtree ){
56614     sqlite3BtreeEnter(pBtree);
56615     for(p=pBtree->pBt->pCursor; p; p=p->pNext){
56616       int i;
56617       if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
56618         if( p->eState==CURSOR_VALID || p->eState==CURSOR_SKIPNEXT ){
56619           rc = saveCursorPosition(p);
56620           if( rc!=SQLITE_OK ){
56621             (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
56622             break;
56623           }
56624         }
56625       }else{
56626         sqlite3BtreeClearCursor(p);
56627         p->eState = CURSOR_FAULT;
56628         p->skipNext = errCode;
56629       }
56630       for(i=0; i<=p->iPage; i++){
56631         releasePage(p->apPage[i]);
56632         p->apPage[i] = 0;
56633       }
56634     }
56635     sqlite3BtreeLeave(pBtree);
56636   }
56637   return rc;
56638 }
56639
56640 /*
56641 ** Rollback the transaction in progress.
56642 **
56643 ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
56644 ** Only write cursors are tripped if writeOnly is true but all cursors are
56645 ** tripped if writeOnly is false.  Any attempt to use
56646 ** a tripped cursor will result in an error.
56647 **
56648 ** This will release the write lock on the database file.  If there
56649 ** are no active cursors, it also releases the read lock.
56650 */
56651 SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
56652   int rc;
56653   BtShared *pBt = p->pBt;
56654   MemPage *pPage1;
56655
56656   assert( writeOnly==1 || writeOnly==0 );
56657   assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
56658   sqlite3BtreeEnter(p);
56659   if( tripCode==SQLITE_OK ){
56660     rc = tripCode = saveAllCursors(pBt, 0, 0);
56661     if( rc ) writeOnly = 0;
56662   }else{
56663     rc = SQLITE_OK;
56664   }
56665   if( tripCode ){
56666     int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
56667     assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
56668     if( rc2!=SQLITE_OK ) rc = rc2;
56669   }
56670   btreeIntegrity(p);
56671
56672   if( p->inTrans==TRANS_WRITE ){
56673     int rc2;
56674
56675     assert( TRANS_WRITE==pBt->inTransaction );
56676     rc2 = sqlite3PagerRollback(pBt->pPager);
56677     if( rc2!=SQLITE_OK ){
56678       rc = rc2;
56679     }
56680
56681     /* The rollback may have destroyed the pPage1->aData value.  So
56682     ** call btreeGetPage() on page 1 again to make
56683     ** sure pPage1->aData is set correctly. */
56684     if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
56685       int nPage = get4byte(28+(u8*)pPage1->aData);
56686       testcase( nPage==0 );
56687       if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
56688       testcase( pBt->nPage!=nPage );
56689       pBt->nPage = nPage;
56690       releasePage(pPage1);
56691     }
56692     assert( countValidCursors(pBt, 1)==0 );
56693     pBt->inTransaction = TRANS_READ;
56694     btreeClearHasContent(pBt);
56695   }
56696
56697   btreeEndTransaction(p);
56698   sqlite3BtreeLeave(p);
56699   return rc;
56700 }
56701
56702 /*
56703 ** Start a statement subtransaction. The subtransaction can be rolled
56704 ** back independently of the main transaction. You must start a transaction 
56705 ** before starting a subtransaction. The subtransaction is ended automatically 
56706 ** if the main transaction commits or rolls back.
56707 **
56708 ** Statement subtransactions are used around individual SQL statements
56709 ** that are contained within a BEGIN...COMMIT block.  If a constraint
56710 ** error occurs within the statement, the effect of that one statement
56711 ** can be rolled back without having to rollback the entire transaction.
56712 **
56713 ** A statement sub-transaction is implemented as an anonymous savepoint. The
56714 ** value passed as the second parameter is the total number of savepoints,
56715 ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
56716 ** are no active savepoints and no other statement-transactions open,
56717 ** iStatement is 1. This anonymous savepoint can be released or rolled back
56718 ** using the sqlite3BtreeSavepoint() function.
56719 */
56720 SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
56721   int rc;
56722   BtShared *pBt = p->pBt;
56723   sqlite3BtreeEnter(p);
56724   assert( p->inTrans==TRANS_WRITE );
56725   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
56726   assert( iStatement>0 );
56727   assert( iStatement>p->db->nSavepoint );
56728   assert( pBt->inTransaction==TRANS_WRITE );
56729   /* At the pager level, a statement transaction is a savepoint with
56730   ** an index greater than all savepoints created explicitly using
56731   ** SQL statements. It is illegal to open, release or rollback any
56732   ** such savepoints while the statement transaction savepoint is active.
56733   */
56734   rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
56735   sqlite3BtreeLeave(p);
56736   return rc;
56737 }
56738
56739 /*
56740 ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
56741 ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
56742 ** savepoint identified by parameter iSavepoint, depending on the value 
56743 ** of op.
56744 **
56745 ** Normally, iSavepoint is greater than or equal to zero. However, if op is
56746 ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the 
56747 ** contents of the entire transaction are rolled back. This is different
56748 ** from a normal transaction rollback, as no locks are released and the
56749 ** transaction remains open.
56750 */
56751 SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
56752   int rc = SQLITE_OK;
56753   if( p && p->inTrans==TRANS_WRITE ){
56754     BtShared *pBt = p->pBt;
56755     assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
56756     assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
56757     sqlite3BtreeEnter(p);
56758     rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
56759     if( rc==SQLITE_OK ){
56760       if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
56761         pBt->nPage = 0;
56762       }
56763       rc = newDatabase(pBt);
56764       pBt->nPage = get4byte(28 + pBt->pPage1->aData);
56765
56766       /* The database size was written into the offset 28 of the header
56767       ** when the transaction started, so we know that the value at offset
56768       ** 28 is nonzero. */
56769       assert( pBt->nPage>0 );
56770     }
56771     sqlite3BtreeLeave(p);
56772   }
56773   return rc;
56774 }
56775
56776 /*
56777 ** Create a new cursor for the BTree whose root is on the page
56778 ** iTable. If a read-only cursor is requested, it is assumed that
56779 ** the caller already has at least a read-only transaction open
56780 ** on the database already. If a write-cursor is requested, then
56781 ** the caller is assumed to have an open write transaction.
56782 **
56783 ** If wrFlag==0, then the cursor can only be used for reading.
56784 ** If wrFlag==1, then the cursor can be used for reading or for
56785 ** writing if other conditions for writing are also met.  These
56786 ** are the conditions that must be met in order for writing to
56787 ** be allowed:
56788 **
56789 ** 1:  The cursor must have been opened with wrFlag==1
56790 **
56791 ** 2:  Other database connections that share the same pager cache
56792 **     but which are not in the READ_UNCOMMITTED state may not have
56793 **     cursors open with wrFlag==0 on the same table.  Otherwise
56794 **     the changes made by this write cursor would be visible to
56795 **     the read cursors in the other database connection.
56796 **
56797 ** 3:  The database must be writable (not on read-only media)
56798 **
56799 ** 4:  There must be an active transaction.
56800 **
56801 ** No checking is done to make sure that page iTable really is the
56802 ** root page of a b-tree.  If it is not, then the cursor acquired
56803 ** will not work correctly.
56804 **
56805 ** It is assumed that the sqlite3BtreeCursorZero() has been called
56806 ** on pCur to initialize the memory space prior to invoking this routine.
56807 */
56808 static int btreeCursor(
56809   Btree *p,                              /* The btree */
56810   int iTable,                            /* Root page of table to open */
56811   int wrFlag,                            /* 1 to write. 0 read-only */
56812   struct KeyInfo *pKeyInfo,              /* First arg to comparison function */
56813   BtCursor *pCur                         /* Space for new cursor */
56814 ){
56815   BtShared *pBt = p->pBt;                /* Shared b-tree handle */
56816
56817   assert( sqlite3BtreeHoldsMutex(p) );
56818   assert( wrFlag==0 || wrFlag==1 );
56819
56820   /* The following assert statements verify that if this is a sharable 
56821   ** b-tree database, the connection is holding the required table locks, 
56822   ** and that no other connection has any open cursor that conflicts with 
56823   ** this lock.  */
56824   assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
56825   assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
56826
56827   /* Assert that the caller has opened the required transaction. */
56828   assert( p->inTrans>TRANS_NONE );
56829   assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
56830   assert( pBt->pPage1 && pBt->pPage1->aData );
56831
56832   if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
56833     return SQLITE_READONLY;
56834   }
56835   if( wrFlag ){
56836     allocateTempSpace(pBt);
56837     if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM;
56838   }
56839   if( iTable==1 && btreePagecount(pBt)==0 ){
56840     assert( wrFlag==0 );
56841     iTable = 0;
56842   }
56843
56844   /* Now that no other errors can occur, finish filling in the BtCursor
56845   ** variables and link the cursor into the BtShared list.  */
56846   pCur->pgnoRoot = (Pgno)iTable;
56847   pCur->iPage = -1;
56848   pCur->pKeyInfo = pKeyInfo;
56849   pCur->pBtree = p;
56850   pCur->pBt = pBt;
56851   assert( wrFlag==0 || wrFlag==BTCF_WriteFlag );
56852   pCur->curFlags = wrFlag;
56853   pCur->pNext = pBt->pCursor;
56854   if( pCur->pNext ){
56855     pCur->pNext->pPrev = pCur;
56856   }
56857   pBt->pCursor = pCur;
56858   pCur->eState = CURSOR_INVALID;
56859   return SQLITE_OK;
56860 }
56861 SQLITE_PRIVATE int sqlite3BtreeCursor(
56862   Btree *p,                                   /* The btree */
56863   int iTable,                                 /* Root page of table to open */
56864   int wrFlag,                                 /* 1 to write. 0 read-only */
56865   struct KeyInfo *pKeyInfo,                   /* First arg to xCompare() */
56866   BtCursor *pCur                              /* Write new cursor here */
56867 ){
56868   int rc;
56869   sqlite3BtreeEnter(p);
56870   rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
56871   sqlite3BtreeLeave(p);
56872   return rc;
56873 }
56874
56875 /*
56876 ** Return the size of a BtCursor object in bytes.
56877 **
56878 ** This interfaces is needed so that users of cursors can preallocate
56879 ** sufficient storage to hold a cursor.  The BtCursor object is opaque
56880 ** to users so they cannot do the sizeof() themselves - they must call
56881 ** this routine.
56882 */
56883 SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
56884   return ROUND8(sizeof(BtCursor));
56885 }
56886
56887 /*
56888 ** Initialize memory that will be converted into a BtCursor object.
56889 **
56890 ** The simple approach here would be to memset() the entire object
56891 ** to zero.  But it turns out that the apPage[] and aiIdx[] arrays
56892 ** do not need to be zeroed and they are large, so we can save a lot
56893 ** of run-time by skipping the initialization of those elements.
56894 */
56895 SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
56896   memset(p, 0, offsetof(BtCursor, iPage));
56897 }
56898
56899 /*
56900 ** Close a cursor.  The read lock on the database file is released
56901 ** when the last cursor is closed.
56902 */
56903 SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
56904   Btree *pBtree = pCur->pBtree;
56905   if( pBtree ){
56906     int i;
56907     BtShared *pBt = pCur->pBt;
56908     sqlite3BtreeEnter(pBtree);
56909     sqlite3BtreeClearCursor(pCur);
56910     if( pCur->pPrev ){
56911       pCur->pPrev->pNext = pCur->pNext;
56912     }else{
56913       pBt->pCursor = pCur->pNext;
56914     }
56915     if( pCur->pNext ){
56916       pCur->pNext->pPrev = pCur->pPrev;
56917     }
56918     for(i=0; i<=pCur->iPage; i++){
56919       releasePage(pCur->apPage[i]);
56920     }
56921     unlockBtreeIfUnused(pBt);
56922     sqlite3_free(pCur->aOverflow);
56923     /* sqlite3_free(pCur); */
56924     sqlite3BtreeLeave(pBtree);
56925   }
56926   return SQLITE_OK;
56927 }
56928
56929 /*
56930 ** Make sure the BtCursor* given in the argument has a valid
56931 ** BtCursor.info structure.  If it is not already valid, call
56932 ** btreeParseCell() to fill it in.
56933 **
56934 ** BtCursor.info is a cache of the information in the current cell.
56935 ** Using this cache reduces the number of calls to btreeParseCell().
56936 **
56937 ** 2007-06-25:  There is a bug in some versions of MSVC that cause the
56938 ** compiler to crash when getCellInfo() is implemented as a macro.
56939 ** But there is a measureable speed advantage to using the macro on gcc
56940 ** (when less compiler optimizations like -Os or -O0 are used and the
56941 ** compiler is not doing aggressive inlining.)  So we use a real function
56942 ** for MSVC and a macro for everything else.  Ticket #2457.
56943 */
56944 #ifndef NDEBUG
56945   static void assertCellInfo(BtCursor *pCur){
56946     CellInfo info;
56947     int iPage = pCur->iPage;
56948     memset(&info, 0, sizeof(info));
56949     btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
56950     assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
56951   }
56952 #else
56953   #define assertCellInfo(x)
56954 #endif
56955 #ifdef _MSC_VER
56956   /* Use a real function in MSVC to work around bugs in that compiler. */
56957   static void getCellInfo(BtCursor *pCur){
56958     if( pCur->info.nSize==0 ){
56959       int iPage = pCur->iPage;
56960       btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
56961       pCur->curFlags |= BTCF_ValidNKey;
56962     }else{
56963       assertCellInfo(pCur);
56964     }
56965   }
56966 #else /* if not _MSC_VER */
56967   /* Use a macro in all other compilers so that the function is inlined */
56968 #define getCellInfo(pCur)                                                      \
56969   if( pCur->info.nSize==0 ){                                                   \
56970     int iPage = pCur->iPage;                                                   \
56971     btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);        \
56972     pCur->curFlags |= BTCF_ValidNKey;                                          \
56973   }else{                                                                       \
56974     assertCellInfo(pCur);                                                      \
56975   }
56976 #endif /* _MSC_VER */
56977
56978 #ifndef NDEBUG  /* The next routine used only within assert() statements */
56979 /*
56980 ** Return true if the given BtCursor is valid.  A valid cursor is one
56981 ** that is currently pointing to a row in a (non-empty) table.
56982 ** This is a verification routine is used only within assert() statements.
56983 */
56984 SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
56985   return pCur && pCur->eState==CURSOR_VALID;
56986 }
56987 #endif /* NDEBUG */
56988
56989 /*
56990 ** Set *pSize to the size of the buffer needed to hold the value of
56991 ** the key for the current entry.  If the cursor is not pointing
56992 ** to a valid entry, *pSize is set to 0. 
56993 **
56994 ** For a table with the INTKEY flag set, this routine returns the key
56995 ** itself, not the number of bytes in the key.
56996 **
56997 ** The caller must position the cursor prior to invoking this routine.
56998 ** 
56999 ** This routine cannot fail.  It always returns SQLITE_OK.  
57000 */
57001 SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
57002   assert( cursorHoldsMutex(pCur) );
57003   assert( pCur->eState==CURSOR_VALID );
57004   getCellInfo(pCur);
57005   *pSize = pCur->info.nKey;
57006   return SQLITE_OK;
57007 }
57008
57009 /*
57010 ** Set *pSize to the number of bytes of data in the entry the
57011 ** cursor currently points to.
57012 **
57013 ** The caller must guarantee that the cursor is pointing to a non-NULL
57014 ** valid entry.  In other words, the calling procedure must guarantee
57015 ** that the cursor has Cursor.eState==CURSOR_VALID.
57016 **
57017 ** Failure is not possible.  This function always returns SQLITE_OK.
57018 ** It might just as well be a procedure (returning void) but we continue
57019 ** to return an integer result code for historical reasons.
57020 */
57021 SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
57022   assert( cursorHoldsMutex(pCur) );
57023   assert( pCur->eState==CURSOR_VALID );
57024   assert( pCur->iPage>=0 );
57025   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
57026   assert( pCur->apPage[pCur->iPage]->intKeyLeaf==1 );
57027   getCellInfo(pCur);
57028   *pSize = pCur->info.nPayload;
57029   return SQLITE_OK;
57030 }
57031
57032 /*
57033 ** Given the page number of an overflow page in the database (parameter
57034 ** ovfl), this function finds the page number of the next page in the 
57035 ** linked list of overflow pages. If possible, it uses the auto-vacuum
57036 ** pointer-map data instead of reading the content of page ovfl to do so. 
57037 **
57038 ** If an error occurs an SQLite error code is returned. Otherwise:
57039 **
57040 ** The page number of the next overflow page in the linked list is 
57041 ** written to *pPgnoNext. If page ovfl is the last page in its linked 
57042 ** list, *pPgnoNext is set to zero. 
57043 **
57044 ** If ppPage is not NULL, and a reference to the MemPage object corresponding
57045 ** to page number pOvfl was obtained, then *ppPage is set to point to that
57046 ** reference. It is the responsibility of the caller to call releasePage()
57047 ** on *ppPage to free the reference. In no reference was obtained (because
57048 ** the pointer-map was used to obtain the value for *pPgnoNext), then
57049 ** *ppPage is set to zero.
57050 */
57051 static int getOverflowPage(
57052   BtShared *pBt,               /* The database file */
57053   Pgno ovfl,                   /* Current overflow page number */
57054   MemPage **ppPage,            /* OUT: MemPage handle (may be NULL) */
57055   Pgno *pPgnoNext              /* OUT: Next overflow page number */
57056 ){
57057   Pgno next = 0;
57058   MemPage *pPage = 0;
57059   int rc = SQLITE_OK;
57060
57061   assert( sqlite3_mutex_held(pBt->mutex) );
57062   assert(pPgnoNext);
57063
57064 #ifndef SQLITE_OMIT_AUTOVACUUM
57065   /* Try to find the next page in the overflow list using the
57066   ** autovacuum pointer-map pages. Guess that the next page in 
57067   ** the overflow list is page number (ovfl+1). If that guess turns 
57068   ** out to be wrong, fall back to loading the data of page 
57069   ** number ovfl to determine the next page number.
57070   */
57071   if( pBt->autoVacuum ){
57072     Pgno pgno;
57073     Pgno iGuess = ovfl+1;
57074     u8 eType;
57075
57076     while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
57077       iGuess++;
57078     }
57079
57080     if( iGuess<=btreePagecount(pBt) ){
57081       rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
57082       if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
57083         next = iGuess;
57084         rc = SQLITE_DONE;
57085       }
57086     }
57087   }
57088 #endif
57089
57090   assert( next==0 || rc==SQLITE_DONE );
57091   if( rc==SQLITE_OK ){
57092     rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
57093     assert( rc==SQLITE_OK || pPage==0 );
57094     if( rc==SQLITE_OK ){
57095       next = get4byte(pPage->aData);
57096     }
57097   }
57098
57099   *pPgnoNext = next;
57100   if( ppPage ){
57101     *ppPage = pPage;
57102   }else{
57103     releasePage(pPage);
57104   }
57105   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
57106 }
57107
57108 /*
57109 ** Copy data from a buffer to a page, or from a page to a buffer.
57110 **
57111 ** pPayload is a pointer to data stored on database page pDbPage.
57112 ** If argument eOp is false, then nByte bytes of data are copied
57113 ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
57114 ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
57115 ** of data are copied from the buffer pBuf to pPayload.
57116 **
57117 ** SQLITE_OK is returned on success, otherwise an error code.
57118 */
57119 static int copyPayload(
57120   void *pPayload,           /* Pointer to page data */
57121   void *pBuf,               /* Pointer to buffer */
57122   int nByte,                /* Number of bytes to copy */
57123   int eOp,                  /* 0 -> copy from page, 1 -> copy to page */
57124   DbPage *pDbPage           /* Page containing pPayload */
57125 ){
57126   if( eOp ){
57127     /* Copy data from buffer to page (a write operation) */
57128     int rc = sqlite3PagerWrite(pDbPage);
57129     if( rc!=SQLITE_OK ){
57130       return rc;
57131     }
57132     memcpy(pPayload, pBuf, nByte);
57133   }else{
57134     /* Copy data from page to buffer (a read operation) */
57135     memcpy(pBuf, pPayload, nByte);
57136   }
57137   return SQLITE_OK;
57138 }
57139
57140 /*
57141 ** This function is used to read or overwrite payload information
57142 ** for the entry that the pCur cursor is pointing to. The eOp
57143 ** argument is interpreted as follows:
57144 **
57145 **   0: The operation is a read. Populate the overflow cache.
57146 **   1: The operation is a write. Populate the overflow cache.
57147 **   2: The operation is a read. Do not populate the overflow cache.
57148 **
57149 ** A total of "amt" bytes are read or written beginning at "offset".
57150 ** Data is read to or from the buffer pBuf.
57151 **
57152 ** The content being read or written might appear on the main page
57153 ** or be scattered out on multiple overflow pages.
57154 **
57155 ** If the current cursor entry uses one or more overflow pages and the
57156 ** eOp argument is not 2, this function may allocate space for and lazily 
57157 ** populates the overflow page-list cache array (BtCursor.aOverflow). 
57158 ** Subsequent calls use this cache to make seeking to the supplied offset 
57159 ** more efficient.
57160 **
57161 ** Once an overflow page-list cache has been allocated, it may be
57162 ** invalidated if some other cursor writes to the same table, or if
57163 ** the cursor is moved to a different row. Additionally, in auto-vacuum
57164 ** mode, the following events may invalidate an overflow page-list cache.
57165 **
57166 **   * An incremental vacuum,
57167 **   * A commit in auto_vacuum="full" mode,
57168 **   * Creating a table (may require moving an overflow page).
57169 */
57170 static int accessPayload(
57171   BtCursor *pCur,      /* Cursor pointing to entry to read from */
57172   u32 offset,          /* Begin reading this far into payload */
57173   u32 amt,             /* Read this many bytes */
57174   unsigned char *pBuf, /* Write the bytes into this buffer */ 
57175   int eOp              /* zero to read. non-zero to write. */
57176 ){
57177   unsigned char *aPayload;
57178   int rc = SQLITE_OK;
57179   int iIdx = 0;
57180   MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
57181   BtShared *pBt = pCur->pBt;                  /* Btree this cursor belongs to */
57182 #ifdef SQLITE_DIRECT_OVERFLOW_READ
57183   unsigned char * const pBufStart = pBuf;
57184   int bEnd;                                 /* True if reading to end of data */
57185 #endif
57186
57187   assert( pPage );
57188   assert( pCur->eState==CURSOR_VALID );
57189   assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
57190   assert( cursorHoldsMutex(pCur) );
57191   assert( eOp!=2 || offset==0 );    /* Always start from beginning for eOp==2 */
57192
57193   getCellInfo(pCur);
57194   aPayload = pCur->info.pPayload;
57195 #ifdef SQLITE_DIRECT_OVERFLOW_READ
57196   bEnd = offset+amt==pCur->info.nPayload;
57197 #endif
57198   assert( offset+amt <= pCur->info.nPayload );
57199
57200   if( &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] ){
57201     /* Trying to read or write past the end of the data is an error */
57202     return SQLITE_CORRUPT_BKPT;
57203   }
57204
57205   /* Check if data must be read/written to/from the btree page itself. */
57206   if( offset<pCur->info.nLocal ){
57207     int a = amt;
57208     if( a+offset>pCur->info.nLocal ){
57209       a = pCur->info.nLocal - offset;
57210     }
57211     rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
57212     offset = 0;
57213     pBuf += a;
57214     amt -= a;
57215   }else{
57216     offset -= pCur->info.nLocal;
57217   }
57218
57219
57220   if( rc==SQLITE_OK && amt>0 ){
57221     const u32 ovflSize = pBt->usableSize - 4;  /* Bytes content per ovfl page */
57222     Pgno nextPage;
57223
57224     nextPage = get4byte(&aPayload[pCur->info.nLocal]);
57225
57226     /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
57227     ** Except, do not allocate aOverflow[] for eOp==2.
57228     **
57229     ** The aOverflow[] array is sized at one entry for each overflow page
57230     ** in the overflow chain. The page number of the first overflow page is
57231     ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
57232     ** means "not yet known" (the cache is lazily populated).
57233     */
57234     if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
57235       int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
57236       if( nOvfl>pCur->nOvflAlloc ){
57237         Pgno *aNew = (Pgno*)sqlite3Realloc(
57238             pCur->aOverflow, nOvfl*2*sizeof(Pgno)
57239         );
57240         if( aNew==0 ){
57241           rc = SQLITE_NOMEM;
57242         }else{
57243           pCur->nOvflAlloc = nOvfl*2;
57244           pCur->aOverflow = aNew;
57245         }
57246       }
57247       if( rc==SQLITE_OK ){
57248         memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
57249         pCur->curFlags |= BTCF_ValidOvfl;
57250       }
57251     }
57252
57253     /* If the overflow page-list cache has been allocated and the
57254     ** entry for the first required overflow page is valid, skip
57255     ** directly to it.
57256     */
57257     if( (pCur->curFlags & BTCF_ValidOvfl)!=0
57258      && pCur->aOverflow[offset/ovflSize]
57259     ){
57260       iIdx = (offset/ovflSize);
57261       nextPage = pCur->aOverflow[iIdx];
57262       offset = (offset%ovflSize);
57263     }
57264
57265     for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
57266
57267       /* If required, populate the overflow page-list cache. */
57268       if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
57269         assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
57270         pCur->aOverflow[iIdx] = nextPage;
57271       }
57272
57273       if( offset>=ovflSize ){
57274         /* The only reason to read this page is to obtain the page
57275         ** number for the next page in the overflow chain. The page
57276         ** data is not required. So first try to lookup the overflow
57277         ** page-list cache, if any, then fall back to the getOverflowPage()
57278         ** function.
57279         **
57280         ** Note that the aOverflow[] array must be allocated because eOp!=2
57281         ** here.  If eOp==2, then offset==0 and this branch is never taken.
57282         */
57283         assert( eOp!=2 );
57284         assert( pCur->curFlags & BTCF_ValidOvfl );
57285         assert( pCur->pBtree->db==pBt->db );
57286         if( pCur->aOverflow[iIdx+1] ){
57287           nextPage = pCur->aOverflow[iIdx+1];
57288         }else{
57289           rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
57290         }
57291         offset -= ovflSize;
57292       }else{
57293         /* Need to read this page properly. It contains some of the
57294         ** range of data that is being read (eOp==0) or written (eOp!=0).
57295         */
57296 #ifdef SQLITE_DIRECT_OVERFLOW_READ
57297         sqlite3_file *fd;
57298 #endif
57299         int a = amt;
57300         if( a + offset > ovflSize ){
57301           a = ovflSize - offset;
57302         }
57303
57304 #ifdef SQLITE_DIRECT_OVERFLOW_READ
57305         /* If all the following are true:
57306         **
57307         **   1) this is a read operation, and 
57308         **   2) data is required from the start of this overflow page, and
57309         **   3) the database is file-backed, and
57310         **   4) there is no open write-transaction, and
57311         **   5) the database is not a WAL database,
57312         **   6) all data from the page is being read.
57313         **   7) at least 4 bytes have already been read into the output buffer 
57314         **
57315         ** then data can be read directly from the database file into the
57316         ** output buffer, bypassing the page-cache altogether. This speeds
57317         ** up loading large records that span many overflow pages.
57318         */
57319         if( (eOp&0x01)==0                                      /* (1) */
57320          && offset==0                                          /* (2) */
57321          && (bEnd || a==ovflSize)                              /* (6) */
57322          && pBt->inTransaction==TRANS_READ                     /* (4) */
57323          && (fd = sqlite3PagerFile(pBt->pPager))->pMethods     /* (3) */
57324          && pBt->pPage1->aData[19]==0x01                       /* (5) */
57325          && &pBuf[-4]>=pBufStart                               /* (7) */
57326         ){
57327           u8 aSave[4];
57328           u8 *aWrite = &pBuf[-4];
57329           assert( aWrite>=pBufStart );                         /* hence (7) */
57330           memcpy(aSave, aWrite, 4);
57331           rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
57332           nextPage = get4byte(aWrite);
57333           memcpy(aWrite, aSave, 4);
57334         }else
57335 #endif
57336
57337         {
57338           DbPage *pDbPage;
57339           rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
57340               ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
57341           );
57342           if( rc==SQLITE_OK ){
57343             aPayload = sqlite3PagerGetData(pDbPage);
57344             nextPage = get4byte(aPayload);
57345             rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
57346             sqlite3PagerUnref(pDbPage);
57347             offset = 0;
57348           }
57349         }
57350         amt -= a;
57351         pBuf += a;
57352       }
57353     }
57354   }
57355
57356   if( rc==SQLITE_OK && amt>0 ){
57357     return SQLITE_CORRUPT_BKPT;
57358   }
57359   return rc;
57360 }
57361
57362 /*
57363 ** Read part of the key associated with cursor pCur.  Exactly
57364 ** "amt" bytes will be transferred into pBuf[].  The transfer
57365 ** begins at "offset".
57366 **
57367 ** The caller must ensure that pCur is pointing to a valid row
57368 ** in the table.
57369 **
57370 ** Return SQLITE_OK on success or an error code if anything goes
57371 ** wrong.  An error is returned if "offset+amt" is larger than
57372 ** the available payload.
57373 */
57374 SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
57375   assert( cursorHoldsMutex(pCur) );
57376   assert( pCur->eState==CURSOR_VALID );
57377   assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
57378   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
57379   return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
57380 }
57381
57382 /*
57383 ** Read part of the data associated with cursor pCur.  Exactly
57384 ** "amt" bytes will be transfered into pBuf[].  The transfer
57385 ** begins at "offset".
57386 **
57387 ** Return SQLITE_OK on success or an error code if anything goes
57388 ** wrong.  An error is returned if "offset+amt" is larger than
57389 ** the available payload.
57390 */
57391 SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
57392   int rc;
57393
57394 #ifndef SQLITE_OMIT_INCRBLOB
57395   if ( pCur->eState==CURSOR_INVALID ){
57396     return SQLITE_ABORT;
57397   }
57398 #endif
57399
57400   assert( cursorHoldsMutex(pCur) );
57401   rc = restoreCursorPosition(pCur);
57402   if( rc==SQLITE_OK ){
57403     assert( pCur->eState==CURSOR_VALID );
57404     assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
57405     assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
57406     rc = accessPayload(pCur, offset, amt, pBuf, 0);
57407   }
57408   return rc;
57409 }
57410
57411 /*
57412 ** Return a pointer to payload information from the entry that the 
57413 ** pCur cursor is pointing to.  The pointer is to the beginning of
57414 ** the key if index btrees (pPage->intKey==0) and is the data for
57415 ** table btrees (pPage->intKey==1). The number of bytes of available
57416 ** key/data is written into *pAmt.  If *pAmt==0, then the value
57417 ** returned will not be a valid pointer.
57418 **
57419 ** This routine is an optimization.  It is common for the entire key
57420 ** and data to fit on the local page and for there to be no overflow
57421 ** pages.  When that is so, this routine can be used to access the
57422 ** key and data without making a copy.  If the key and/or data spills
57423 ** onto overflow pages, then accessPayload() must be used to reassemble
57424 ** the key/data and copy it into a preallocated buffer.
57425 **
57426 ** The pointer returned by this routine looks directly into the cached
57427 ** page of the database.  The data might change or move the next time
57428 ** any btree routine is called.
57429 */
57430 static const void *fetchPayload(
57431   BtCursor *pCur,      /* Cursor pointing to entry to read from */
57432   u32 *pAmt            /* Write the number of available bytes here */
57433 ){
57434   assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
57435   assert( pCur->eState==CURSOR_VALID );
57436   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
57437   assert( cursorHoldsMutex(pCur) );
57438   assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
57439   assert( pCur->info.nSize>0 );
57440   *pAmt = pCur->info.nLocal;
57441   return (void*)pCur->info.pPayload;
57442 }
57443
57444
57445 /*
57446 ** For the entry that cursor pCur is point to, return as
57447 ** many bytes of the key or data as are available on the local
57448 ** b-tree page.  Write the number of available bytes into *pAmt.
57449 **
57450 ** The pointer returned is ephemeral.  The key/data may move
57451 ** or be destroyed on the next call to any Btree routine,
57452 ** including calls from other threads against the same cache.
57453 ** Hence, a mutex on the BtShared should be held prior to calling
57454 ** this routine.
57455 **
57456 ** These routines is used to get quick access to key and data
57457 ** in the common case where no overflow pages are used.
57458 */
57459 SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){
57460   return fetchPayload(pCur, pAmt);
57461 }
57462 SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){
57463   return fetchPayload(pCur, pAmt);
57464 }
57465
57466
57467 /*
57468 ** Move the cursor down to a new child page.  The newPgno argument is the
57469 ** page number of the child page to move to.
57470 **
57471 ** This function returns SQLITE_CORRUPT if the page-header flags field of
57472 ** the new child page does not match the flags field of the parent (i.e.
57473 ** if an intkey page appears to be the parent of a non-intkey page, or
57474 ** vice-versa).
57475 */
57476 static int moveToChild(BtCursor *pCur, u32 newPgno){
57477   int rc;
57478   int i = pCur->iPage;
57479   MemPage *pNewPage;
57480   BtShared *pBt = pCur->pBt;
57481
57482   assert( cursorHoldsMutex(pCur) );
57483   assert( pCur->eState==CURSOR_VALID );
57484   assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
57485   assert( pCur->iPage>=0 );
57486   if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
57487     return SQLITE_CORRUPT_BKPT;
57488   }
57489   rc = getAndInitPage(pBt, newPgno, &pNewPage,
57490                (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
57491   if( rc ) return rc;
57492   pCur->apPage[i+1] = pNewPage;
57493   pCur->aiIdx[i+1] = 0;
57494   pCur->iPage++;
57495
57496   pCur->info.nSize = 0;
57497   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
57498   if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
57499     return SQLITE_CORRUPT_BKPT;
57500   }
57501   return SQLITE_OK;
57502 }
57503
57504 #if SQLITE_DEBUG
57505 /*
57506 ** Page pParent is an internal (non-leaf) tree page. This function 
57507 ** asserts that page number iChild is the left-child if the iIdx'th
57508 ** cell in page pParent. Or, if iIdx is equal to the total number of
57509 ** cells in pParent, that page number iChild is the right-child of
57510 ** the page.
57511 */
57512 static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
57513   if( CORRUPT_DB ) return;  /* The conditions tested below might not be true
57514                             ** in a corrupt database */
57515   assert( iIdx<=pParent->nCell );
57516   if( iIdx==pParent->nCell ){
57517     assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
57518   }else{
57519     assert( get4byte(findCell(pParent, iIdx))==iChild );
57520   }
57521 }
57522 #else
57523 #  define assertParentIndex(x,y,z) 
57524 #endif
57525
57526 /*
57527 ** Move the cursor up to the parent page.
57528 **
57529 ** pCur->idx is set to the cell index that contains the pointer
57530 ** to the page we are coming from.  If we are coming from the
57531 ** right-most child page then pCur->idx is set to one more than
57532 ** the largest cell index.
57533 */
57534 static void moveToParent(BtCursor *pCur){
57535   assert( cursorHoldsMutex(pCur) );
57536   assert( pCur->eState==CURSOR_VALID );
57537   assert( pCur->iPage>0 );
57538   assert( pCur->apPage[pCur->iPage] );
57539   assertParentIndex(
57540     pCur->apPage[pCur->iPage-1], 
57541     pCur->aiIdx[pCur->iPage-1], 
57542     pCur->apPage[pCur->iPage]->pgno
57543   );
57544   testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
57545
57546   releasePage(pCur->apPage[pCur->iPage]);
57547   pCur->iPage--;
57548   pCur->info.nSize = 0;
57549   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
57550 }
57551
57552 /*
57553 ** Move the cursor to point to the root page of its b-tree structure.
57554 **
57555 ** If the table has a virtual root page, then the cursor is moved to point
57556 ** to the virtual root page instead of the actual root page. A table has a
57557 ** virtual root page when the actual root page contains no cells and a 
57558 ** single child page. This can only happen with the table rooted at page 1.
57559 **
57560 ** If the b-tree structure is empty, the cursor state is set to 
57561 ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
57562 ** cell located on the root (or virtual root) page and the cursor state
57563 ** is set to CURSOR_VALID.
57564 **
57565 ** If this function returns successfully, it may be assumed that the
57566 ** page-header flags indicate that the [virtual] root-page is the expected 
57567 ** kind of b-tree page (i.e. if when opening the cursor the caller did not
57568 ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
57569 ** indicating a table b-tree, or if the caller did specify a KeyInfo 
57570 ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
57571 ** b-tree).
57572 */
57573 static int moveToRoot(BtCursor *pCur){
57574   MemPage *pRoot;
57575   int rc = SQLITE_OK;
57576
57577   assert( cursorHoldsMutex(pCur) );
57578   assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
57579   assert( CURSOR_VALID   < CURSOR_REQUIRESEEK );
57580   assert( CURSOR_FAULT   > CURSOR_REQUIRESEEK );
57581   if( pCur->eState>=CURSOR_REQUIRESEEK ){
57582     if( pCur->eState==CURSOR_FAULT ){
57583       assert( pCur->skipNext!=SQLITE_OK );
57584       return pCur->skipNext;
57585     }
57586     sqlite3BtreeClearCursor(pCur);
57587   }
57588
57589   if( pCur->iPage>=0 ){
57590     while( pCur->iPage ) releasePage(pCur->apPage[pCur->iPage--]);
57591   }else if( pCur->pgnoRoot==0 ){
57592     pCur->eState = CURSOR_INVALID;
57593     return SQLITE_OK;
57594   }else{
57595     rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
57596                  (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
57597     if( rc!=SQLITE_OK ){
57598       pCur->eState = CURSOR_INVALID;
57599       return rc;
57600     }
57601     pCur->iPage = 0;
57602   }
57603   pRoot = pCur->apPage[0];
57604   assert( pRoot->pgno==pCur->pgnoRoot );
57605
57606   /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
57607   ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
57608   ** NULL, the caller expects a table b-tree. If this is not the case,
57609   ** return an SQLITE_CORRUPT error. 
57610   **
57611   ** Earlier versions of SQLite assumed that this test could not fail
57612   ** if the root page was already loaded when this function was called (i.e.
57613   ** if pCur->iPage>=0). But this is not so if the database is corrupted 
57614   ** in such a way that page pRoot is linked into a second b-tree table 
57615   ** (or the freelist).  */
57616   assert( pRoot->intKey==1 || pRoot->intKey==0 );
57617   if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
57618     return SQLITE_CORRUPT_BKPT;
57619   }
57620
57621   pCur->aiIdx[0] = 0;
57622   pCur->info.nSize = 0;
57623   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
57624
57625   if( pRoot->nCell>0 ){
57626     pCur->eState = CURSOR_VALID;
57627   }else if( !pRoot->leaf ){
57628     Pgno subpage;
57629     if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
57630     subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
57631     pCur->eState = CURSOR_VALID;
57632     rc = moveToChild(pCur, subpage);
57633   }else{
57634     pCur->eState = CURSOR_INVALID;
57635   }
57636   return rc;
57637 }
57638
57639 /*
57640 ** Move the cursor down to the left-most leaf entry beneath the
57641 ** entry to which it is currently pointing.
57642 **
57643 ** The left-most leaf is the one with the smallest key - the first
57644 ** in ascending order.
57645 */
57646 static int moveToLeftmost(BtCursor *pCur){
57647   Pgno pgno;
57648   int rc = SQLITE_OK;
57649   MemPage *pPage;
57650
57651   assert( cursorHoldsMutex(pCur) );
57652   assert( pCur->eState==CURSOR_VALID );
57653   while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
57654     assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
57655     pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
57656     rc = moveToChild(pCur, pgno);
57657   }
57658   return rc;
57659 }
57660
57661 /*
57662 ** Move the cursor down to the right-most leaf entry beneath the
57663 ** page to which it is currently pointing.  Notice the difference
57664 ** between moveToLeftmost() and moveToRightmost().  moveToLeftmost()
57665 ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
57666 ** finds the right-most entry beneath the *page*.
57667 **
57668 ** The right-most entry is the one with the largest key - the last
57669 ** key in ascending order.
57670 */
57671 static int moveToRightmost(BtCursor *pCur){
57672   Pgno pgno;
57673   int rc = SQLITE_OK;
57674   MemPage *pPage = 0;
57675
57676   assert( cursorHoldsMutex(pCur) );
57677   assert( pCur->eState==CURSOR_VALID );
57678   while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
57679     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
57680     pCur->aiIdx[pCur->iPage] = pPage->nCell;
57681     rc = moveToChild(pCur, pgno);
57682     if( rc ) return rc;
57683   }
57684   pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
57685   assert( pCur->info.nSize==0 );
57686   assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
57687   return SQLITE_OK;
57688 }
57689
57690 /* Move the cursor to the first entry in the table.  Return SQLITE_OK
57691 ** on success.  Set *pRes to 0 if the cursor actually points to something
57692 ** or set *pRes to 1 if the table is empty.
57693 */
57694 SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
57695   int rc;
57696
57697   assert( cursorHoldsMutex(pCur) );
57698   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
57699   rc = moveToRoot(pCur);
57700   if( rc==SQLITE_OK ){
57701     if( pCur->eState==CURSOR_INVALID ){
57702       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
57703       *pRes = 1;
57704     }else{
57705       assert( pCur->apPage[pCur->iPage]->nCell>0 );
57706       *pRes = 0;
57707       rc = moveToLeftmost(pCur);
57708     }
57709   }
57710   return rc;
57711 }
57712
57713 /* Move the cursor to the last entry in the table.  Return SQLITE_OK
57714 ** on success.  Set *pRes to 0 if the cursor actually points to something
57715 ** or set *pRes to 1 if the table is empty.
57716 */
57717 SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
57718   int rc;
57719  
57720   assert( cursorHoldsMutex(pCur) );
57721   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
57722
57723   /* If the cursor already points to the last entry, this is a no-op. */
57724   if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
57725 #ifdef SQLITE_DEBUG
57726     /* This block serves to assert() that the cursor really does point 
57727     ** to the last entry in the b-tree. */
57728     int ii;
57729     for(ii=0; ii<pCur->iPage; ii++){
57730       assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
57731     }
57732     assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
57733     assert( pCur->apPage[pCur->iPage]->leaf );
57734 #endif
57735     return SQLITE_OK;
57736   }
57737
57738   rc = moveToRoot(pCur);
57739   if( rc==SQLITE_OK ){
57740     if( CURSOR_INVALID==pCur->eState ){
57741       assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
57742       *pRes = 1;
57743     }else{
57744       assert( pCur->eState==CURSOR_VALID );
57745       *pRes = 0;
57746       rc = moveToRightmost(pCur);
57747       if( rc==SQLITE_OK ){
57748         pCur->curFlags |= BTCF_AtLast;
57749       }else{
57750         pCur->curFlags &= ~BTCF_AtLast;
57751       }
57752    
57753     }
57754   }
57755   return rc;
57756 }
57757
57758 /* Move the cursor so that it points to an entry near the key 
57759 ** specified by pIdxKey or intKey.   Return a success code.
57760 **
57761 ** For INTKEY tables, the intKey parameter is used.  pIdxKey 
57762 ** must be NULL.  For index tables, pIdxKey is used and intKey
57763 ** is ignored.
57764 **
57765 ** If an exact match is not found, then the cursor is always
57766 ** left pointing at a leaf page which would hold the entry if it
57767 ** were present.  The cursor might point to an entry that comes
57768 ** before or after the key.
57769 **
57770 ** An integer is written into *pRes which is the result of
57771 ** comparing the key with the entry to which the cursor is 
57772 ** pointing.  The meaning of the integer written into
57773 ** *pRes is as follows:
57774 **
57775 **     *pRes<0      The cursor is left pointing at an entry that
57776 **                  is smaller than intKey/pIdxKey or if the table is empty
57777 **                  and the cursor is therefore left point to nothing.
57778 **
57779 **     *pRes==0     The cursor is left pointing at an entry that
57780 **                  exactly matches intKey/pIdxKey.
57781 **
57782 **     *pRes>0      The cursor is left pointing at an entry that
57783 **                  is larger than intKey/pIdxKey.
57784 **
57785 */
57786 SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
57787   BtCursor *pCur,          /* The cursor to be moved */
57788   UnpackedRecord *pIdxKey, /* Unpacked index key */
57789   i64 intKey,              /* The table key */
57790   int biasRight,           /* If true, bias the search to the high end */
57791   int *pRes                /* Write search results here */
57792 ){
57793   int rc;
57794   RecordCompare xRecordCompare;
57795
57796   assert( cursorHoldsMutex(pCur) );
57797   assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
57798   assert( pRes );
57799   assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
57800
57801   /* If the cursor is already positioned at the point we are trying
57802   ** to move to, then just return without doing any work */
57803   if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
57804    && pCur->apPage[0]->intKey 
57805   ){
57806     if( pCur->info.nKey==intKey ){
57807       *pRes = 0;
57808       return SQLITE_OK;
57809     }
57810     if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
57811       *pRes = -1;
57812       return SQLITE_OK;
57813     }
57814   }
57815
57816   if( pIdxKey ){
57817     xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
57818     pIdxKey->errCode = 0;
57819     assert( pIdxKey->default_rc==1 
57820          || pIdxKey->default_rc==0 
57821          || pIdxKey->default_rc==-1
57822     );
57823   }else{
57824     xRecordCompare = 0; /* All keys are integers */
57825   }
57826
57827   rc = moveToRoot(pCur);
57828   if( rc ){
57829     return rc;
57830   }
57831   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
57832   assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
57833   assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
57834   if( pCur->eState==CURSOR_INVALID ){
57835     *pRes = -1;
57836     assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
57837     return SQLITE_OK;
57838   }
57839   assert( pCur->apPage[0]->intKey || pIdxKey );
57840   for(;;){
57841     int lwr, upr, idx, c;
57842     Pgno chldPg;
57843     MemPage *pPage = pCur->apPage[pCur->iPage];
57844     u8 *pCell;                          /* Pointer to current cell in pPage */
57845
57846     /* pPage->nCell must be greater than zero. If this is the root-page
57847     ** the cursor would have been INVALID above and this for(;;) loop
57848     ** not run. If this is not the root-page, then the moveToChild() routine
57849     ** would have already detected db corruption. Similarly, pPage must
57850     ** be the right kind (index or table) of b-tree page. Otherwise
57851     ** a moveToChild() or moveToRoot() call would have detected corruption.  */
57852     assert( pPage->nCell>0 );
57853     assert( pPage->intKey==(pIdxKey==0) );
57854     lwr = 0;
57855     upr = pPage->nCell-1;
57856     assert( biasRight==0 || biasRight==1 );
57857     idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
57858     pCur->aiIdx[pCur->iPage] = (u16)idx;
57859     if( xRecordCompare==0 ){
57860       for(;;){
57861         i64 nCellKey;
57862         pCell = findCell(pPage, idx) + pPage->childPtrSize;
57863         if( pPage->intKeyLeaf ){
57864           while( 0x80 <= *(pCell++) ){
57865             if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
57866           }
57867         }
57868         getVarint(pCell, (u64*)&nCellKey);
57869         if( nCellKey<intKey ){
57870           lwr = idx+1;
57871           if( lwr>upr ){ c = -1; break; }
57872         }else if( nCellKey>intKey ){
57873           upr = idx-1;
57874           if( lwr>upr ){ c = +1; break; }
57875         }else{
57876           assert( nCellKey==intKey );
57877           pCur->curFlags |= BTCF_ValidNKey;
57878           pCur->info.nKey = nCellKey;
57879           pCur->aiIdx[pCur->iPage] = (u16)idx;
57880           if( !pPage->leaf ){
57881             lwr = idx;
57882             goto moveto_next_layer;
57883           }else{
57884             *pRes = 0;
57885             rc = SQLITE_OK;
57886             goto moveto_finish;
57887           }
57888         }
57889         assert( lwr+upr>=0 );
57890         idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2; */
57891       }
57892     }else{
57893       for(;;){
57894         int nCell;
57895         pCell = findCell(pPage, idx) + pPage->childPtrSize;
57896
57897         /* The maximum supported page-size is 65536 bytes. This means that
57898         ** the maximum number of record bytes stored on an index B-Tree
57899         ** page is less than 16384 bytes and may be stored as a 2-byte
57900         ** varint. This information is used to attempt to avoid parsing 
57901         ** the entire cell by checking for the cases where the record is 
57902         ** stored entirely within the b-tree page by inspecting the first 
57903         ** 2 bytes of the cell.
57904         */
57905         nCell = pCell[0];
57906         if( nCell<=pPage->max1bytePayload ){
57907           /* This branch runs if the record-size field of the cell is a
57908           ** single byte varint and the record fits entirely on the main
57909           ** b-tree page.  */
57910           testcase( pCell+nCell+1==pPage->aDataEnd );
57911           c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
57912         }else if( !(pCell[1] & 0x80) 
57913           && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
57914         ){
57915           /* The record-size field is a 2 byte varint and the record 
57916           ** fits entirely on the main b-tree page.  */
57917           testcase( pCell+nCell+2==pPage->aDataEnd );
57918           c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
57919         }else{
57920           /* The record flows over onto one or more overflow pages. In
57921           ** this case the whole cell needs to be parsed, a buffer allocated
57922           ** and accessPayload() used to retrieve the record into the
57923           ** buffer before VdbeRecordCompare() can be called. */
57924           void *pCellKey;
57925           u8 * const pCellBody = pCell - pPage->childPtrSize;
57926           btreeParseCellPtr(pPage, pCellBody, &pCur->info);
57927           nCell = (int)pCur->info.nKey;
57928           pCellKey = sqlite3Malloc( nCell );
57929           if( pCellKey==0 ){
57930             rc = SQLITE_NOMEM;
57931             goto moveto_finish;
57932           }
57933           pCur->aiIdx[pCur->iPage] = (u16)idx;
57934           rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
57935           if( rc ){
57936             sqlite3_free(pCellKey);
57937             goto moveto_finish;
57938           }
57939           c = xRecordCompare(nCell, pCellKey, pIdxKey);
57940           sqlite3_free(pCellKey);
57941         }
57942         assert( 
57943             (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
57944          && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
57945         );
57946         if( c<0 ){
57947           lwr = idx+1;
57948         }else if( c>0 ){
57949           upr = idx-1;
57950         }else{
57951           assert( c==0 );
57952           *pRes = 0;
57953           rc = SQLITE_OK;
57954           pCur->aiIdx[pCur->iPage] = (u16)idx;
57955           if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
57956           goto moveto_finish;
57957         }
57958         if( lwr>upr ) break;
57959         assert( lwr+upr>=0 );
57960         idx = (lwr+upr)>>1;  /* idx = (lwr+upr)/2 */
57961       }
57962     }
57963     assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
57964     assert( pPage->isInit );
57965     if( pPage->leaf ){
57966       assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
57967       pCur->aiIdx[pCur->iPage] = (u16)idx;
57968       *pRes = c;
57969       rc = SQLITE_OK;
57970       goto moveto_finish;
57971     }
57972 moveto_next_layer:
57973     if( lwr>=pPage->nCell ){
57974       chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
57975     }else{
57976       chldPg = get4byte(findCell(pPage, lwr));
57977     }
57978     pCur->aiIdx[pCur->iPage] = (u16)lwr;
57979     rc = moveToChild(pCur, chldPg);
57980     if( rc ) break;
57981   }
57982 moveto_finish:
57983   pCur->info.nSize = 0;
57984   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
57985   return rc;
57986 }
57987
57988
57989 /*
57990 ** Return TRUE if the cursor is not pointing at an entry of the table.
57991 **
57992 ** TRUE will be returned after a call to sqlite3BtreeNext() moves
57993 ** past the last entry in the table or sqlite3BtreePrev() moves past
57994 ** the first entry.  TRUE is also returned if the table is empty.
57995 */
57996 SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
57997   /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
57998   ** have been deleted? This API will need to change to return an error code
57999   ** as well as the boolean result value.
58000   */
58001   return (CURSOR_VALID!=pCur->eState);
58002 }
58003
58004 /*
58005 ** Advance the cursor to the next entry in the database.  If
58006 ** successful then set *pRes=0.  If the cursor
58007 ** was already pointing to the last entry in the database before
58008 ** this routine was called, then set *pRes=1.
58009 **
58010 ** The main entry point is sqlite3BtreeNext().  That routine is optimized
58011 ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
58012 ** to the next cell on the current page.  The (slower) btreeNext() helper
58013 ** routine is called when it is necessary to move to a different page or
58014 ** to restore the cursor.
58015 **
58016 ** The calling function will set *pRes to 0 or 1.  The initial *pRes value
58017 ** will be 1 if the cursor being stepped corresponds to an SQL index and
58018 ** if this routine could have been skipped if that SQL index had been
58019 ** a unique index.  Otherwise the caller will have set *pRes to zero.
58020 ** Zero is the common case. The btree implementation is free to use the
58021 ** initial *pRes value as a hint to improve performance, but the current
58022 ** SQLite btree implementation does not. (Note that the comdb2 btree
58023 ** implementation does use this hint, however.)
58024 */
58025 static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
58026   int rc;
58027   int idx;
58028   MemPage *pPage;
58029
58030   assert( cursorHoldsMutex(pCur) );
58031   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
58032   assert( *pRes==0 );
58033   if( pCur->eState!=CURSOR_VALID ){
58034     assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
58035     rc = restoreCursorPosition(pCur);
58036     if( rc!=SQLITE_OK ){
58037       return rc;
58038     }
58039     if( CURSOR_INVALID==pCur->eState ){
58040       *pRes = 1;
58041       return SQLITE_OK;
58042     }
58043     if( pCur->skipNext ){
58044       assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
58045       pCur->eState = CURSOR_VALID;
58046       if( pCur->skipNext>0 ){
58047         pCur->skipNext = 0;
58048         return SQLITE_OK;
58049       }
58050       pCur->skipNext = 0;
58051     }
58052   }
58053
58054   pPage = pCur->apPage[pCur->iPage];
58055   idx = ++pCur->aiIdx[pCur->iPage];
58056   assert( pPage->isInit );
58057
58058   /* If the database file is corrupt, it is possible for the value of idx 
58059   ** to be invalid here. This can only occur if a second cursor modifies
58060   ** the page while cursor pCur is holding a reference to it. Which can
58061   ** only happen if the database is corrupt in such a way as to link the
58062   ** page into more than one b-tree structure. */
58063   testcase( idx>pPage->nCell );
58064
58065   if( idx>=pPage->nCell ){
58066     if( !pPage->leaf ){
58067       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
58068       if( rc ) return rc;
58069       return moveToLeftmost(pCur);
58070     }
58071     do{
58072       if( pCur->iPage==0 ){
58073         *pRes = 1;
58074         pCur->eState = CURSOR_INVALID;
58075         return SQLITE_OK;
58076       }
58077       moveToParent(pCur);
58078       pPage = pCur->apPage[pCur->iPage];
58079     }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
58080     if( pPage->intKey ){
58081       return sqlite3BtreeNext(pCur, pRes);
58082     }else{
58083       return SQLITE_OK;
58084     }
58085   }
58086   if( pPage->leaf ){
58087     return SQLITE_OK;
58088   }else{
58089     return moveToLeftmost(pCur);
58090   }
58091 }
58092 SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
58093   MemPage *pPage;
58094   assert( cursorHoldsMutex(pCur) );
58095   assert( pRes!=0 );
58096   assert( *pRes==0 || *pRes==1 );
58097   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
58098   pCur->info.nSize = 0;
58099   pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
58100   *pRes = 0;
58101   if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
58102   pPage = pCur->apPage[pCur->iPage];
58103   if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
58104     pCur->aiIdx[pCur->iPage]--;
58105     return btreeNext(pCur, pRes);
58106   }
58107   if( pPage->leaf ){
58108     return SQLITE_OK;
58109   }else{
58110     return moveToLeftmost(pCur);
58111   }
58112 }
58113
58114 /*
58115 ** Step the cursor to the back to the previous entry in the database.  If
58116 ** successful then set *pRes=0.  If the cursor
58117 ** was already pointing to the first entry in the database before
58118 ** this routine was called, then set *pRes=1.
58119 **
58120 ** The main entry point is sqlite3BtreePrevious().  That routine is optimized
58121 ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
58122 ** to the previous cell on the current page.  The (slower) btreePrevious()
58123 ** helper routine is called when it is necessary to move to a different page
58124 ** or to restore the cursor.
58125 **
58126 ** The calling function will set *pRes to 0 or 1.  The initial *pRes value
58127 ** will be 1 if the cursor being stepped corresponds to an SQL index and
58128 ** if this routine could have been skipped if that SQL index had been
58129 ** a unique index.  Otherwise the caller will have set *pRes to zero.
58130 ** Zero is the common case. The btree implementation is free to use the
58131 ** initial *pRes value as a hint to improve performance, but the current
58132 ** SQLite btree implementation does not. (Note that the comdb2 btree
58133 ** implementation does use this hint, however.)
58134 */
58135 static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
58136   int rc;
58137   MemPage *pPage;
58138
58139   assert( cursorHoldsMutex(pCur) );
58140   assert( pRes!=0 );
58141   assert( *pRes==0 );
58142   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
58143   assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
58144   assert( pCur->info.nSize==0 );
58145   if( pCur->eState!=CURSOR_VALID ){
58146     rc = restoreCursorPosition(pCur);
58147     if( rc!=SQLITE_OK ){
58148       return rc;
58149     }
58150     if( CURSOR_INVALID==pCur->eState ){
58151       *pRes = 1;
58152       return SQLITE_OK;
58153     }
58154     if( pCur->skipNext ){
58155       assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
58156       pCur->eState = CURSOR_VALID;
58157       if( pCur->skipNext<0 ){
58158         pCur->skipNext = 0;
58159         return SQLITE_OK;
58160       }
58161       pCur->skipNext = 0;
58162     }
58163   }
58164
58165   pPage = pCur->apPage[pCur->iPage];
58166   assert( pPage->isInit );
58167   if( !pPage->leaf ){
58168     int idx = pCur->aiIdx[pCur->iPage];
58169     rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
58170     if( rc ) return rc;
58171     rc = moveToRightmost(pCur);
58172   }else{
58173     while( pCur->aiIdx[pCur->iPage]==0 ){
58174       if( pCur->iPage==0 ){
58175         pCur->eState = CURSOR_INVALID;
58176         *pRes = 1;
58177         return SQLITE_OK;
58178       }
58179       moveToParent(pCur);
58180     }
58181     assert( pCur->info.nSize==0 );
58182     assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 );
58183
58184     pCur->aiIdx[pCur->iPage]--;
58185     pPage = pCur->apPage[pCur->iPage];
58186     if( pPage->intKey && !pPage->leaf ){
58187       rc = sqlite3BtreePrevious(pCur, pRes);
58188     }else{
58189       rc = SQLITE_OK;
58190     }
58191   }
58192   return rc;
58193 }
58194 SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
58195   assert( cursorHoldsMutex(pCur) );
58196   assert( pRes!=0 );
58197   assert( *pRes==0 || *pRes==1 );
58198   assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
58199   *pRes = 0;
58200   pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
58201   pCur->info.nSize = 0;
58202   if( pCur->eState!=CURSOR_VALID
58203    || pCur->aiIdx[pCur->iPage]==0
58204    || pCur->apPage[pCur->iPage]->leaf==0
58205   ){
58206     return btreePrevious(pCur, pRes);
58207   }
58208   pCur->aiIdx[pCur->iPage]--;
58209   return SQLITE_OK;
58210 }
58211
58212 /*
58213 ** Allocate a new page from the database file.
58214 **
58215 ** The new page is marked as dirty.  (In other words, sqlite3PagerWrite()
58216 ** has already been called on the new page.)  The new page has also
58217 ** been referenced and the calling routine is responsible for calling
58218 ** sqlite3PagerUnref() on the new page when it is done.
58219 **
58220 ** SQLITE_OK is returned on success.  Any other return value indicates
58221 ** an error.  *ppPage and *pPgno are undefined in the event of an error.
58222 ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
58223 **
58224 ** If the "nearby" parameter is not 0, then an effort is made to 
58225 ** locate a page close to the page number "nearby".  This can be used in an
58226 ** attempt to keep related pages close to each other in the database file,
58227 ** which in turn can make database access faster.
58228 **
58229 ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
58230 ** anywhere on the free-list, then it is guaranteed to be returned.  If
58231 ** eMode is BTALLOC_LT then the page returned will be less than or equal
58232 ** to nearby if any such page exists.  If eMode is BTALLOC_ANY then there
58233 ** are no restrictions on which page is returned.
58234 */
58235 static int allocateBtreePage(
58236   BtShared *pBt,         /* The btree */
58237   MemPage **ppPage,      /* Store pointer to the allocated page here */
58238   Pgno *pPgno,           /* Store the page number here */
58239   Pgno nearby,           /* Search for a page near this one */
58240   u8 eMode               /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
58241 ){
58242   MemPage *pPage1;
58243   int rc;
58244   u32 n;     /* Number of pages on the freelist */
58245   u32 k;     /* Number of leaves on the trunk of the freelist */
58246   MemPage *pTrunk = 0;
58247   MemPage *pPrevTrunk = 0;
58248   Pgno mxPage;     /* Total size of the database file */
58249
58250   assert( sqlite3_mutex_held(pBt->mutex) );
58251   assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
58252   pPage1 = pBt->pPage1;
58253   mxPage = btreePagecount(pBt);
58254   /* EVIDENCE-OF: R-05119-02637 The 4-byte big-endian integer at offset 36
58255   ** stores stores the total number of pages on the freelist. */
58256   n = get4byte(&pPage1->aData[36]);
58257   testcase( n==mxPage-1 );
58258   if( n>=mxPage ){
58259     return SQLITE_CORRUPT_BKPT;
58260   }
58261   if( n>0 ){
58262     /* There are pages on the freelist.  Reuse one of those pages. */
58263     Pgno iTrunk;
58264     u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
58265     
58266     /* If eMode==BTALLOC_EXACT and a query of the pointer-map
58267     ** shows that the page 'nearby' is somewhere on the free-list, then
58268     ** the entire-list will be searched for that page.
58269     */
58270 #ifndef SQLITE_OMIT_AUTOVACUUM
58271     if( eMode==BTALLOC_EXACT ){
58272       if( nearby<=mxPage ){
58273         u8 eType;
58274         assert( nearby>0 );
58275         assert( pBt->autoVacuum );
58276         rc = ptrmapGet(pBt, nearby, &eType, 0);
58277         if( rc ) return rc;
58278         if( eType==PTRMAP_FREEPAGE ){
58279           searchList = 1;
58280         }
58281       }
58282     }else if( eMode==BTALLOC_LE ){
58283       searchList = 1;
58284     }
58285 #endif
58286
58287     /* Decrement the free-list count by 1. Set iTrunk to the index of the
58288     ** first free-list trunk page. iPrevTrunk is initially 1.
58289     */
58290     rc = sqlite3PagerWrite(pPage1->pDbPage);
58291     if( rc ) return rc;
58292     put4byte(&pPage1->aData[36], n-1);
58293
58294     /* The code within this loop is run only once if the 'searchList' variable
58295     ** is not true. Otherwise, it runs once for each trunk-page on the
58296     ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
58297     ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
58298     */
58299     do {
58300       pPrevTrunk = pTrunk;
58301       if( pPrevTrunk ){
58302         /* EVIDENCE-OF: R-01506-11053 The first integer on a freelist trunk page
58303         ** is the page number of the next freelist trunk page in the list or
58304         ** zero if this is the last freelist trunk page. */
58305         iTrunk = get4byte(&pPrevTrunk->aData[0]);
58306       }else{
58307         /* EVIDENCE-OF: R-59841-13798 The 4-byte big-endian integer at offset 32
58308         ** stores the page number of the first page of the freelist, or zero if
58309         ** the freelist is empty. */
58310         iTrunk = get4byte(&pPage1->aData[32]);
58311       }
58312       testcase( iTrunk==mxPage );
58313       if( iTrunk>mxPage ){
58314         rc = SQLITE_CORRUPT_BKPT;
58315       }else{
58316         rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
58317       }
58318       if( rc ){
58319         pTrunk = 0;
58320         goto end_allocate_page;
58321       }
58322       assert( pTrunk!=0 );
58323       assert( pTrunk->aData!=0 );
58324       /* EVIDENCE-OF: R-13523-04394 The second integer on a freelist trunk page
58325       ** is the number of leaf page pointers to follow. */
58326       k = get4byte(&pTrunk->aData[4]);
58327       if( k==0 && !searchList ){
58328         /* The trunk has no leaves and the list is not being searched. 
58329         ** So extract the trunk page itself and use it as the newly 
58330         ** allocated page */
58331         assert( pPrevTrunk==0 );
58332         rc = sqlite3PagerWrite(pTrunk->pDbPage);
58333         if( rc ){
58334           goto end_allocate_page;
58335         }
58336         *pPgno = iTrunk;
58337         memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
58338         *ppPage = pTrunk;
58339         pTrunk = 0;
58340         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
58341       }else if( k>(u32)(pBt->usableSize/4 - 2) ){
58342         /* Value of k is out of range.  Database corruption */
58343         rc = SQLITE_CORRUPT_BKPT;
58344         goto end_allocate_page;
58345 #ifndef SQLITE_OMIT_AUTOVACUUM
58346       }else if( searchList 
58347             && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE)) 
58348       ){
58349         /* The list is being searched and this trunk page is the page
58350         ** to allocate, regardless of whether it has leaves.
58351         */
58352         *pPgno = iTrunk;
58353         *ppPage = pTrunk;
58354         searchList = 0;
58355         rc = sqlite3PagerWrite(pTrunk->pDbPage);
58356         if( rc ){
58357           goto end_allocate_page;
58358         }
58359         if( k==0 ){
58360           if( !pPrevTrunk ){
58361             memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
58362           }else{
58363             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
58364             if( rc!=SQLITE_OK ){
58365               goto end_allocate_page;
58366             }
58367             memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
58368           }
58369         }else{
58370           /* The trunk page is required by the caller but it contains 
58371           ** pointers to free-list leaves. The first leaf becomes a trunk
58372           ** page in this case.
58373           */
58374           MemPage *pNewTrunk;
58375           Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
58376           if( iNewTrunk>mxPage ){ 
58377             rc = SQLITE_CORRUPT_BKPT;
58378             goto end_allocate_page;
58379           }
58380           testcase( iNewTrunk==mxPage );
58381           rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
58382           if( rc!=SQLITE_OK ){
58383             goto end_allocate_page;
58384           }
58385           rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
58386           if( rc!=SQLITE_OK ){
58387             releasePage(pNewTrunk);
58388             goto end_allocate_page;
58389           }
58390           memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
58391           put4byte(&pNewTrunk->aData[4], k-1);
58392           memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
58393           releasePage(pNewTrunk);
58394           if( !pPrevTrunk ){
58395             assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
58396             put4byte(&pPage1->aData[32], iNewTrunk);
58397           }else{
58398             rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
58399             if( rc ){
58400               goto end_allocate_page;
58401             }
58402             put4byte(&pPrevTrunk->aData[0], iNewTrunk);
58403           }
58404         }
58405         pTrunk = 0;
58406         TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
58407 #endif
58408       }else if( k>0 ){
58409         /* Extract a leaf from the trunk */
58410         u32 closest;
58411         Pgno iPage;
58412         unsigned char *aData = pTrunk->aData;
58413         if( nearby>0 ){
58414           u32 i;
58415           closest = 0;
58416           if( eMode==BTALLOC_LE ){
58417             for(i=0; i<k; i++){
58418               iPage = get4byte(&aData[8+i*4]);
58419               if( iPage<=nearby ){
58420                 closest = i;
58421                 break;
58422               }
58423             }
58424           }else{
58425             int dist;
58426             dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
58427             for(i=1; i<k; i++){
58428               int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
58429               if( d2<dist ){
58430                 closest = i;
58431                 dist = d2;
58432               }
58433             }
58434           }
58435         }else{
58436           closest = 0;
58437         }
58438
58439         iPage = get4byte(&aData[8+closest*4]);
58440         testcase( iPage==mxPage );
58441         if( iPage>mxPage ){
58442           rc = SQLITE_CORRUPT_BKPT;
58443           goto end_allocate_page;
58444         }
58445         testcase( iPage==mxPage );
58446         if( !searchList 
58447          || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE)) 
58448         ){
58449           int noContent;
58450           *pPgno = iPage;
58451           TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
58452                  ": %d more free pages\n",
58453                  *pPgno, closest+1, k, pTrunk->pgno, n-1));
58454           rc = sqlite3PagerWrite(pTrunk->pDbPage);
58455           if( rc ) goto end_allocate_page;
58456           if( closest<k-1 ){
58457             memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
58458           }
58459           put4byte(&aData[4], k-1);
58460           noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
58461           rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
58462           if( rc==SQLITE_OK ){
58463             rc = sqlite3PagerWrite((*ppPage)->pDbPage);
58464             if( rc!=SQLITE_OK ){
58465               releasePage(*ppPage);
58466             }
58467           }
58468           searchList = 0;
58469         }
58470       }
58471       releasePage(pPrevTrunk);
58472       pPrevTrunk = 0;
58473     }while( searchList );
58474   }else{
58475     /* There are no pages on the freelist, so append a new page to the
58476     ** database image.
58477     **
58478     ** Normally, new pages allocated by this block can be requested from the
58479     ** pager layer with the 'no-content' flag set. This prevents the pager
58480     ** from trying to read the pages content from disk. However, if the
58481     ** current transaction has already run one or more incremental-vacuum
58482     ** steps, then the page we are about to allocate may contain content
58483     ** that is required in the event of a rollback. In this case, do
58484     ** not set the no-content flag. This causes the pager to load and journal
58485     ** the current page content before overwriting it.
58486     **
58487     ** Note that the pager will not actually attempt to load or journal 
58488     ** content for any page that really does lie past the end of the database
58489     ** file on disk. So the effects of disabling the no-content optimization
58490     ** here are confined to those pages that lie between the end of the
58491     ** database image and the end of the database file.
58492     */
58493     int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
58494
58495     rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
58496     if( rc ) return rc;
58497     pBt->nPage++;
58498     if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
58499
58500 #ifndef SQLITE_OMIT_AUTOVACUUM
58501     if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
58502       /* If *pPgno refers to a pointer-map page, allocate two new pages
58503       ** at the end of the file instead of one. The first allocated page
58504       ** becomes a new pointer-map page, the second is used by the caller.
58505       */
58506       MemPage *pPg = 0;
58507       TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
58508       assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
58509       rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
58510       if( rc==SQLITE_OK ){
58511         rc = sqlite3PagerWrite(pPg->pDbPage);
58512         releasePage(pPg);
58513       }
58514       if( rc ) return rc;
58515       pBt->nPage++;
58516       if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
58517     }
58518 #endif
58519     put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
58520     *pPgno = pBt->nPage;
58521
58522     assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
58523     rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
58524     if( rc ) return rc;
58525     rc = sqlite3PagerWrite((*ppPage)->pDbPage);
58526     if( rc!=SQLITE_OK ){
58527       releasePage(*ppPage);
58528     }
58529     TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
58530   }
58531
58532   assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
58533
58534 end_allocate_page:
58535   releasePage(pTrunk);
58536   releasePage(pPrevTrunk);
58537   if( rc==SQLITE_OK ){
58538     if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
58539       releasePage(*ppPage);
58540       *ppPage = 0;
58541       return SQLITE_CORRUPT_BKPT;
58542     }
58543     (*ppPage)->isInit = 0;
58544   }else{
58545     *ppPage = 0;
58546   }
58547   assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
58548   return rc;
58549 }
58550
58551 /*
58552 ** This function is used to add page iPage to the database file free-list. 
58553 ** It is assumed that the page is not already a part of the free-list.
58554 **
58555 ** The value passed as the second argument to this function is optional.
58556 ** If the caller happens to have a pointer to the MemPage object 
58557 ** corresponding to page iPage handy, it may pass it as the second value. 
58558 ** Otherwise, it may pass NULL.
58559 **
58560 ** If a pointer to a MemPage object is passed as the second argument,
58561 ** its reference count is not altered by this function.
58562 */
58563 static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
58564   MemPage *pTrunk = 0;                /* Free-list trunk page */
58565   Pgno iTrunk = 0;                    /* Page number of free-list trunk page */ 
58566   MemPage *pPage1 = pBt->pPage1;      /* Local reference to page 1 */
58567   MemPage *pPage;                     /* Page being freed. May be NULL. */
58568   int rc;                             /* Return Code */
58569   int nFree;                          /* Initial number of pages on free-list */
58570
58571   assert( sqlite3_mutex_held(pBt->mutex) );
58572   assert( iPage>1 );
58573   assert( !pMemPage || pMemPage->pgno==iPage );
58574
58575   if( pMemPage ){
58576     pPage = pMemPage;
58577     sqlite3PagerRef(pPage->pDbPage);
58578   }else{
58579     pPage = btreePageLookup(pBt, iPage);
58580   }
58581
58582   /* Increment the free page count on pPage1 */
58583   rc = sqlite3PagerWrite(pPage1->pDbPage);
58584   if( rc ) goto freepage_out;
58585   nFree = get4byte(&pPage1->aData[36]);
58586   put4byte(&pPage1->aData[36], nFree+1);
58587
58588   if( pBt->btsFlags & BTS_SECURE_DELETE ){
58589     /* If the secure_delete option is enabled, then
58590     ** always fully overwrite deleted information with zeros.
58591     */
58592     if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
58593      ||            ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
58594     ){
58595       goto freepage_out;
58596     }
58597     memset(pPage->aData, 0, pPage->pBt->pageSize);
58598   }
58599
58600   /* If the database supports auto-vacuum, write an entry in the pointer-map
58601   ** to indicate that the page is free.
58602   */
58603   if( ISAUTOVACUUM ){
58604     ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
58605     if( rc ) goto freepage_out;
58606   }
58607
58608   /* Now manipulate the actual database free-list structure. There are two
58609   ** possibilities. If the free-list is currently empty, or if the first
58610   ** trunk page in the free-list is full, then this page will become a
58611   ** new free-list trunk page. Otherwise, it will become a leaf of the
58612   ** first trunk page in the current free-list. This block tests if it
58613   ** is possible to add the page as a new free-list leaf.
58614   */
58615   if( nFree!=0 ){
58616     u32 nLeaf;                /* Initial number of leaf cells on trunk page */
58617
58618     iTrunk = get4byte(&pPage1->aData[32]);
58619     rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
58620     if( rc!=SQLITE_OK ){
58621       goto freepage_out;
58622     }
58623
58624     nLeaf = get4byte(&pTrunk->aData[4]);
58625     assert( pBt->usableSize>32 );
58626     if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
58627       rc = SQLITE_CORRUPT_BKPT;
58628       goto freepage_out;
58629     }
58630     if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
58631       /* In this case there is room on the trunk page to insert the page
58632       ** being freed as a new leaf.
58633       **
58634       ** Note that the trunk page is not really full until it contains
58635       ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
58636       ** coded.  But due to a coding error in versions of SQLite prior to
58637       ** 3.6.0, databases with freelist trunk pages holding more than
58638       ** usableSize/4 - 8 entries will be reported as corrupt.  In order
58639       ** to maintain backwards compatibility with older versions of SQLite,
58640       ** we will continue to restrict the number of entries to usableSize/4 - 8
58641       ** for now.  At some point in the future (once everyone has upgraded
58642       ** to 3.6.0 or later) we should consider fixing the conditional above
58643       ** to read "usableSize/4-2" instead of "usableSize/4-8".
58644       **
58645       ** EVIDENCE-OF: R-19920-11576 However, newer versions of SQLite still
58646       ** avoid using the last six entries in the freelist trunk page array in
58647       ** order that database files created by newer versions of SQLite can be
58648       ** read by older versions of SQLite.
58649       */
58650       rc = sqlite3PagerWrite(pTrunk->pDbPage);
58651       if( rc==SQLITE_OK ){
58652         put4byte(&pTrunk->aData[4], nLeaf+1);
58653         put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
58654         if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
58655           sqlite3PagerDontWrite(pPage->pDbPage);
58656         }
58657         rc = btreeSetHasContent(pBt, iPage);
58658       }
58659       TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
58660       goto freepage_out;
58661     }
58662   }
58663
58664   /* If control flows to this point, then it was not possible to add the
58665   ** the page being freed as a leaf page of the first trunk in the free-list.
58666   ** Possibly because the free-list is empty, or possibly because the 
58667   ** first trunk in the free-list is full. Either way, the page being freed
58668   ** will become the new first trunk page in the free-list.
58669   */
58670   if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
58671     goto freepage_out;
58672   }
58673   rc = sqlite3PagerWrite(pPage->pDbPage);
58674   if( rc!=SQLITE_OK ){
58675     goto freepage_out;
58676   }
58677   put4byte(pPage->aData, iTrunk);
58678   put4byte(&pPage->aData[4], 0);
58679   put4byte(&pPage1->aData[32], iPage);
58680   TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
58681
58682 freepage_out:
58683   if( pPage ){
58684     pPage->isInit = 0;
58685   }
58686   releasePage(pPage);
58687   releasePage(pTrunk);
58688   return rc;
58689 }
58690 static void freePage(MemPage *pPage, int *pRC){
58691   if( (*pRC)==SQLITE_OK ){
58692     *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
58693   }
58694 }
58695
58696 /*
58697 ** Free any overflow pages associated with the given Cell.  Write the
58698 ** local Cell size (the number of bytes on the original page, omitting
58699 ** overflow) into *pnSize.
58700 */
58701 static int clearCell(
58702   MemPage *pPage,          /* The page that contains the Cell */
58703   unsigned char *pCell,    /* First byte of the Cell */
58704   u16 *pnSize              /* Write the size of the Cell here */
58705 ){
58706   BtShared *pBt = pPage->pBt;
58707   CellInfo info;
58708   Pgno ovflPgno;
58709   int rc;
58710   int nOvfl;
58711   u32 ovflPageSize;
58712
58713   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
58714   btreeParseCellPtr(pPage, pCell, &info);
58715   *pnSize = info.nSize;
58716   if( info.iOverflow==0 ){
58717     return SQLITE_OK;  /* No overflow pages. Return without doing anything */
58718   }
58719   if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
58720     return SQLITE_CORRUPT_BKPT;  /* Cell extends past end of page */
58721   }
58722   ovflPgno = get4byte(&pCell[info.iOverflow]);
58723   assert( pBt->usableSize > 4 );
58724   ovflPageSize = pBt->usableSize - 4;
58725   nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
58726   assert( ovflPgno==0 || nOvfl>0 );
58727   while( nOvfl-- ){
58728     Pgno iNext = 0;
58729     MemPage *pOvfl = 0;
58730     if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
58731       /* 0 is not a legal page number and page 1 cannot be an 
58732       ** overflow page. Therefore if ovflPgno<2 or past the end of the 
58733       ** file the database must be corrupt. */
58734       return SQLITE_CORRUPT_BKPT;
58735     }
58736     if( nOvfl ){
58737       rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
58738       if( rc ) return rc;
58739     }
58740
58741     if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
58742      && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
58743     ){
58744       /* There is no reason any cursor should have an outstanding reference 
58745       ** to an overflow page belonging to a cell that is being deleted/updated.
58746       ** So if there exists more than one reference to this page, then it 
58747       ** must not really be an overflow page and the database must be corrupt. 
58748       ** It is helpful to detect this before calling freePage2(), as 
58749       ** freePage2() may zero the page contents if secure-delete mode is
58750       ** enabled. If this 'overflow' page happens to be a page that the
58751       ** caller is iterating through or using in some other way, this
58752       ** can be problematic.
58753       */
58754       rc = SQLITE_CORRUPT_BKPT;
58755     }else{
58756       rc = freePage2(pBt, pOvfl, ovflPgno);
58757     }
58758
58759     if( pOvfl ){
58760       sqlite3PagerUnref(pOvfl->pDbPage);
58761     }
58762     if( rc ) return rc;
58763     ovflPgno = iNext;
58764   }
58765   return SQLITE_OK;
58766 }
58767
58768 /*
58769 ** Create the byte sequence used to represent a cell on page pPage
58770 ** and write that byte sequence into pCell[].  Overflow pages are
58771 ** allocated and filled in as necessary.  The calling procedure
58772 ** is responsible for making sure sufficient space has been allocated
58773 ** for pCell[].
58774 **
58775 ** Note that pCell does not necessary need to point to the pPage->aData
58776 ** area.  pCell might point to some temporary storage.  The cell will
58777 ** be constructed in this temporary area then copied into pPage->aData
58778 ** later.
58779 */
58780 static int fillInCell(
58781   MemPage *pPage,                /* The page that contains the cell */
58782   unsigned char *pCell,          /* Complete text of the cell */
58783   const void *pKey, i64 nKey,    /* The key */
58784   const void *pData,int nData,   /* The data */
58785   int nZero,                     /* Extra zero bytes to append to pData */
58786   int *pnSize                    /* Write cell size here */
58787 ){
58788   int nPayload;
58789   const u8 *pSrc;
58790   int nSrc, n, rc;
58791   int spaceLeft;
58792   MemPage *pOvfl = 0;
58793   MemPage *pToRelease = 0;
58794   unsigned char *pPrior;
58795   unsigned char *pPayload;
58796   BtShared *pBt = pPage->pBt;
58797   Pgno pgnoOvfl = 0;
58798   int nHeader;
58799
58800   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
58801
58802   /* pPage is not necessarily writeable since pCell might be auxiliary
58803   ** buffer space that is separate from the pPage buffer area */
58804   assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
58805             || sqlite3PagerIswriteable(pPage->pDbPage) );
58806
58807   /* Fill in the header. */
58808   nHeader = pPage->childPtrSize;
58809   nPayload = nData + nZero;
58810   if( pPage->intKeyLeaf ){
58811     nHeader += putVarint32(&pCell[nHeader], nPayload);
58812   }else{
58813     assert( nData==0 );
58814     assert( nZero==0 );
58815   }
58816   nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
58817   
58818   /* Fill in the payload size */
58819   if( pPage->intKey ){
58820     pSrc = pData;
58821     nSrc = nData;
58822     nData = 0;
58823   }else{ 
58824     if( NEVER(nKey>0x7fffffff || pKey==0) ){
58825       return SQLITE_CORRUPT_BKPT;
58826     }
58827     nPayload = (int)nKey;
58828     pSrc = pKey;
58829     nSrc = (int)nKey;
58830   }
58831   if( nPayload<=pPage->maxLocal ){
58832     n = nHeader + nPayload;
58833     testcase( n==3 );
58834     testcase( n==4 );
58835     if( n<4 ) n = 4;
58836     *pnSize = n;
58837     spaceLeft = nPayload;
58838     pPrior = pCell;
58839   }else{
58840     int mn = pPage->minLocal;
58841     n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
58842     testcase( n==pPage->maxLocal );
58843     testcase( n==pPage->maxLocal+1 );
58844     if( n > pPage->maxLocal ) n = mn;
58845     spaceLeft = n;
58846     *pnSize = n + nHeader + 4;
58847     pPrior = &pCell[nHeader+n];
58848   }
58849   pPayload = &pCell[nHeader];
58850
58851   /* At this point variables should be set as follows:
58852   **
58853   **   nPayload           Total payload size in bytes
58854   **   pPayload           Begin writing payload here
58855   **   spaceLeft          Space available at pPayload.  If nPayload>spaceLeft,
58856   **                      that means content must spill into overflow pages.
58857   **   *pnSize            Size of the local cell (not counting overflow pages)
58858   **   pPrior             Where to write the pgno of the first overflow page
58859   **
58860   ** Use a call to btreeParseCellPtr() to verify that the values above
58861   ** were computed correctly.
58862   */
58863 #if SQLITE_DEBUG
58864   {
58865     CellInfo info;
58866     btreeParseCellPtr(pPage, pCell, &info);
58867     assert( nHeader=(int)(info.pPayload - pCell) );
58868     assert( info.nKey==nKey );
58869     assert( *pnSize == info.nSize );
58870     assert( spaceLeft == info.nLocal );
58871     assert( pPrior == &pCell[info.iOverflow] );
58872   }
58873 #endif
58874
58875   /* Write the payload into the local Cell and any extra into overflow pages */
58876   while( nPayload>0 ){
58877     if( spaceLeft==0 ){
58878 #ifndef SQLITE_OMIT_AUTOVACUUM
58879       Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
58880       if( pBt->autoVacuum ){
58881         do{
58882           pgnoOvfl++;
58883         } while( 
58884           PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt) 
58885         );
58886       }
58887 #endif
58888       rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
58889 #ifndef SQLITE_OMIT_AUTOVACUUM
58890       /* If the database supports auto-vacuum, and the second or subsequent
58891       ** overflow page is being allocated, add an entry to the pointer-map
58892       ** for that page now. 
58893       **
58894       ** If this is the first overflow page, then write a partial entry 
58895       ** to the pointer-map. If we write nothing to this pointer-map slot,
58896       ** then the optimistic overflow chain processing in clearCell()
58897       ** may misinterpret the uninitialized values and delete the
58898       ** wrong pages from the database.
58899       */
58900       if( pBt->autoVacuum && rc==SQLITE_OK ){
58901         u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
58902         ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
58903         if( rc ){
58904           releasePage(pOvfl);
58905         }
58906       }
58907 #endif
58908       if( rc ){
58909         releasePage(pToRelease);
58910         return rc;
58911       }
58912
58913       /* If pToRelease is not zero than pPrior points into the data area
58914       ** of pToRelease.  Make sure pToRelease is still writeable. */
58915       assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
58916
58917       /* If pPrior is part of the data area of pPage, then make sure pPage
58918       ** is still writeable */
58919       assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
58920             || sqlite3PagerIswriteable(pPage->pDbPage) );
58921
58922       put4byte(pPrior, pgnoOvfl);
58923       releasePage(pToRelease);
58924       pToRelease = pOvfl;
58925       pPrior = pOvfl->aData;
58926       put4byte(pPrior, 0);
58927       pPayload = &pOvfl->aData[4];
58928       spaceLeft = pBt->usableSize - 4;
58929     }
58930     n = nPayload;
58931     if( n>spaceLeft ) n = spaceLeft;
58932
58933     /* If pToRelease is not zero than pPayload points into the data area
58934     ** of pToRelease.  Make sure pToRelease is still writeable. */
58935     assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
58936
58937     /* If pPayload is part of the data area of pPage, then make sure pPage
58938     ** is still writeable */
58939     assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
58940             || sqlite3PagerIswriteable(pPage->pDbPage) );
58941
58942     if( nSrc>0 ){
58943       if( n>nSrc ) n = nSrc;
58944       assert( pSrc );
58945       memcpy(pPayload, pSrc, n);
58946     }else{
58947       memset(pPayload, 0, n);
58948     }
58949     nPayload -= n;
58950     pPayload += n;
58951     pSrc += n;
58952     nSrc -= n;
58953     spaceLeft -= n;
58954     if( nSrc==0 ){
58955       nSrc = nData;
58956       pSrc = pData;
58957     }
58958   }
58959   releasePage(pToRelease);
58960   return SQLITE_OK;
58961 }
58962
58963 /*
58964 ** Remove the i-th cell from pPage.  This routine effects pPage only.
58965 ** The cell content is not freed or deallocated.  It is assumed that
58966 ** the cell content has been copied someplace else.  This routine just
58967 ** removes the reference to the cell from pPage.
58968 **
58969 ** "sz" must be the number of bytes in the cell.
58970 */
58971 static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
58972   u32 pc;         /* Offset to cell content of cell being deleted */
58973   u8 *data;       /* pPage->aData */
58974   u8 *ptr;        /* Used to move bytes around within data[] */
58975   int rc;         /* The return code */
58976   int hdr;        /* Beginning of the header.  0 most pages.  100 page 1 */
58977
58978   if( *pRC ) return;
58979
58980   assert( idx>=0 && idx<pPage->nCell );
58981   assert( sz==cellSize(pPage, idx) );
58982   assert( sqlite3PagerIswriteable(pPage->pDbPage) );
58983   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
58984   data = pPage->aData;
58985   ptr = &pPage->aCellIdx[2*idx];
58986   pc = get2byte(ptr);
58987   hdr = pPage->hdrOffset;
58988   testcase( pc==get2byte(&data[hdr+5]) );
58989   testcase( pc+sz==pPage->pBt->usableSize );
58990   if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
58991     *pRC = SQLITE_CORRUPT_BKPT;
58992     return;
58993   }
58994   rc = freeSpace(pPage, pc, sz);
58995   if( rc ){
58996     *pRC = rc;
58997     return;
58998   }
58999   pPage->nCell--;
59000   if( pPage->nCell==0 ){
59001     memset(&data[hdr+1], 0, 4);
59002     data[hdr+7] = 0;
59003     put2byte(&data[hdr+5], pPage->pBt->usableSize);
59004     pPage->nFree = pPage->pBt->usableSize - pPage->hdrOffset
59005                        - pPage->childPtrSize - 8;
59006   }else{
59007     memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
59008     put2byte(&data[hdr+3], pPage->nCell);
59009     pPage->nFree += 2;
59010   }
59011 }
59012
59013 /*
59014 ** Insert a new cell on pPage at cell index "i".  pCell points to the
59015 ** content of the cell.
59016 **
59017 ** If the cell content will fit on the page, then put it there.  If it
59018 ** will not fit, then make a copy of the cell content into pTemp if
59019 ** pTemp is not null.  Regardless of pTemp, allocate a new entry
59020 ** in pPage->apOvfl[] and make it point to the cell content (either
59021 ** in pTemp or the original pCell) and also record its index. 
59022 ** Allocating a new entry in pPage->aCell[] implies that 
59023 ** pPage->nOverflow is incremented.
59024 */
59025 static void insertCell(
59026   MemPage *pPage,   /* Page into which we are copying */
59027   int i,            /* New cell becomes the i-th cell of the page */
59028   u8 *pCell,        /* Content of the new cell */
59029   int sz,           /* Bytes of content in pCell */
59030   u8 *pTemp,        /* Temp storage space for pCell, if needed */
59031   Pgno iChild,      /* If non-zero, replace first 4 bytes with this value */
59032   int *pRC          /* Read and write return code from here */
59033 ){
59034   int idx = 0;      /* Where to write new cell content in data[] */
59035   int j;            /* Loop counter */
59036   int end;          /* First byte past the last cell pointer in data[] */
59037   int ins;          /* Index in data[] where new cell pointer is inserted */
59038   int cellOffset;   /* Address of first cell pointer in data[] */
59039   u8 *data;         /* The content of the whole page */
59040
59041   if( *pRC ) return;
59042
59043   assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
59044   assert( MX_CELL(pPage->pBt)<=10921 );
59045   assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
59046   assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
59047   assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
59048   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59049   /* The cell should normally be sized correctly.  However, when moving a
59050   ** malformed cell from a leaf page to an interior page, if the cell size
59051   ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
59052   ** might be less than 8 (leaf-size + pointer) on the interior node.  Hence
59053   ** the term after the || in the following assert(). */
59054   assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
59055   if( pPage->nOverflow || sz+2>pPage->nFree ){
59056     if( pTemp ){
59057       memcpy(pTemp, pCell, sz);
59058       pCell = pTemp;
59059     }
59060     if( iChild ){
59061       put4byte(pCell, iChild);
59062     }
59063     j = pPage->nOverflow++;
59064     assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
59065     pPage->apOvfl[j] = pCell;
59066     pPage->aiOvfl[j] = (u16)i;
59067   }else{
59068     int rc = sqlite3PagerWrite(pPage->pDbPage);
59069     if( rc!=SQLITE_OK ){
59070       *pRC = rc;
59071       return;
59072     }
59073     assert( sqlite3PagerIswriteable(pPage->pDbPage) );
59074     data = pPage->aData;
59075     cellOffset = pPage->cellOffset;
59076     end = cellOffset + 2*pPage->nCell;
59077     ins = cellOffset + 2*i;
59078     rc = allocateSpace(pPage, sz, &idx);
59079     if( rc ){ *pRC = rc; return; }
59080     /* The allocateSpace() routine guarantees the following two properties
59081     ** if it returns success */
59082     assert( idx >= end+2 );
59083     assert( idx+sz <= (int)pPage->pBt->usableSize );
59084     pPage->nCell++;
59085     pPage->nFree -= (u16)(2 + sz);
59086     memcpy(&data[idx], pCell, sz);
59087     if( iChild ){
59088       put4byte(&data[idx], iChild);
59089     }
59090     memmove(&data[ins+2], &data[ins], end-ins);
59091     put2byte(&data[ins], idx);
59092     put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
59093 #ifndef SQLITE_OMIT_AUTOVACUUM
59094     if( pPage->pBt->autoVacuum ){
59095       /* The cell may contain a pointer to an overflow page. If so, write
59096       ** the entry for the overflow page into the pointer map.
59097       */
59098       ptrmapPutOvflPtr(pPage, pCell, pRC);
59099     }
59100 #endif
59101   }
59102 }
59103
59104 /*
59105 ** Array apCell[] contains pointers to nCell b-tree page cells. The 
59106 ** szCell[] array contains the size in bytes of each cell. This function
59107 ** replaces the current contents of page pPg with the contents of the cell
59108 ** array.
59109 **
59110 ** Some of the cells in apCell[] may currently be stored in pPg. This
59111 ** function works around problems caused by this by making a copy of any 
59112 ** such cells before overwriting the page data.
59113 **
59114 ** The MemPage.nFree field is invalidated by this function. It is the 
59115 ** responsibility of the caller to set it correctly.
59116 */
59117 static void rebuildPage(
59118   MemPage *pPg,                   /* Edit this page */
59119   int nCell,                      /* Final number of cells on page */
59120   u8 **apCell,                    /* Array of cells */
59121   u16 *szCell                     /* Array of cell sizes */
59122 ){
59123   const int hdr = pPg->hdrOffset;          /* Offset of header on pPg */
59124   u8 * const aData = pPg->aData;           /* Pointer to data for pPg */
59125   const int usableSize = pPg->pBt->usableSize;
59126   u8 * const pEnd = &aData[usableSize];
59127   int i;
59128   u8 *pCellptr = pPg->aCellIdx;
59129   u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
59130   u8 *pData;
59131
59132   i = get2byte(&aData[hdr+5]);
59133   memcpy(&pTmp[i], &aData[i], usableSize - i);
59134
59135   pData = pEnd;
59136   for(i=0; i<nCell; i++){
59137     u8 *pCell = apCell[i];
59138     if( pCell>aData && pCell<pEnd ){
59139       pCell = &pTmp[pCell - aData];
59140     }
59141     pData -= szCell[i];
59142     memcpy(pData, pCell, szCell[i]);
59143     put2byte(pCellptr, (pData - aData));
59144     pCellptr += 2;
59145     assert( szCell[i]==cellSizePtr(pPg, pCell) );
59146   }
59147
59148   /* The pPg->nFree field is now set incorrectly. The caller will fix it. */
59149   pPg->nCell = nCell;
59150   pPg->nOverflow = 0;
59151
59152   put2byte(&aData[hdr+1], 0);
59153   put2byte(&aData[hdr+3], pPg->nCell);
59154   put2byte(&aData[hdr+5], pData - aData);
59155   aData[hdr+7] = 0x00;
59156 }
59157
59158 /*
59159 ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell
59160 ** contains the size in bytes of each such cell. This function attempts to 
59161 ** add the cells stored in the array to page pPg. If it cannot (because 
59162 ** the page needs to be defragmented before the cells will fit), non-zero
59163 ** is returned. Otherwise, if the cells are added successfully, zero is
59164 ** returned.
59165 **
59166 ** Argument pCellptr points to the first entry in the cell-pointer array
59167 ** (part of page pPg) to populate. After cell apCell[0] is written to the
59168 ** page body, a 16-bit offset is written to pCellptr. And so on, for each
59169 ** cell in the array. It is the responsibility of the caller to ensure
59170 ** that it is safe to overwrite this part of the cell-pointer array.
59171 **
59172 ** When this function is called, *ppData points to the start of the 
59173 ** content area on page pPg. If the size of the content area is extended,
59174 ** *ppData is updated to point to the new start of the content area
59175 ** before returning.
59176 **
59177 ** Finally, argument pBegin points to the byte immediately following the
59178 ** end of the space required by this page for the cell-pointer area (for
59179 ** all cells - not just those inserted by the current call). If the content
59180 ** area must be extended to before this point in order to accomodate all
59181 ** cells in apCell[], then the cells do not fit and non-zero is returned.
59182 */
59183 static int pageInsertArray(
59184   MemPage *pPg,                   /* Page to add cells to */
59185   u8 *pBegin,                     /* End of cell-pointer array */
59186   u8 **ppData,                    /* IN/OUT: Page content -area pointer */
59187   u8 *pCellptr,                   /* Pointer to cell-pointer area */
59188   int nCell,                      /* Number of cells to add to pPg */
59189   u8 **apCell,                    /* Array of cells */
59190   u16 *szCell                     /* Array of cell sizes */
59191 ){
59192   int i;
59193   u8 *aData = pPg->aData;
59194   u8 *pData = *ppData;
59195   const int bFreelist = aData[1] || aData[2];
59196   assert( CORRUPT_DB || pPg->hdrOffset==0 );    /* Never called on page 1 */
59197   for(i=0; i<nCell; i++){
59198     int sz = szCell[i];
59199     int rc;
59200     u8 *pSlot;
59201     if( bFreelist==0 || (pSlot = pageFindSlot(pPg, sz, &rc, 0))==0 ){
59202       pData -= sz;
59203       if( pData<pBegin ) return 1;
59204       pSlot = pData;
59205     }
59206     memcpy(pSlot, apCell[i], sz);
59207     put2byte(pCellptr, (pSlot - aData));
59208     pCellptr += 2;
59209   }
59210   *ppData = pData;
59211   return 0;
59212 }
59213
59214 /*
59215 ** Array apCell[] contains nCell pointers to b-tree cells. Array szCell 
59216 ** contains the size in bytes of each such cell. This function adds the
59217 ** space associated with each cell in the array that is currently stored 
59218 ** within the body of pPg to the pPg free-list. The cell-pointers and other
59219 ** fields of the page are not updated.
59220 **
59221 ** This function returns the total number of cells added to the free-list.
59222 */
59223 static int pageFreeArray(
59224   MemPage *pPg,                   /* Page to edit */
59225   int nCell,                      /* Cells to delete */
59226   u8 **apCell,                    /* Array of cells */
59227   u16 *szCell                     /* Array of cell sizes */
59228 ){
59229   u8 * const aData = pPg->aData;
59230   u8 * const pEnd = &aData[pPg->pBt->usableSize];
59231   u8 * const pStart = &aData[pPg->hdrOffset + 8 + pPg->childPtrSize];
59232   int nRet = 0;
59233   int i;
59234   u8 *pFree = 0;
59235   int szFree = 0;
59236
59237   for(i=0; i<nCell; i++){
59238     u8 *pCell = apCell[i];
59239     if( pCell>=pStart && pCell<pEnd ){
59240       int sz = szCell[i];
59241       if( pFree!=(pCell + sz) ){
59242         if( pFree ){
59243           assert( pFree>aData && (pFree - aData)<65536 );
59244           freeSpace(pPg, (u16)(pFree - aData), szFree);
59245         }
59246         pFree = pCell;
59247         szFree = sz;
59248         if( pFree+sz>pEnd ) return 0;
59249       }else{
59250         pFree = pCell;
59251         szFree += sz;
59252       }
59253       nRet++;
59254     }
59255   }
59256   if( pFree ){
59257     assert( pFree>aData && (pFree - aData)<65536 );
59258     freeSpace(pPg, (u16)(pFree - aData), szFree);
59259   }
59260   return nRet;
59261 }
59262
59263 /*
59264 ** apCell[] and szCell[] contains pointers to and sizes of all cells in the
59265 ** pages being balanced.  The current page, pPg, has pPg->nCell cells starting
59266 ** with apCell[iOld].  After balancing, this page should hold nNew cells
59267 ** starting at apCell[iNew].
59268 **
59269 ** This routine makes the necessary adjustments to pPg so that it contains
59270 ** the correct cells after being balanced.
59271 **
59272 ** The pPg->nFree field is invalid when this function returns. It is the
59273 ** responsibility of the caller to set it correctly.
59274 */
59275 static void editPage(
59276   MemPage *pPg,                   /* Edit this page */
59277   int iOld,                       /* Index of first cell currently on page */
59278   int iNew,                       /* Index of new first cell on page */
59279   int nNew,                       /* Final number of cells on page */
59280   u8 **apCell,                    /* Array of cells */
59281   u16 *szCell                     /* Array of cell sizes */
59282 ){
59283   u8 * const aData = pPg->aData;
59284   const int hdr = pPg->hdrOffset;
59285   u8 *pBegin = &pPg->aCellIdx[nNew * 2];
59286   int nCell = pPg->nCell;       /* Cells stored on pPg */
59287   u8 *pData;
59288   u8 *pCellptr;
59289   int i;
59290   int iOldEnd = iOld + pPg->nCell + pPg->nOverflow;
59291   int iNewEnd = iNew + nNew;
59292
59293 #ifdef SQLITE_DEBUG
59294   u8 *pTmp = sqlite3PagerTempSpace(pPg->pBt->pPager);
59295   memcpy(pTmp, aData, pPg->pBt->usableSize);
59296 #endif
59297
59298   /* Remove cells from the start and end of the page */
59299   if( iOld<iNew ){
59300     int nShift = pageFreeArray(
59301         pPg, iNew-iOld, &apCell[iOld], &szCell[iOld]
59302     );
59303     memmove(pPg->aCellIdx, &pPg->aCellIdx[nShift*2], nCell*2);
59304     nCell -= nShift;
59305   }
59306   if( iNewEnd < iOldEnd ){
59307     nCell -= pageFreeArray(
59308         pPg, iOldEnd-iNewEnd, &apCell[iNewEnd], &szCell[iNewEnd]
59309     );
59310   }
59311
59312   pData = &aData[get2byteNotZero(&aData[hdr+5])];
59313   if( pData<pBegin ) goto editpage_fail;
59314
59315   /* Add cells to the start of the page */
59316   if( iNew<iOld ){
59317     int nAdd = MIN(nNew,iOld-iNew);
59318     assert( (iOld-iNew)<nNew || nCell==0 || CORRUPT_DB );
59319     pCellptr = pPg->aCellIdx;
59320     memmove(&pCellptr[nAdd*2], pCellptr, nCell*2);
59321     if( pageInsertArray(
59322           pPg, pBegin, &pData, pCellptr,
59323           nAdd, &apCell[iNew], &szCell[iNew]
59324     ) ) goto editpage_fail;
59325     nCell += nAdd;
59326   }
59327
59328   /* Add any overflow cells */
59329   for(i=0; i<pPg->nOverflow; i++){
59330     int iCell = (iOld + pPg->aiOvfl[i]) - iNew;
59331     if( iCell>=0 && iCell<nNew ){
59332       pCellptr = &pPg->aCellIdx[iCell * 2];
59333       memmove(&pCellptr[2], pCellptr, (nCell - iCell) * 2);
59334       nCell++;
59335       if( pageInsertArray(
59336             pPg, pBegin, &pData, pCellptr,
59337             1, &apCell[iCell + iNew], &szCell[iCell + iNew]
59338       ) ) goto editpage_fail;
59339     }
59340   }
59341
59342   /* Append cells to the end of the page */
59343   pCellptr = &pPg->aCellIdx[nCell*2];
59344   if( pageInsertArray(
59345         pPg, pBegin, &pData, pCellptr,
59346         nNew-nCell, &apCell[iNew+nCell], &szCell[iNew+nCell]
59347   ) ) goto editpage_fail;
59348
59349   pPg->nCell = nNew;
59350   pPg->nOverflow = 0;
59351
59352   put2byte(&aData[hdr+3], pPg->nCell);
59353   put2byte(&aData[hdr+5], pData - aData);
59354
59355 #ifdef SQLITE_DEBUG
59356   for(i=0; i<nNew && !CORRUPT_DB; i++){
59357     u8 *pCell = apCell[i+iNew];
59358     int iOff = get2byte(&pPg->aCellIdx[i*2]);
59359     if( pCell>=aData && pCell<&aData[pPg->pBt->usableSize] ){
59360       pCell = &pTmp[pCell - aData];
59361     }
59362     assert( 0==memcmp(pCell, &aData[iOff], szCell[i+iNew]) );
59363   }
59364 #endif
59365
59366   return;
59367  editpage_fail:
59368   /* Unable to edit this page. Rebuild it from scratch instead. */
59369   rebuildPage(pPg, nNew, &apCell[iNew], &szCell[iNew]);
59370 }
59371
59372 /*
59373 ** The following parameters determine how many adjacent pages get involved
59374 ** in a balancing operation.  NN is the number of neighbors on either side
59375 ** of the page that participate in the balancing operation.  NB is the
59376 ** total number of pages that participate, including the target page and
59377 ** NN neighbors on either side.
59378 **
59379 ** The minimum value of NN is 1 (of course).  Increasing NN above 1
59380 ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
59381 ** in exchange for a larger degradation in INSERT and UPDATE performance.
59382 ** The value of NN appears to give the best results overall.
59383 */
59384 #define NN 1             /* Number of neighbors on either side of pPage */
59385 #define NB (NN*2+1)      /* Total pages involved in the balance */
59386
59387
59388 #ifndef SQLITE_OMIT_QUICKBALANCE
59389 /*
59390 ** This version of balance() handles the common special case where
59391 ** a new entry is being inserted on the extreme right-end of the
59392 ** tree, in other words, when the new entry will become the largest
59393 ** entry in the tree.
59394 **
59395 ** Instead of trying to balance the 3 right-most leaf pages, just add
59396 ** a new page to the right-hand side and put the one new entry in
59397 ** that page.  This leaves the right side of the tree somewhat
59398 ** unbalanced.  But odds are that we will be inserting new entries
59399 ** at the end soon afterwards so the nearly empty page will quickly
59400 ** fill up.  On average.
59401 **
59402 ** pPage is the leaf page which is the right-most page in the tree.
59403 ** pParent is its parent.  pPage must have a single overflow entry
59404 ** which is also the right-most entry on the page.
59405 **
59406 ** The pSpace buffer is used to store a temporary copy of the divider
59407 ** cell that will be inserted into pParent. Such a cell consists of a 4
59408 ** byte page number followed by a variable length integer. In other
59409 ** words, at most 13 bytes. Hence the pSpace buffer must be at
59410 ** least 13 bytes in size.
59411 */
59412 static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
59413   BtShared *const pBt = pPage->pBt;    /* B-Tree Database */
59414   MemPage *pNew;                       /* Newly allocated page */
59415   int rc;                              /* Return Code */
59416   Pgno pgnoNew;                        /* Page number of pNew */
59417
59418   assert( sqlite3_mutex_held(pPage->pBt->mutex) );
59419   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
59420   assert( pPage->nOverflow==1 );
59421
59422   /* This error condition is now caught prior to reaching this function */
59423   if( NEVER(pPage->nCell==0) ) return SQLITE_CORRUPT_BKPT;
59424
59425   /* Allocate a new page. This page will become the right-sibling of 
59426   ** pPage. Make the parent page writable, so that the new divider cell
59427   ** may be inserted. If both these operations are successful, proceed.
59428   */
59429   rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
59430
59431   if( rc==SQLITE_OK ){
59432
59433     u8 *pOut = &pSpace[4];
59434     u8 *pCell = pPage->apOvfl[0];
59435     u16 szCell = cellSizePtr(pPage, pCell);
59436     u8 *pStop;
59437
59438     assert( sqlite3PagerIswriteable(pNew->pDbPage) );
59439     assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
59440     zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
59441     rebuildPage(pNew, 1, &pCell, &szCell);
59442     pNew->nFree = pBt->usableSize - pNew->cellOffset - 2 - szCell;
59443
59444     /* If this is an auto-vacuum database, update the pointer map
59445     ** with entries for the new page, and any pointer from the 
59446     ** cell on the page to an overflow page. If either of these
59447     ** operations fails, the return code is set, but the contents
59448     ** of the parent page are still manipulated by thh code below.
59449     ** That is Ok, at this point the parent page is guaranteed to
59450     ** be marked as dirty. Returning an error code will cause a
59451     ** rollback, undoing any changes made to the parent page.
59452     */
59453     if( ISAUTOVACUUM ){
59454       ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
59455       if( szCell>pNew->minLocal ){
59456         ptrmapPutOvflPtr(pNew, pCell, &rc);
59457       }
59458     }
59459   
59460     /* Create a divider cell to insert into pParent. The divider cell
59461     ** consists of a 4-byte page number (the page number of pPage) and
59462     ** a variable length key value (which must be the same value as the
59463     ** largest key on pPage).
59464     **
59465     ** To find the largest key value on pPage, first find the right-most 
59466     ** cell on pPage. The first two fields of this cell are the 
59467     ** record-length (a variable length integer at most 32-bits in size)
59468     ** and the key value (a variable length integer, may have any value).
59469     ** The first of the while(...) loops below skips over the record-length
59470     ** field. The second while(...) loop copies the key value from the
59471     ** cell on pPage into the pSpace buffer.
59472     */
59473     pCell = findCell(pPage, pPage->nCell-1);
59474     pStop = &pCell[9];
59475     while( (*(pCell++)&0x80) && pCell<pStop );
59476     pStop = &pCell[9];
59477     while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
59478
59479     /* Insert the new divider cell into pParent. */
59480     insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
59481                0, pPage->pgno, &rc);
59482
59483     /* Set the right-child pointer of pParent to point to the new page. */
59484     put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
59485   
59486     /* Release the reference to the new page. */
59487     releasePage(pNew);
59488   }
59489
59490   return rc;
59491 }
59492 #endif /* SQLITE_OMIT_QUICKBALANCE */
59493
59494 #if 0
59495 /*
59496 ** This function does not contribute anything to the operation of SQLite.
59497 ** it is sometimes activated temporarily while debugging code responsible 
59498 ** for setting pointer-map entries.
59499 */
59500 static int ptrmapCheckPages(MemPage **apPage, int nPage){
59501   int i, j;
59502   for(i=0; i<nPage; i++){
59503     Pgno n;
59504     u8 e;
59505     MemPage *pPage = apPage[i];
59506     BtShared *pBt = pPage->pBt;
59507     assert( pPage->isInit );
59508
59509     for(j=0; j<pPage->nCell; j++){
59510       CellInfo info;
59511       u8 *z;
59512      
59513       z = findCell(pPage, j);
59514       btreeParseCellPtr(pPage, z, &info);
59515       if( info.iOverflow ){
59516         Pgno ovfl = get4byte(&z[info.iOverflow]);
59517         ptrmapGet(pBt, ovfl, &e, &n);
59518         assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
59519       }
59520       if( !pPage->leaf ){
59521         Pgno child = get4byte(z);
59522         ptrmapGet(pBt, child, &e, &n);
59523         assert( n==pPage->pgno && e==PTRMAP_BTREE );
59524       }
59525     }
59526     if( !pPage->leaf ){
59527       Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
59528       ptrmapGet(pBt, child, &e, &n);
59529       assert( n==pPage->pgno && e==PTRMAP_BTREE );
59530     }
59531   }
59532   return 1;
59533 }
59534 #endif
59535
59536 /*
59537 ** This function is used to copy the contents of the b-tree node stored 
59538 ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
59539 ** the pointer-map entries for each child page are updated so that the
59540 ** parent page stored in the pointer map is page pTo. If pFrom contained
59541 ** any cells with overflow page pointers, then the corresponding pointer
59542 ** map entries are also updated so that the parent page is page pTo.
59543 **
59544 ** If pFrom is currently carrying any overflow cells (entries in the
59545 ** MemPage.apOvfl[] array), they are not copied to pTo. 
59546 **
59547 ** Before returning, page pTo is reinitialized using btreeInitPage().
59548 **
59549 ** The performance of this function is not critical. It is only used by 
59550 ** the balance_shallower() and balance_deeper() procedures, neither of
59551 ** which are called often under normal circumstances.
59552 */
59553 static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
59554   if( (*pRC)==SQLITE_OK ){
59555     BtShared * const pBt = pFrom->pBt;
59556     u8 * const aFrom = pFrom->aData;
59557     u8 * const aTo = pTo->aData;
59558     int const iFromHdr = pFrom->hdrOffset;
59559     int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
59560     int rc;
59561     int iData;
59562   
59563   
59564     assert( pFrom->isInit );
59565     assert( pFrom->nFree>=iToHdr );
59566     assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
59567   
59568     /* Copy the b-tree node content from page pFrom to page pTo. */
59569     iData = get2byte(&aFrom[iFromHdr+5]);
59570     memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
59571     memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
59572   
59573     /* Reinitialize page pTo so that the contents of the MemPage structure
59574     ** match the new data. The initialization of pTo can actually fail under
59575     ** fairly obscure circumstances, even though it is a copy of initialized 
59576     ** page pFrom.
59577     */
59578     pTo->isInit = 0;
59579     rc = btreeInitPage(pTo);
59580     if( rc!=SQLITE_OK ){
59581       *pRC = rc;
59582       return;
59583     }
59584   
59585     /* If this is an auto-vacuum database, update the pointer-map entries
59586     ** for any b-tree or overflow pages that pTo now contains the pointers to.
59587     */
59588     if( ISAUTOVACUUM ){
59589       *pRC = setChildPtrmaps(pTo);
59590     }
59591   }
59592 }
59593
59594 /*
59595 ** This routine redistributes cells on the iParentIdx'th child of pParent
59596 ** (hereafter "the page") and up to 2 siblings so that all pages have about the
59597 ** same amount of free space. Usually a single sibling on either side of the
59598 ** page are used in the balancing, though both siblings might come from one
59599 ** side if the page is the first or last child of its parent. If the page 
59600 ** has fewer than 2 siblings (something which can only happen if the page
59601 ** is a root page or a child of a root page) then all available siblings
59602 ** participate in the balancing.
59603 **
59604 ** The number of siblings of the page might be increased or decreased by 
59605 ** one or two in an effort to keep pages nearly full but not over full. 
59606 **
59607 ** Note that when this routine is called, some of the cells on the page
59608 ** might not actually be stored in MemPage.aData[]. This can happen
59609 ** if the page is overfull. This routine ensures that all cells allocated
59610 ** to the page and its siblings fit into MemPage.aData[] before returning.
59611 **
59612 ** In the course of balancing the page and its siblings, cells may be
59613 ** inserted into or removed from the parent page (pParent). Doing so
59614 ** may cause the parent page to become overfull or underfull. If this
59615 ** happens, it is the responsibility of the caller to invoke the correct
59616 ** balancing routine to fix this problem (see the balance() routine). 
59617 **
59618 ** If this routine fails for any reason, it might leave the database
59619 ** in a corrupted state. So if this routine fails, the database should
59620 ** be rolled back.
59621 **
59622 ** The third argument to this function, aOvflSpace, is a pointer to a
59623 ** buffer big enough to hold one page. If while inserting cells into the parent
59624 ** page (pParent) the parent page becomes overfull, this buffer is
59625 ** used to store the parent's overflow cells. Because this function inserts
59626 ** a maximum of four divider cells into the parent page, and the maximum
59627 ** size of a cell stored within an internal node is always less than 1/4
59628 ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
59629 ** enough for all overflow cells.
59630 **
59631 ** If aOvflSpace is set to a null pointer, this function returns 
59632 ** SQLITE_NOMEM.
59633 */
59634 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
59635 #pragma optimize("", off)
59636 #endif
59637 static int balance_nonroot(
59638   MemPage *pParent,               /* Parent page of siblings being balanced */
59639   int iParentIdx,                 /* Index of "the page" in pParent */
59640   u8 *aOvflSpace,                 /* page-size bytes of space for parent ovfl */
59641   int isRoot,                     /* True if pParent is a root-page */
59642   int bBulk                       /* True if this call is part of a bulk load */
59643 ){
59644   BtShared *pBt;               /* The whole database */
59645   int nCell = 0;               /* Number of cells in apCell[] */
59646   int nMaxCells = 0;           /* Allocated size of apCell, szCell, aFrom. */
59647   int nNew = 0;                /* Number of pages in apNew[] */
59648   int nOld;                    /* Number of pages in apOld[] */
59649   int i, j, k;                 /* Loop counters */
59650   int nxDiv;                   /* Next divider slot in pParent->aCell[] */
59651   int rc = SQLITE_OK;          /* The return code */
59652   u16 leafCorrection;          /* 4 if pPage is a leaf.  0 if not */
59653   int leafData;                /* True if pPage is a leaf of a LEAFDATA tree */
59654   int usableSpace;             /* Bytes in pPage beyond the header */
59655   int pageFlags;               /* Value of pPage->aData[0] */
59656   int subtotal;                /* Subtotal of bytes in cells on one page */
59657   int iSpace1 = 0;             /* First unused byte of aSpace1[] */
59658   int iOvflSpace = 0;          /* First unused byte of aOvflSpace[] */
59659   int szScratch;               /* Size of scratch memory requested */
59660   MemPage *apOld[NB];          /* pPage and up to two siblings */
59661   MemPage *apNew[NB+2];        /* pPage and up to NB siblings after balancing */
59662   u8 *pRight;                  /* Location in parent of right-sibling pointer */
59663   u8 *apDiv[NB-1];             /* Divider cells in pParent */
59664   int cntNew[NB+2];            /* Index in aCell[] of cell after i-th page */
59665   int cntOld[NB+2];            /* Old index in aCell[] after i-th page */
59666   int szNew[NB+2];             /* Combined size of cells placed on i-th page */
59667   u8 **apCell = 0;             /* All cells begin balanced */
59668   u16 *szCell;                 /* Local size of all cells in apCell[] */
59669   u8 *aSpace1;                 /* Space for copies of dividers cells */
59670   Pgno pgno;                   /* Temp var to store a page number in */
59671   u8 abDone[NB+2];             /* True after i'th new page is populated */
59672   Pgno aPgno[NB+2];            /* Page numbers of new pages before shuffling */
59673   Pgno aPgOrder[NB+2];         /* Copy of aPgno[] used for sorting pages */
59674   u16 aPgFlags[NB+2];          /* flags field of new pages before shuffling */
59675
59676   memset(abDone, 0, sizeof(abDone));
59677   pBt = pParent->pBt;
59678   assert( sqlite3_mutex_held(pBt->mutex) );
59679   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
59680
59681 #if 0
59682   TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
59683 #endif
59684
59685   /* At this point pParent may have at most one overflow cell. And if
59686   ** this overflow cell is present, it must be the cell with 
59687   ** index iParentIdx. This scenario comes about when this function
59688   ** is called (indirectly) from sqlite3BtreeDelete().
59689   */
59690   assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
59691   assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
59692
59693   if( !aOvflSpace ){
59694     return SQLITE_NOMEM;
59695   }
59696
59697   /* Find the sibling pages to balance. Also locate the cells in pParent 
59698   ** that divide the siblings. An attempt is made to find NN siblings on 
59699   ** either side of pPage. More siblings are taken from one side, however, 
59700   ** if there are fewer than NN siblings on the other side. If pParent
59701   ** has NB or fewer children then all children of pParent are taken.  
59702   **
59703   ** This loop also drops the divider cells from the parent page. This
59704   ** way, the remainder of the function does not have to deal with any
59705   ** overflow cells in the parent page, since if any existed they will
59706   ** have already been removed.
59707   */
59708   i = pParent->nOverflow + pParent->nCell;
59709   if( i<2 ){
59710     nxDiv = 0;
59711   }else{
59712     assert( bBulk==0 || bBulk==1 );
59713     if( iParentIdx==0 ){                 
59714       nxDiv = 0;
59715     }else if( iParentIdx==i ){
59716       nxDiv = i-2+bBulk;
59717     }else{
59718       assert( bBulk==0 );
59719       nxDiv = iParentIdx-1;
59720     }
59721     i = 2-bBulk;
59722   }
59723   nOld = i+1;
59724   if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
59725     pRight = &pParent->aData[pParent->hdrOffset+8];
59726   }else{
59727     pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
59728   }
59729   pgno = get4byte(pRight);
59730   while( 1 ){
59731     rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
59732     if( rc ){
59733       memset(apOld, 0, (i+1)*sizeof(MemPage*));
59734       goto balance_cleanup;
59735     }
59736     nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
59737     if( (i--)==0 ) break;
59738
59739     if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
59740       apDiv[i] = pParent->apOvfl[0];
59741       pgno = get4byte(apDiv[i]);
59742       szNew[i] = cellSizePtr(pParent, apDiv[i]);
59743       pParent->nOverflow = 0;
59744     }else{
59745       apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
59746       pgno = get4byte(apDiv[i]);
59747       szNew[i] = cellSizePtr(pParent, apDiv[i]);
59748
59749       /* Drop the cell from the parent page. apDiv[i] still points to
59750       ** the cell within the parent, even though it has been dropped.
59751       ** This is safe because dropping a cell only overwrites the first
59752       ** four bytes of it, and this function does not need the first
59753       ** four bytes of the divider cell. So the pointer is safe to use
59754       ** later on.  
59755       **
59756       ** But not if we are in secure-delete mode. In secure-delete mode,
59757       ** the dropCell() routine will overwrite the entire cell with zeroes.
59758       ** In this case, temporarily copy the cell into the aOvflSpace[]
59759       ** buffer. It will be copied out again as soon as the aSpace[] buffer
59760       ** is allocated.  */
59761       if( pBt->btsFlags & BTS_SECURE_DELETE ){
59762         int iOff;
59763
59764         iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
59765         if( (iOff+szNew[i])>(int)pBt->usableSize ){
59766           rc = SQLITE_CORRUPT_BKPT;
59767           memset(apOld, 0, (i+1)*sizeof(MemPage*));
59768           goto balance_cleanup;
59769         }else{
59770           memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
59771           apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
59772         }
59773       }
59774       dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
59775     }
59776   }
59777
59778   /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
59779   ** alignment */
59780   nMaxCells = (nMaxCells + 3)&~3;
59781
59782   /*
59783   ** Allocate space for memory structures
59784   */
59785   szScratch =
59786        nMaxCells*sizeof(u8*)                       /* apCell */
59787      + nMaxCells*sizeof(u16)                       /* szCell */
59788      + pBt->pageSize;                              /* aSpace1 */
59789
59790   /* EVIDENCE-OF: R-28375-38319 SQLite will never request a scratch buffer
59791   ** that is more than 6 times the database page size. */
59792   assert( szScratch<=6*(int)pBt->pageSize );
59793   apCell = sqlite3ScratchMalloc( szScratch ); 
59794   if( apCell==0 ){
59795     rc = SQLITE_NOMEM;
59796     goto balance_cleanup;
59797   }
59798   szCell = (u16*)&apCell[nMaxCells];
59799   aSpace1 = (u8*)&szCell[nMaxCells];
59800   assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
59801
59802   /*
59803   ** Load pointers to all cells on sibling pages and the divider cells
59804   ** into the local apCell[] array.  Make copies of the divider cells
59805   ** into space obtained from aSpace1[]. The divider cells have already
59806   ** been removed from pParent.
59807   **
59808   ** If the siblings are on leaf pages, then the child pointers of the
59809   ** divider cells are stripped from the cells before they are copied
59810   ** into aSpace1[].  In this way, all cells in apCell[] are without
59811   ** child pointers.  If siblings are not leaves, then all cell in
59812   ** apCell[] include child pointers.  Either way, all cells in apCell[]
59813   ** are alike.
59814   **
59815   ** leafCorrection:  4 if pPage is a leaf.  0 if pPage is not a leaf.
59816   **       leafData:  1 if pPage holds key+data and pParent holds only keys.
59817   */
59818   leafCorrection = apOld[0]->leaf*4;
59819   leafData = apOld[0]->intKeyLeaf;
59820   for(i=0; i<nOld; i++){
59821     int limit;
59822     MemPage *pOld = apOld[i];
59823
59824     limit = pOld->nCell+pOld->nOverflow;
59825     if( pOld->nOverflow>0 ){
59826       for(j=0; j<limit; j++){
59827         assert( nCell<nMaxCells );
59828         apCell[nCell] = findOverflowCell(pOld, j);
59829         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
59830         nCell++;
59831       }
59832     }else{
59833       u8 *aData = pOld->aData;
59834       u16 maskPage = pOld->maskPage;
59835       u16 cellOffset = pOld->cellOffset;
59836       for(j=0; j<limit; j++){
59837         assert( nCell<nMaxCells );
59838         apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
59839         szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
59840         nCell++;
59841       }
59842     }       
59843     cntOld[i] = nCell;
59844     if( i<nOld-1 && !leafData){
59845       u16 sz = (u16)szNew[i];
59846       u8 *pTemp;
59847       assert( nCell<nMaxCells );
59848       szCell[nCell] = sz;
59849       pTemp = &aSpace1[iSpace1];
59850       iSpace1 += sz;
59851       assert( sz<=pBt->maxLocal+23 );
59852       assert( iSpace1 <= (int)pBt->pageSize );
59853       memcpy(pTemp, apDiv[i], sz);
59854       apCell[nCell] = pTemp+leafCorrection;
59855       assert( leafCorrection==0 || leafCorrection==4 );
59856       szCell[nCell] = szCell[nCell] - leafCorrection;
59857       if( !pOld->leaf ){
59858         assert( leafCorrection==0 );
59859         assert( pOld->hdrOffset==0 );
59860         /* The right pointer of the child page pOld becomes the left
59861         ** pointer of the divider cell */
59862         memcpy(apCell[nCell], &pOld->aData[8], 4);
59863       }else{
59864         assert( leafCorrection==4 );
59865         if( szCell[nCell]<4 ){
59866           /* Do not allow any cells smaller than 4 bytes. If a smaller cell
59867           ** does exist, pad it with 0x00 bytes. */
59868           assert( szCell[nCell]==3 );
59869           assert( apCell[nCell]==&aSpace1[iSpace1-3] );
59870           aSpace1[iSpace1++] = 0x00;
59871           szCell[nCell] = 4;
59872         }
59873       }
59874       nCell++;
59875     }
59876   }
59877
59878   /*
59879   ** Figure out the number of pages needed to hold all nCell cells.
59880   ** Store this number in "k".  Also compute szNew[] which is the total
59881   ** size of all cells on the i-th page and cntNew[] which is the index
59882   ** in apCell[] of the cell that divides page i from page i+1.  
59883   ** cntNew[k] should equal nCell.
59884   **
59885   ** Values computed by this block:
59886   **
59887   **           k: The total number of sibling pages
59888   **    szNew[i]: Spaced used on the i-th sibling page.
59889   **   cntNew[i]: Index in apCell[] and szCell[] for the first cell to
59890   **              the right of the i-th sibling page.
59891   ** usableSpace: Number of bytes of space available on each sibling.
59892   ** 
59893   */
59894   usableSpace = pBt->usableSize - 12 + leafCorrection;
59895   for(subtotal=k=i=0; i<nCell; i++){
59896     assert( i<nMaxCells );
59897     subtotal += szCell[i] + 2;
59898     if( subtotal > usableSpace ){
59899       szNew[k] = subtotal - szCell[i] - 2;
59900       cntNew[k] = i;
59901       if( leafData ){ i--; }
59902       subtotal = 0;
59903       k++;
59904       if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
59905     }
59906   }
59907   szNew[k] = subtotal;
59908   cntNew[k] = nCell;
59909   k++;
59910
59911   /*
59912   ** The packing computed by the previous block is biased toward the siblings
59913   ** on the left side (siblings with smaller keys). The left siblings are
59914   ** always nearly full, while the right-most sibling might be nearly empty.
59915   ** The next block of code attempts to adjust the packing of siblings to
59916   ** get a better balance.
59917   **
59918   ** This adjustment is more than an optimization.  The packing above might
59919   ** be so out of balance as to be illegal.  For example, the right-most
59920   ** sibling might be completely empty.  This adjustment is not optional.
59921   */
59922   for(i=k-1; i>0; i--){
59923     int szRight = szNew[i];  /* Size of sibling on the right */
59924     int szLeft = szNew[i-1]; /* Size of sibling on the left */
59925     int r;              /* Index of right-most cell in left sibling */
59926     int d;              /* Index of first cell to the left of right sibling */
59927
59928     r = cntNew[i-1] - 1;
59929     d = r + 1 - leafData;
59930     assert( d<nMaxCells );
59931     assert( r<nMaxCells );
59932     while( szRight==0 
59933        || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2)) 
59934     ){
59935       szRight += szCell[d] + 2;
59936       szLeft -= szCell[r] + 2;
59937       cntNew[i-1]--;
59938       r = cntNew[i-1] - 1;
59939       d = r + 1 - leafData;
59940     }
59941     szNew[i] = szRight;
59942     szNew[i-1] = szLeft;
59943   }
59944
59945   /* Sanity check:  For a non-corrupt database file one of the follwing
59946   ** must be true:
59947   **    (1) We found one or more cells (cntNew[0])>0), or
59948   **    (2) pPage is a virtual root page.  A virtual root page is when
59949   **        the real root page is page 1 and we are the only child of
59950   **        that page.
59951   */
59952   assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) || CORRUPT_DB);
59953   TRACE(("BALANCE: old: %d(nc=%d) %d(nc=%d) %d(nc=%d)\n",
59954     apOld[0]->pgno, apOld[0]->nCell,
59955     nOld>=2 ? apOld[1]->pgno : 0, nOld>=2 ? apOld[1]->nCell : 0,
59956     nOld>=3 ? apOld[2]->pgno : 0, nOld>=3 ? apOld[2]->nCell : 0
59957   ));
59958
59959   /*
59960   ** Allocate k new pages.  Reuse old pages where possible.
59961   */
59962   if( apOld[0]->pgno<=1 ){
59963     rc = SQLITE_CORRUPT_BKPT;
59964     goto balance_cleanup;
59965   }
59966   pageFlags = apOld[0]->aData[0];
59967   for(i=0; i<k; i++){
59968     MemPage *pNew;
59969     if( i<nOld ){
59970       pNew = apNew[i] = apOld[i];
59971       apOld[i] = 0;
59972       rc = sqlite3PagerWrite(pNew->pDbPage);
59973       nNew++;
59974       if( rc ) goto balance_cleanup;
59975     }else{
59976       assert( i>0 );
59977       rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
59978       if( rc ) goto balance_cleanup;
59979       zeroPage(pNew, pageFlags);
59980       apNew[i] = pNew;
59981       nNew++;
59982       cntOld[i] = nCell;
59983
59984       /* Set the pointer-map entry for the new sibling page. */
59985       if( ISAUTOVACUUM ){
59986         ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
59987         if( rc!=SQLITE_OK ){
59988           goto balance_cleanup;
59989         }
59990       }
59991     }
59992   }
59993
59994   /*
59995   ** Reassign page numbers so that the new pages are in ascending order. 
59996   ** This helps to keep entries in the disk file in order so that a scan
59997   ** of the table is closer to a linear scan through the file. That in turn 
59998   ** helps the operating system to deliver pages from the disk more rapidly.
59999   **
60000   ** An O(n^2) insertion sort algorithm is used, but since n is never more 
60001   ** than (NB+2) (a small constant), that should not be a problem.
60002   **
60003   ** When NB==3, this one optimization makes the database about 25% faster 
60004   ** for large insertions and deletions.
60005   */
60006   for(i=0; i<nNew; i++){
60007     aPgOrder[i] = aPgno[i] = apNew[i]->pgno;
60008     aPgFlags[i] = apNew[i]->pDbPage->flags;
60009     for(j=0; j<i; j++){
60010       if( aPgno[j]==aPgno[i] ){
60011         /* This branch is taken if the set of sibling pages somehow contains
60012         ** duplicate entries. This can happen if the database is corrupt. 
60013         ** It would be simpler to detect this as part of the loop below, but
60014         ** we do the detection here in order to avoid populating the pager
60015         ** cache with two separate objects associated with the same
60016         ** page number.  */
60017         assert( CORRUPT_DB );
60018         rc = SQLITE_CORRUPT_BKPT;
60019         goto balance_cleanup;
60020       }
60021     }
60022   }
60023   for(i=0; i<nNew; i++){
60024     int iBest = 0;                /* aPgno[] index of page number to use */
60025     for(j=1; j<nNew; j++){
60026       if( aPgOrder[j]<aPgOrder[iBest] ) iBest = j;
60027     }
60028     pgno = aPgOrder[iBest];
60029     aPgOrder[iBest] = 0xffffffff;
60030     if( iBest!=i ){
60031       if( iBest>i ){
60032         sqlite3PagerRekey(apNew[iBest]->pDbPage, pBt->nPage+iBest+1, 0);
60033       }
60034       sqlite3PagerRekey(apNew[i]->pDbPage, pgno, aPgFlags[iBest]);
60035       apNew[i]->pgno = pgno;
60036     }
60037   }
60038
60039   TRACE(("BALANCE: new: %d(%d nc=%d) %d(%d nc=%d) %d(%d nc=%d) "
60040          "%d(%d nc=%d) %d(%d nc=%d)\n",
60041     apNew[0]->pgno, szNew[0], cntNew[0],
60042     nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
60043     nNew>=2 ? cntNew[1] - cntNew[0] - !leafData : 0,
60044     nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
60045     nNew>=3 ? cntNew[2] - cntNew[1] - !leafData : 0,
60046     nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
60047     nNew>=4 ? cntNew[3] - cntNew[2] - !leafData : 0,
60048     nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0,
60049     nNew>=5 ? cntNew[4] - cntNew[3] - !leafData : 0
60050   ));
60051
60052   assert( sqlite3PagerIswriteable(pParent->pDbPage) );
60053   put4byte(pRight, apNew[nNew-1]->pgno);
60054
60055   /* If the sibling pages are not leaves, ensure that the right-child pointer
60056   ** of the right-most new sibling page is set to the value that was 
60057   ** originally in the same field of the right-most old sibling page. */
60058   if( (pageFlags & PTF_LEAF)==0 && nOld!=nNew ){
60059     MemPage *pOld = (nNew>nOld ? apNew : apOld)[nOld-1];
60060     memcpy(&apNew[nNew-1]->aData[8], &pOld->aData[8], 4);
60061   }
60062
60063   /* Make any required updates to pointer map entries associated with 
60064   ** cells stored on sibling pages following the balance operation. Pointer
60065   ** map entries associated with divider cells are set by the insertCell()
60066   ** routine. The associated pointer map entries are:
60067   **
60068   **   a) if the cell contains a reference to an overflow chain, the
60069   **      entry associated with the first page in the overflow chain, and
60070   **
60071   **   b) if the sibling pages are not leaves, the child page associated
60072   **      with the cell.
60073   **
60074   ** If the sibling pages are not leaves, then the pointer map entry 
60075   ** associated with the right-child of each sibling may also need to be 
60076   ** updated. This happens below, after the sibling pages have been 
60077   ** populated, not here.
60078   */
60079   if( ISAUTOVACUUM ){
60080     MemPage *pNew = apNew[0];
60081     u8 *aOld = pNew->aData;
60082     int cntOldNext = pNew->nCell + pNew->nOverflow;
60083     int usableSize = pBt->usableSize;
60084     int iNew = 0;
60085     int iOld = 0;
60086
60087     for(i=0; i<nCell; i++){
60088       u8 *pCell = apCell[i];
60089       if( i==cntOldNext ){
60090         MemPage *pOld = (++iOld)<nNew ? apNew[iOld] : apOld[iOld];
60091         cntOldNext += pOld->nCell + pOld->nOverflow + !leafData;
60092         aOld = pOld->aData;
60093       }
60094       if( i==cntNew[iNew] ){
60095         pNew = apNew[++iNew];
60096         if( !leafData ) continue;
60097       }
60098
60099       /* Cell pCell is destined for new sibling page pNew. Originally, it
60100       ** was either part of sibling page iOld (possibly an overflow cell), 
60101       ** or else the divider cell to the left of sibling page iOld. So,
60102       ** if sibling page iOld had the same page number as pNew, and if
60103       ** pCell really was a part of sibling page iOld (not a divider or
60104       ** overflow cell), we can skip updating the pointer map entries.  */
60105       if( iOld>=nNew
60106        || pNew->pgno!=aPgno[iOld]
60107        || pCell<aOld
60108        || pCell>=&aOld[usableSize]
60109       ){
60110         if( !leafCorrection ){
60111           ptrmapPut(pBt, get4byte(pCell), PTRMAP_BTREE, pNew->pgno, &rc);
60112         }
60113         if( szCell[i]>pNew->minLocal ){
60114           ptrmapPutOvflPtr(pNew, pCell, &rc);
60115         }
60116       }
60117     }
60118   }
60119
60120   /* Insert new divider cells into pParent. */
60121   for(i=0; i<nNew-1; i++){
60122     u8 *pCell;
60123     u8 *pTemp;
60124     int sz;
60125     MemPage *pNew = apNew[i];
60126     j = cntNew[i];
60127
60128     assert( j<nMaxCells );
60129     pCell = apCell[j];
60130     sz = szCell[j] + leafCorrection;
60131     pTemp = &aOvflSpace[iOvflSpace];
60132     if( !pNew->leaf ){
60133       memcpy(&pNew->aData[8], pCell, 4);
60134     }else if( leafData ){
60135       /* If the tree is a leaf-data tree, and the siblings are leaves, 
60136       ** then there is no divider cell in apCell[]. Instead, the divider 
60137       ** cell consists of the integer key for the right-most cell of 
60138       ** the sibling-page assembled above only.
60139       */
60140       CellInfo info;
60141       j--;
60142       btreeParseCellPtr(pNew, apCell[j], &info);
60143       pCell = pTemp;
60144       sz = 4 + putVarint(&pCell[4], info.nKey);
60145       pTemp = 0;
60146     }else{
60147       pCell -= 4;
60148       /* Obscure case for non-leaf-data trees: If the cell at pCell was
60149       ** previously stored on a leaf node, and its reported size was 4
60150       ** bytes, then it may actually be smaller than this 
60151       ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
60152       ** any cell). But it is important to pass the correct size to 
60153       ** insertCell(), so reparse the cell now.
60154       **
60155       ** Note that this can never happen in an SQLite data file, as all
60156       ** cells are at least 4 bytes. It only happens in b-trees used
60157       ** to evaluate "IN (SELECT ...)" and similar clauses.
60158       */
60159       if( szCell[j]==4 ){
60160         assert(leafCorrection==4);
60161         sz = cellSizePtr(pParent, pCell);
60162       }
60163     }
60164     iOvflSpace += sz;
60165     assert( sz<=pBt->maxLocal+23 );
60166     assert( iOvflSpace <= (int)pBt->pageSize );
60167     insertCell(pParent, nxDiv+i, pCell, sz, pTemp, pNew->pgno, &rc);
60168     if( rc!=SQLITE_OK ) goto balance_cleanup;
60169     assert( sqlite3PagerIswriteable(pParent->pDbPage) );
60170   }
60171
60172   /* Now update the actual sibling pages. The order in which they are updated
60173   ** is important, as this code needs to avoid disrupting any page from which
60174   ** cells may still to be read. In practice, this means:
60175   **
60176   **  (1) If cells are moving left (from apNew[iPg] to apNew[iPg-1])
60177   **      then it is not safe to update page apNew[iPg] until after
60178   **      the left-hand sibling apNew[iPg-1] has been updated.
60179   **
60180   **  (2) If cells are moving right (from apNew[iPg] to apNew[iPg+1])
60181   **      then it is not safe to update page apNew[iPg] until after
60182   **      the right-hand sibling apNew[iPg+1] has been updated.
60183   **
60184   ** If neither of the above apply, the page is safe to update.
60185   **
60186   ** The iPg value in the following loop starts at nNew-1 goes down
60187   ** to 0, then back up to nNew-1 again, thus making two passes over
60188   ** the pages.  On the initial downward pass, only condition (1) above
60189   ** needs to be tested because (2) will always be true from the previous
60190   ** step.  On the upward pass, both conditions are always true, so the
60191   ** upwards pass simply processes pages that were missed on the downward
60192   ** pass.
60193   */
60194   for(i=1-nNew; i<nNew; i++){
60195     int iPg = i<0 ? -i : i;
60196     assert( iPg>=0 && iPg<nNew );
60197     if( abDone[iPg] ) continue;         /* Skip pages already processed */
60198     if( i>=0                            /* On the upwards pass, or... */
60199      || cntOld[iPg-1]>=cntNew[iPg-1]    /* Condition (1) is true */
60200     ){
60201       int iNew;
60202       int iOld;
60203       int nNewCell;
60204
60205       /* Verify condition (1):  If cells are moving left, update iPg
60206       ** only after iPg-1 has already been updated. */
60207       assert( iPg==0 || cntOld[iPg-1]>=cntNew[iPg-1] || abDone[iPg-1] );
60208
60209       /* Verify condition (2):  If cells are moving right, update iPg
60210       ** only after iPg+1 has already been updated. */
60211       assert( cntNew[iPg]>=cntOld[iPg] || abDone[iPg+1] );
60212
60213       if( iPg==0 ){
60214         iNew = iOld = 0;
60215         nNewCell = cntNew[0];
60216       }else{
60217         iOld = iPg<nOld ? (cntOld[iPg-1] + !leafData) : nCell;
60218         iNew = cntNew[iPg-1] + !leafData;
60219         nNewCell = cntNew[iPg] - iNew;
60220       }
60221
60222       editPage(apNew[iPg], iOld, iNew, nNewCell, apCell, szCell);
60223       abDone[iPg]++;
60224       apNew[iPg]->nFree = usableSpace-szNew[iPg];
60225       assert( apNew[iPg]->nOverflow==0 );
60226       assert( apNew[iPg]->nCell==nNewCell );
60227     }
60228   }
60229
60230   /* All pages have been processed exactly once */
60231   assert( memcmp(abDone, "\01\01\01\01\01", nNew)==0 );
60232
60233   assert( nOld>0 );
60234   assert( nNew>0 );
60235
60236   if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
60237     /* The root page of the b-tree now contains no cells. The only sibling
60238     ** page is the right-child of the parent. Copy the contents of the
60239     ** child page into the parent, decreasing the overall height of the
60240     ** b-tree structure by one. This is described as the "balance-shallower"
60241     ** sub-algorithm in some documentation.
60242     **
60243     ** If this is an auto-vacuum database, the call to copyNodeContent() 
60244     ** sets all pointer-map entries corresponding to database image pages 
60245     ** for which the pointer is stored within the content being copied.
60246     **
60247     ** It is critical that the child page be defragmented before being
60248     ** copied into the parent, because if the parent is page 1 then it will
60249     ** by smaller than the child due to the database header, and so all the
60250     ** free space needs to be up front.
60251     */
60252     assert( nNew==1 );
60253     rc = defragmentPage(apNew[0]);
60254     testcase( rc!=SQLITE_OK );
60255     assert( apNew[0]->nFree == 
60256         (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
60257       || rc!=SQLITE_OK
60258     );
60259     copyNodeContent(apNew[0], pParent, &rc);
60260     freePage(apNew[0], &rc);
60261   }else if( ISAUTOVACUUM && !leafCorrection ){
60262     /* Fix the pointer map entries associated with the right-child of each
60263     ** sibling page. All other pointer map entries have already been taken
60264     ** care of.  */
60265     for(i=0; i<nNew; i++){
60266       u32 key = get4byte(&apNew[i]->aData[8]);
60267       ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
60268     }
60269   }
60270
60271   assert( pParent->isInit );
60272   TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
60273           nOld, nNew, nCell));
60274
60275   /* Free any old pages that were not reused as new pages.
60276   */
60277   for(i=nNew; i<nOld; i++){
60278     freePage(apOld[i], &rc);
60279   }
60280
60281 #if 0
60282   if( ISAUTOVACUUM && rc==SQLITE_OK && apNew[0]->isInit ){
60283     /* The ptrmapCheckPages() contains assert() statements that verify that
60284     ** all pointer map pages are set correctly. This is helpful while 
60285     ** debugging. This is usually disabled because a corrupt database may
60286     ** cause an assert() statement to fail.  */
60287     ptrmapCheckPages(apNew, nNew);
60288     ptrmapCheckPages(&pParent, 1);
60289   }
60290 #endif
60291
60292   /*
60293   ** Cleanup before returning.
60294   */
60295 balance_cleanup:
60296   sqlite3ScratchFree(apCell);
60297   for(i=0; i<nOld; i++){
60298     releasePage(apOld[i]);
60299   }
60300   for(i=0; i<nNew; i++){
60301     releasePage(apNew[i]);
60302   }
60303
60304   return rc;
60305 }
60306 #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
60307 #pragma optimize("", on)
60308 #endif
60309
60310
60311 /*
60312 ** This function is called when the root page of a b-tree structure is
60313 ** overfull (has one or more overflow pages).
60314 **
60315 ** A new child page is allocated and the contents of the current root
60316 ** page, including overflow cells, are copied into the child. The root
60317 ** page is then overwritten to make it an empty page with the right-child 
60318 ** pointer pointing to the new page.
60319 **
60320 ** Before returning, all pointer-map entries corresponding to pages 
60321 ** that the new child-page now contains pointers to are updated. The
60322 ** entry corresponding to the new right-child pointer of the root
60323 ** page is also updated.
60324 **
60325 ** If successful, *ppChild is set to contain a reference to the child 
60326 ** page and SQLITE_OK is returned. In this case the caller is required
60327 ** to call releasePage() on *ppChild exactly once. If an error occurs,
60328 ** an error code is returned and *ppChild is set to 0.
60329 */
60330 static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
60331   int rc;                        /* Return value from subprocedures */
60332   MemPage *pChild = 0;           /* Pointer to a new child page */
60333   Pgno pgnoChild = 0;            /* Page number of the new child page */
60334   BtShared *pBt = pRoot->pBt;    /* The BTree */
60335
60336   assert( pRoot->nOverflow>0 );
60337   assert( sqlite3_mutex_held(pBt->mutex) );
60338
60339   /* Make pRoot, the root page of the b-tree, writable. Allocate a new 
60340   ** page that will become the new right-child of pPage. Copy the contents
60341   ** of the node stored on pRoot into the new child page.
60342   */
60343   rc = sqlite3PagerWrite(pRoot->pDbPage);
60344   if( rc==SQLITE_OK ){
60345     rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
60346     copyNodeContent(pRoot, pChild, &rc);
60347     if( ISAUTOVACUUM ){
60348       ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
60349     }
60350   }
60351   if( rc ){
60352     *ppChild = 0;
60353     releasePage(pChild);
60354     return rc;
60355   }
60356   assert( sqlite3PagerIswriteable(pChild->pDbPage) );
60357   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
60358   assert( pChild->nCell==pRoot->nCell );
60359
60360   TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
60361
60362   /* Copy the overflow cells from pRoot to pChild */
60363   memcpy(pChild->aiOvfl, pRoot->aiOvfl,
60364          pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
60365   memcpy(pChild->apOvfl, pRoot->apOvfl,
60366          pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
60367   pChild->nOverflow = pRoot->nOverflow;
60368
60369   /* Zero the contents of pRoot. Then install pChild as the right-child. */
60370   zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
60371   put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
60372
60373   *ppChild = pChild;
60374   return SQLITE_OK;
60375 }
60376
60377 /*
60378 ** The page that pCur currently points to has just been modified in
60379 ** some way. This function figures out if this modification means the
60380 ** tree needs to be balanced, and if so calls the appropriate balancing 
60381 ** routine. Balancing routines are:
60382 **
60383 **   balance_quick()
60384 **   balance_deeper()
60385 **   balance_nonroot()
60386 */
60387 static int balance(BtCursor *pCur){
60388   int rc = SQLITE_OK;
60389   const int nMin = pCur->pBt->usableSize * 2 / 3;
60390   u8 aBalanceQuickSpace[13];
60391   u8 *pFree = 0;
60392
60393   TESTONLY( int balance_quick_called = 0 );
60394   TESTONLY( int balance_deeper_called = 0 );
60395
60396   do {
60397     int iPage = pCur->iPage;
60398     MemPage *pPage = pCur->apPage[iPage];
60399
60400     if( iPage==0 ){
60401       if( pPage->nOverflow ){
60402         /* The root page of the b-tree is overfull. In this case call the
60403         ** balance_deeper() function to create a new child for the root-page
60404         ** and copy the current contents of the root-page to it. The
60405         ** next iteration of the do-loop will balance the child page.
60406         */ 
60407         assert( (balance_deeper_called++)==0 );
60408         rc = balance_deeper(pPage, &pCur->apPage[1]);
60409         if( rc==SQLITE_OK ){
60410           pCur->iPage = 1;
60411           pCur->aiIdx[0] = 0;
60412           pCur->aiIdx[1] = 0;
60413           assert( pCur->apPage[1]->nOverflow );
60414         }
60415       }else{
60416         break;
60417       }
60418     }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
60419       break;
60420     }else{
60421       MemPage * const pParent = pCur->apPage[iPage-1];
60422       int const iIdx = pCur->aiIdx[iPage-1];
60423
60424       rc = sqlite3PagerWrite(pParent->pDbPage);
60425       if( rc==SQLITE_OK ){
60426 #ifndef SQLITE_OMIT_QUICKBALANCE
60427         if( pPage->intKeyLeaf
60428          && pPage->nOverflow==1
60429          && pPage->aiOvfl[0]==pPage->nCell
60430          && pParent->pgno!=1
60431          && pParent->nCell==iIdx
60432         ){
60433           /* Call balance_quick() to create a new sibling of pPage on which
60434           ** to store the overflow cell. balance_quick() inserts a new cell
60435           ** into pParent, which may cause pParent overflow. If this
60436           ** happens, the next iteration of the do-loop will balance pParent 
60437           ** use either balance_nonroot() or balance_deeper(). Until this
60438           ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
60439           ** buffer. 
60440           **
60441           ** The purpose of the following assert() is to check that only a
60442           ** single call to balance_quick() is made for each call to this
60443           ** function. If this were not verified, a subtle bug involving reuse
60444           ** of the aBalanceQuickSpace[] might sneak in.
60445           */
60446           assert( (balance_quick_called++)==0 );
60447           rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
60448         }else
60449 #endif
60450         {
60451           /* In this case, call balance_nonroot() to redistribute cells
60452           ** between pPage and up to 2 of its sibling pages. This involves
60453           ** modifying the contents of pParent, which may cause pParent to
60454           ** become overfull or underfull. The next iteration of the do-loop
60455           ** will balance the parent page to correct this.
60456           ** 
60457           ** If the parent page becomes overfull, the overflow cell or cells
60458           ** are stored in the pSpace buffer allocated immediately below. 
60459           ** A subsequent iteration of the do-loop will deal with this by
60460           ** calling balance_nonroot() (balance_deeper() may be called first,
60461           ** but it doesn't deal with overflow cells - just moves them to a
60462           ** different page). Once this subsequent call to balance_nonroot() 
60463           ** has completed, it is safe to release the pSpace buffer used by
60464           ** the previous call, as the overflow cell data will have been 
60465           ** copied either into the body of a database page or into the new
60466           ** pSpace buffer passed to the latter call to balance_nonroot().
60467           */
60468           u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
60469           rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1,
60470                                pCur->hints&BTREE_BULKLOAD);
60471           if( pFree ){
60472             /* If pFree is not NULL, it points to the pSpace buffer used 
60473             ** by a previous call to balance_nonroot(). Its contents are
60474             ** now stored either on real database pages or within the 
60475             ** new pSpace buffer, so it may be safely freed here. */
60476             sqlite3PageFree(pFree);
60477           }
60478
60479           /* The pSpace buffer will be freed after the next call to
60480           ** balance_nonroot(), or just before this function returns, whichever
60481           ** comes first. */
60482           pFree = pSpace;
60483         }
60484       }
60485
60486       pPage->nOverflow = 0;
60487
60488       /* The next iteration of the do-loop balances the parent page. */
60489       releasePage(pPage);
60490       pCur->iPage--;
60491       assert( pCur->iPage>=0 );
60492     }
60493   }while( rc==SQLITE_OK );
60494
60495   if( pFree ){
60496     sqlite3PageFree(pFree);
60497   }
60498   return rc;
60499 }
60500
60501
60502 /*
60503 ** Insert a new record into the BTree.  The key is given by (pKey,nKey)
60504 ** and the data is given by (pData,nData).  The cursor is used only to
60505 ** define what table the record should be inserted into.  The cursor
60506 ** is left pointing at a random location.
60507 **
60508 ** For an INTKEY table, only the nKey value of the key is used.  pKey is
60509 ** ignored.  For a ZERODATA table, the pData and nData are both ignored.
60510 **
60511 ** If the seekResult parameter is non-zero, then a successful call to
60512 ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
60513 ** been performed. seekResult is the search result returned (a negative
60514 ** number if pCur points at an entry that is smaller than (pKey, nKey), or
60515 ** a positive value if pCur points at an entry that is larger than 
60516 ** (pKey, nKey)). 
60517 **
60518 ** If the seekResult parameter is non-zero, then the caller guarantees that
60519 ** cursor pCur is pointing at the existing copy of a row that is to be
60520 ** overwritten.  If the seekResult parameter is 0, then cursor pCur may
60521 ** point to any entry or to no entry at all and so this function has to seek
60522 ** the cursor before the new key can be inserted.
60523 */
60524 SQLITE_PRIVATE int sqlite3BtreeInsert(
60525   BtCursor *pCur,                /* Insert data into the table of this cursor */
60526   const void *pKey, i64 nKey,    /* The key of the new record */
60527   const void *pData, int nData,  /* The data of the new record */
60528   int nZero,                     /* Number of extra 0 bytes to append to data */
60529   int appendBias,                /* True if this is likely an append */
60530   int seekResult                 /* Result of prior MovetoUnpacked() call */
60531 ){
60532   int rc;
60533   int loc = seekResult;          /* -1: before desired location  +1: after */
60534   int szNew = 0;
60535   int idx;
60536   MemPage *pPage;
60537   Btree *p = pCur->pBtree;
60538   BtShared *pBt = p->pBt;
60539   unsigned char *oldCell;
60540   unsigned char *newCell = 0;
60541
60542   if( pCur->eState==CURSOR_FAULT ){
60543     assert( pCur->skipNext!=SQLITE_OK );
60544     return pCur->skipNext;
60545   }
60546
60547   assert( cursorHoldsMutex(pCur) );
60548   assert( (pCur->curFlags & BTCF_WriteFlag)!=0
60549               && pBt->inTransaction==TRANS_WRITE
60550               && (pBt->btsFlags & BTS_READ_ONLY)==0 );
60551   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
60552
60553   /* Assert that the caller has been consistent. If this cursor was opened
60554   ** expecting an index b-tree, then the caller should be inserting blob
60555   ** keys with no associated data. If the cursor was opened expecting an
60556   ** intkey table, the caller should be inserting integer keys with a
60557   ** blob of associated data.  */
60558   assert( (pKey==0)==(pCur->pKeyInfo==0) );
60559
60560   /* Save the positions of any other cursors open on this table.
60561   **
60562   ** In some cases, the call to btreeMoveto() below is a no-op. For
60563   ** example, when inserting data into a table with auto-generated integer
60564   ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the 
60565   ** integer key to use. It then calls this function to actually insert the 
60566   ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
60567   ** that the cursor is already where it needs to be and returns without
60568   ** doing any work. To avoid thwarting these optimizations, it is important
60569   ** not to clear the cursor here.
60570   */
60571   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
60572   if( rc ) return rc;
60573
60574   if( pCur->pKeyInfo==0 ){
60575     /* If this is an insert into a table b-tree, invalidate any incrblob 
60576     ** cursors open on the row being replaced */
60577     invalidateIncrblobCursors(p, nKey, 0);
60578
60579     /* If the cursor is currently on the last row and we are appending a
60580     ** new row onto the end, set the "loc" to avoid an unnecessary btreeMoveto()
60581     ** call */
60582     if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0
60583       && pCur->info.nKey==nKey-1 ){
60584       loc = -1;
60585     }
60586   }
60587
60588   if( !loc ){
60589     rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
60590     if( rc ) return rc;
60591   }
60592   assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
60593
60594   pPage = pCur->apPage[pCur->iPage];
60595   assert( pPage->intKey || nKey>=0 );
60596   assert( pPage->leaf || !pPage->intKey );
60597
60598   TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
60599           pCur->pgnoRoot, nKey, nData, pPage->pgno,
60600           loc==0 ? "overwrite" : "new entry"));
60601   assert( pPage->isInit );
60602   newCell = pBt->pTmpSpace;
60603   assert( newCell!=0 );
60604   rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
60605   if( rc ) goto end_insert;
60606   assert( szNew==cellSizePtr(pPage, newCell) );
60607   assert( szNew <= MX_CELL_SIZE(pBt) );
60608   idx = pCur->aiIdx[pCur->iPage];
60609   if( loc==0 ){
60610     u16 szOld;
60611     assert( idx<pPage->nCell );
60612     rc = sqlite3PagerWrite(pPage->pDbPage);
60613     if( rc ){
60614       goto end_insert;
60615     }
60616     oldCell = findCell(pPage, idx);
60617     if( !pPage->leaf ){
60618       memcpy(newCell, oldCell, 4);
60619     }
60620     rc = clearCell(pPage, oldCell, &szOld);
60621     dropCell(pPage, idx, szOld, &rc);
60622     if( rc ) goto end_insert;
60623   }else if( loc<0 && pPage->nCell>0 ){
60624     assert( pPage->leaf );
60625     idx = ++pCur->aiIdx[pCur->iPage];
60626   }else{
60627     assert( pPage->leaf );
60628   }
60629   insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
60630   assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
60631
60632   /* If no error has occurred and pPage has an overflow cell, call balance() 
60633   ** to redistribute the cells within the tree. Since balance() may move
60634   ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
60635   ** variables.
60636   **
60637   ** Previous versions of SQLite called moveToRoot() to move the cursor
60638   ** back to the root page as balance() used to invalidate the contents
60639   ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
60640   ** set the cursor state to "invalid". This makes common insert operations
60641   ** slightly faster.
60642   **
60643   ** There is a subtle but important optimization here too. When inserting
60644   ** multiple records into an intkey b-tree using a single cursor (as can
60645   ** happen while processing an "INSERT INTO ... SELECT" statement), it
60646   ** is advantageous to leave the cursor pointing to the last entry in
60647   ** the b-tree if possible. If the cursor is left pointing to the last
60648   ** entry in the table, and the next row inserted has an integer key
60649   ** larger than the largest existing key, it is possible to insert the
60650   ** row without seeking the cursor. This can be a big performance boost.
60651   */
60652   pCur->info.nSize = 0;
60653   if( rc==SQLITE_OK && pPage->nOverflow ){
60654     pCur->curFlags &= ~(BTCF_ValidNKey);
60655     rc = balance(pCur);
60656
60657     /* Must make sure nOverflow is reset to zero even if the balance()
60658     ** fails. Internal data structure corruption will result otherwise. 
60659     ** Also, set the cursor state to invalid. This stops saveCursorPosition()
60660     ** from trying to save the current position of the cursor.  */
60661     pCur->apPage[pCur->iPage]->nOverflow = 0;
60662     pCur->eState = CURSOR_INVALID;
60663   }
60664   assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
60665
60666 end_insert:
60667   return rc;
60668 }
60669
60670 /*
60671 ** Delete the entry that the cursor is pointing to.  The cursor
60672 ** is left pointing at an arbitrary location.
60673 */
60674 SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
60675   Btree *p = pCur->pBtree;
60676   BtShared *pBt = p->pBt;              
60677   int rc;                              /* Return code */
60678   MemPage *pPage;                      /* Page to delete cell from */
60679   unsigned char *pCell;                /* Pointer to cell to delete */
60680   int iCellIdx;                        /* Index of cell to delete */
60681   int iCellDepth;                      /* Depth of node containing pCell */ 
60682   u16 szCell;                          /* Size of the cell being deleted */
60683
60684   assert( cursorHoldsMutex(pCur) );
60685   assert( pBt->inTransaction==TRANS_WRITE );
60686   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
60687   assert( pCur->curFlags & BTCF_WriteFlag );
60688   assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
60689   assert( !hasReadConflicts(p, pCur->pgnoRoot) );
60690
60691   if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell) 
60692    || NEVER(pCur->eState!=CURSOR_VALID)
60693   ){
60694     return SQLITE_ERROR;  /* Something has gone awry. */
60695   }
60696
60697   iCellDepth = pCur->iPage;
60698   iCellIdx = pCur->aiIdx[iCellDepth];
60699   pPage = pCur->apPage[iCellDepth];
60700   pCell = findCell(pPage, iCellIdx);
60701
60702   /* If the page containing the entry to delete is not a leaf page, move
60703   ** the cursor to the largest entry in the tree that is smaller than
60704   ** the entry being deleted. This cell will replace the cell being deleted
60705   ** from the internal node. The 'previous' entry is used for this instead
60706   ** of the 'next' entry, as the previous entry is always a part of the
60707   ** sub-tree headed by the child page of the cell being deleted. This makes
60708   ** balancing the tree following the delete operation easier.  */
60709   if( !pPage->leaf ){
60710     int notUsed = 0;
60711     rc = sqlite3BtreePrevious(pCur, &notUsed);
60712     if( rc ) return rc;
60713   }
60714
60715   /* Save the positions of any other cursors open on this table before
60716   ** making any modifications. Make the page containing the entry to be 
60717   ** deleted writable. Then free any overflow pages associated with the 
60718   ** entry and finally remove the cell itself from within the page.  
60719   */
60720   rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
60721   if( rc ) return rc;
60722
60723   /* If this is a delete operation to remove a row from a table b-tree,
60724   ** invalidate any incrblob cursors open on the row being deleted.  */
60725   if( pCur->pKeyInfo==0 ){
60726     invalidateIncrblobCursors(p, pCur->info.nKey, 0);
60727   }
60728
60729   rc = sqlite3PagerWrite(pPage->pDbPage);
60730   if( rc ) return rc;
60731   rc = clearCell(pPage, pCell, &szCell);
60732   dropCell(pPage, iCellIdx, szCell, &rc);
60733   if( rc ) return rc;
60734
60735   /* If the cell deleted was not located on a leaf page, then the cursor
60736   ** is currently pointing to the largest entry in the sub-tree headed
60737   ** by the child-page of the cell that was just deleted from an internal
60738   ** node. The cell from the leaf node needs to be moved to the internal
60739   ** node to replace the deleted cell.  */
60740   if( !pPage->leaf ){
60741     MemPage *pLeaf = pCur->apPage[pCur->iPage];
60742     int nCell;
60743     Pgno n = pCur->apPage[iCellDepth+1]->pgno;
60744     unsigned char *pTmp;
60745
60746     pCell = findCell(pLeaf, pLeaf->nCell-1);
60747     nCell = cellSizePtr(pLeaf, pCell);
60748     assert( MX_CELL_SIZE(pBt) >= nCell );
60749     pTmp = pBt->pTmpSpace;
60750     assert( pTmp!=0 );
60751     rc = sqlite3PagerWrite(pLeaf->pDbPage);
60752     insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
60753     dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
60754     if( rc ) return rc;
60755   }
60756
60757   /* Balance the tree. If the entry deleted was located on a leaf page,
60758   ** then the cursor still points to that page. In this case the first
60759   ** call to balance() repairs the tree, and the if(...) condition is
60760   ** never true.
60761   **
60762   ** Otherwise, if the entry deleted was on an internal node page, then
60763   ** pCur is pointing to the leaf page from which a cell was removed to
60764   ** replace the cell deleted from the internal node. This is slightly
60765   ** tricky as the leaf node may be underfull, and the internal node may
60766   ** be either under or overfull. In this case run the balancing algorithm
60767   ** on the leaf node first. If the balance proceeds far enough up the
60768   ** tree that we can be sure that any problem in the internal node has
60769   ** been corrected, so be it. Otherwise, after balancing the leaf node,
60770   ** walk the cursor up the tree to the internal node and balance it as 
60771   ** well.  */
60772   rc = balance(pCur);
60773   if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
60774     while( pCur->iPage>iCellDepth ){
60775       releasePage(pCur->apPage[pCur->iPage--]);
60776     }
60777     rc = balance(pCur);
60778   }
60779
60780   if( rc==SQLITE_OK ){
60781     moveToRoot(pCur);
60782   }
60783   return rc;
60784 }
60785
60786 /*
60787 ** Create a new BTree table.  Write into *piTable the page
60788 ** number for the root page of the new table.
60789 **
60790 ** The type of type is determined by the flags parameter.  Only the
60791 ** following values of flags are currently in use.  Other values for
60792 ** flags might not work:
60793 **
60794 **     BTREE_INTKEY|BTREE_LEAFDATA     Used for SQL tables with rowid keys
60795 **     BTREE_ZERODATA                  Used for SQL indices
60796 */
60797 static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
60798   BtShared *pBt = p->pBt;
60799   MemPage *pRoot;
60800   Pgno pgnoRoot;
60801   int rc;
60802   int ptfFlags;          /* Page-type flage for the root page of new table */
60803
60804   assert( sqlite3BtreeHoldsMutex(p) );
60805   assert( pBt->inTransaction==TRANS_WRITE );
60806   assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
60807
60808 #ifdef SQLITE_OMIT_AUTOVACUUM
60809   rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
60810   if( rc ){
60811     return rc;
60812   }
60813 #else
60814   if( pBt->autoVacuum ){
60815     Pgno pgnoMove;      /* Move a page here to make room for the root-page */
60816     MemPage *pPageMove; /* The page to move to. */
60817
60818     /* Creating a new table may probably require moving an existing database
60819     ** to make room for the new tables root page. In case this page turns
60820     ** out to be an overflow page, delete all overflow page-map caches
60821     ** held by open cursors.
60822     */
60823     invalidateAllOverflowCache(pBt);
60824
60825     /* Read the value of meta[3] from the database to determine where the
60826     ** root page of the new table should go. meta[3] is the largest root-page
60827     ** created so far, so the new root-page is (meta[3]+1).
60828     */
60829     sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
60830     pgnoRoot++;
60831
60832     /* The new root-page may not be allocated on a pointer-map page, or the
60833     ** PENDING_BYTE page.
60834     */
60835     while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
60836         pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
60837       pgnoRoot++;
60838     }
60839     assert( pgnoRoot>=3 );
60840
60841     /* Allocate a page. The page that currently resides at pgnoRoot will
60842     ** be moved to the allocated page (unless the allocated page happens
60843     ** to reside at pgnoRoot).
60844     */
60845     rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
60846     if( rc!=SQLITE_OK ){
60847       return rc;
60848     }
60849
60850     if( pgnoMove!=pgnoRoot ){
60851       /* pgnoRoot is the page that will be used for the root-page of
60852       ** the new table (assuming an error did not occur). But we were
60853       ** allocated pgnoMove. If required (i.e. if it was not allocated
60854       ** by extending the file), the current page at position pgnoMove
60855       ** is already journaled.
60856       */
60857       u8 eType = 0;
60858       Pgno iPtrPage = 0;
60859
60860       /* Save the positions of any open cursors. This is required in
60861       ** case they are holding a reference to an xFetch reference
60862       ** corresponding to page pgnoRoot.  */
60863       rc = saveAllCursors(pBt, 0, 0);
60864       releasePage(pPageMove);
60865       if( rc!=SQLITE_OK ){
60866         return rc;
60867       }
60868
60869       /* Move the page currently at pgnoRoot to pgnoMove. */
60870       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
60871       if( rc!=SQLITE_OK ){
60872         return rc;
60873       }
60874       rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
60875       if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
60876         rc = SQLITE_CORRUPT_BKPT;
60877       }
60878       if( rc!=SQLITE_OK ){
60879         releasePage(pRoot);
60880         return rc;
60881       }
60882       assert( eType!=PTRMAP_ROOTPAGE );
60883       assert( eType!=PTRMAP_FREEPAGE );
60884       rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
60885       releasePage(pRoot);
60886
60887       /* Obtain the page at pgnoRoot */
60888       if( rc!=SQLITE_OK ){
60889         return rc;
60890       }
60891       rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
60892       if( rc!=SQLITE_OK ){
60893         return rc;
60894       }
60895       rc = sqlite3PagerWrite(pRoot->pDbPage);
60896       if( rc!=SQLITE_OK ){
60897         releasePage(pRoot);
60898         return rc;
60899       }
60900     }else{
60901       pRoot = pPageMove;
60902     } 
60903
60904     /* Update the pointer-map and meta-data with the new root-page number. */
60905     ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
60906     if( rc ){
60907       releasePage(pRoot);
60908       return rc;
60909     }
60910
60911     /* When the new root page was allocated, page 1 was made writable in
60912     ** order either to increase the database filesize, or to decrement the
60913     ** freelist count.  Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
60914     */
60915     assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
60916     rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
60917     if( NEVER(rc) ){
60918       releasePage(pRoot);
60919       return rc;
60920     }
60921
60922   }else{
60923     rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
60924     if( rc ) return rc;
60925   }
60926 #endif
60927   assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
60928   if( createTabFlags & BTREE_INTKEY ){
60929     ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
60930   }else{
60931     ptfFlags = PTF_ZERODATA | PTF_LEAF;
60932   }
60933   zeroPage(pRoot, ptfFlags);
60934   sqlite3PagerUnref(pRoot->pDbPage);
60935   assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
60936   *piTable = (int)pgnoRoot;
60937   return SQLITE_OK;
60938 }
60939 SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
60940   int rc;
60941   sqlite3BtreeEnter(p);
60942   rc = btreeCreateTable(p, piTable, flags);
60943   sqlite3BtreeLeave(p);
60944   return rc;
60945 }
60946
60947 /*
60948 ** Erase the given database page and all its children.  Return
60949 ** the page to the freelist.
60950 */
60951 static int clearDatabasePage(
60952   BtShared *pBt,           /* The BTree that contains the table */
60953   Pgno pgno,               /* Page number to clear */
60954   int freePageFlag,        /* Deallocate page if true */
60955   int *pnChange            /* Add number of Cells freed to this counter */
60956 ){
60957   MemPage *pPage;
60958   int rc;
60959   unsigned char *pCell;
60960   int i;
60961   int hdr;
60962   u16 szCell;
60963
60964   assert( sqlite3_mutex_held(pBt->mutex) );
60965   if( pgno>btreePagecount(pBt) ){
60966     return SQLITE_CORRUPT_BKPT;
60967   }
60968   rc = getAndInitPage(pBt, pgno, &pPage, 0);
60969   if( rc ) return rc;
60970   if( pPage->bBusy ){
60971     rc = SQLITE_CORRUPT_BKPT;
60972     goto cleardatabasepage_out;
60973   }
60974   pPage->bBusy = 1;
60975   hdr = pPage->hdrOffset;
60976   for(i=0; i<pPage->nCell; i++){
60977     pCell = findCell(pPage, i);
60978     if( !pPage->leaf ){
60979       rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
60980       if( rc ) goto cleardatabasepage_out;
60981     }
60982     rc = clearCell(pPage, pCell, &szCell);
60983     if( rc ) goto cleardatabasepage_out;
60984   }
60985   if( !pPage->leaf ){
60986     rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
60987     if( rc ) goto cleardatabasepage_out;
60988   }else if( pnChange ){
60989     assert( pPage->intKey );
60990     *pnChange += pPage->nCell;
60991   }
60992   if( freePageFlag ){
60993     freePage(pPage, &rc);
60994   }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
60995     zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
60996   }
60997
60998 cleardatabasepage_out:
60999   pPage->bBusy = 0;
61000   releasePage(pPage);
61001   return rc;
61002 }
61003
61004 /*
61005 ** Delete all information from a single table in the database.  iTable is
61006 ** the page number of the root of the table.  After this routine returns,
61007 ** the root page is empty, but still exists.
61008 **
61009 ** This routine will fail with SQLITE_LOCKED if there are any open
61010 ** read cursors on the table.  Open write cursors are moved to the
61011 ** root of the table.
61012 **
61013 ** If pnChange is not NULL, then table iTable must be an intkey table. The
61014 ** integer value pointed to by pnChange is incremented by the number of
61015 ** entries in the table.
61016 */
61017 SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
61018   int rc;
61019   BtShared *pBt = p->pBt;
61020   sqlite3BtreeEnter(p);
61021   assert( p->inTrans==TRANS_WRITE );
61022
61023   rc = saveAllCursors(pBt, (Pgno)iTable, 0);
61024
61025   if( SQLITE_OK==rc ){
61026     /* Invalidate all incrblob cursors open on table iTable (assuming iTable
61027     ** is the root of a table b-tree - if it is not, the following call is
61028     ** a no-op).  */
61029     invalidateIncrblobCursors(p, 0, 1);
61030     rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
61031   }
61032   sqlite3BtreeLeave(p);
61033   return rc;
61034 }
61035
61036 /*
61037 ** Delete all information from the single table that pCur is open on.
61038 **
61039 ** This routine only work for pCur on an ephemeral table.
61040 */
61041 SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
61042   return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
61043 }
61044
61045 /*
61046 ** Erase all information in a table and add the root of the table to
61047 ** the freelist.  Except, the root of the principle table (the one on
61048 ** page 1) is never added to the freelist.
61049 **
61050 ** This routine will fail with SQLITE_LOCKED if there are any open
61051 ** cursors on the table.
61052 **
61053 ** If AUTOVACUUM is enabled and the page at iTable is not the last
61054 ** root page in the database file, then the last root page 
61055 ** in the database file is moved into the slot formerly occupied by
61056 ** iTable and that last slot formerly occupied by the last root page
61057 ** is added to the freelist instead of iTable.  In this say, all
61058 ** root pages are kept at the beginning of the database file, which
61059 ** is necessary for AUTOVACUUM to work right.  *piMoved is set to the 
61060 ** page number that used to be the last root page in the file before
61061 ** the move.  If no page gets moved, *piMoved is set to 0.
61062 ** The last root page is recorded in meta[3] and the value of
61063 ** meta[3] is updated by this procedure.
61064 */
61065 static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
61066   int rc;
61067   MemPage *pPage = 0;
61068   BtShared *pBt = p->pBt;
61069
61070   assert( sqlite3BtreeHoldsMutex(p) );
61071   assert( p->inTrans==TRANS_WRITE );
61072
61073   /* It is illegal to drop a table if any cursors are open on the
61074   ** database. This is because in auto-vacuum mode the backend may
61075   ** need to move another root-page to fill a gap left by the deleted
61076   ** root page. If an open cursor was using this page a problem would 
61077   ** occur.
61078   **
61079   ** This error is caught long before control reaches this point.
61080   */
61081   if( NEVER(pBt->pCursor) ){
61082     sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
61083     return SQLITE_LOCKED_SHAREDCACHE;
61084   }
61085
61086   rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
61087   if( rc ) return rc;
61088   rc = sqlite3BtreeClearTable(p, iTable, 0);
61089   if( rc ){
61090     releasePage(pPage);
61091     return rc;
61092   }
61093
61094   *piMoved = 0;
61095
61096   if( iTable>1 ){
61097 #ifdef SQLITE_OMIT_AUTOVACUUM
61098     freePage(pPage, &rc);
61099     releasePage(pPage);
61100 #else
61101     if( pBt->autoVacuum ){
61102       Pgno maxRootPgno;
61103       sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
61104
61105       if( iTable==maxRootPgno ){
61106         /* If the table being dropped is the table with the largest root-page
61107         ** number in the database, put the root page on the free list. 
61108         */
61109         freePage(pPage, &rc);
61110         releasePage(pPage);
61111         if( rc!=SQLITE_OK ){
61112           return rc;
61113         }
61114       }else{
61115         /* The table being dropped does not have the largest root-page
61116         ** number in the database. So move the page that does into the 
61117         ** gap left by the deleted root-page.
61118         */
61119         MemPage *pMove;
61120         releasePage(pPage);
61121         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
61122         if( rc!=SQLITE_OK ){
61123           return rc;
61124         }
61125         rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
61126         releasePage(pMove);
61127         if( rc!=SQLITE_OK ){
61128           return rc;
61129         }
61130         pMove = 0;
61131         rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
61132         freePage(pMove, &rc);
61133         releasePage(pMove);
61134         if( rc!=SQLITE_OK ){
61135           return rc;
61136         }
61137         *piMoved = maxRootPgno;
61138       }
61139
61140       /* Set the new 'max-root-page' value in the database header. This
61141       ** is the old value less one, less one more if that happens to
61142       ** be a root-page number, less one again if that is the
61143       ** PENDING_BYTE_PAGE.
61144       */
61145       maxRootPgno--;
61146       while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
61147              || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
61148         maxRootPgno--;
61149       }
61150       assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
61151
61152       rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
61153     }else{
61154       freePage(pPage, &rc);
61155       releasePage(pPage);
61156     }
61157 #endif
61158   }else{
61159     /* If sqlite3BtreeDropTable was called on page 1.
61160     ** This really never should happen except in a corrupt
61161     ** database. 
61162     */
61163     zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
61164     releasePage(pPage);
61165   }
61166   return rc;  
61167 }
61168 SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
61169   int rc;
61170   sqlite3BtreeEnter(p);
61171   rc = btreeDropTable(p, iTable, piMoved);
61172   sqlite3BtreeLeave(p);
61173   return rc;
61174 }
61175
61176
61177 /*
61178 ** This function may only be called if the b-tree connection already
61179 ** has a read or write transaction open on the database.
61180 **
61181 ** Read the meta-information out of a database file.  Meta[0]
61182 ** is the number of free pages currently in the database.  Meta[1]
61183 ** through meta[15] are available for use by higher layers.  Meta[0]
61184 ** is read-only, the others are read/write.
61185 ** 
61186 ** The schema layer numbers meta values differently.  At the schema
61187 ** layer (and the SetCookie and ReadCookie opcodes) the number of
61188 ** free pages is not visible.  So Cookie[0] is the same as Meta[1].
61189 **
61190 ** This routine treats Meta[BTREE_DATA_VERSION] as a special case.  Instead
61191 ** of reading the value out of the header, it instead loads the "DataVersion"
61192 ** from the pager.  The BTREE_DATA_VERSION value is not actually stored in the
61193 ** database file.  It is a number computed by the pager.  But its access
61194 ** pattern is the same as header meta values, and so it is convenient to
61195 ** read it from this routine.
61196 */
61197 SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
61198   BtShared *pBt = p->pBt;
61199
61200   sqlite3BtreeEnter(p);
61201   assert( p->inTrans>TRANS_NONE );
61202   assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
61203   assert( pBt->pPage1 );
61204   assert( idx>=0 && idx<=15 );
61205
61206   if( idx==BTREE_DATA_VERSION ){
61207     *pMeta = sqlite3PagerDataVersion(pBt->pPager) + p->iDataVersion;
61208   }else{
61209     *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
61210   }
61211
61212   /* If auto-vacuum is disabled in this build and this is an auto-vacuum
61213   ** database, mark the database as read-only.  */
61214 #ifdef SQLITE_OMIT_AUTOVACUUM
61215   if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
61216     pBt->btsFlags |= BTS_READ_ONLY;
61217   }
61218 #endif
61219
61220   sqlite3BtreeLeave(p);
61221 }
61222
61223 /*
61224 ** Write meta-information back into the database.  Meta[0] is
61225 ** read-only and may not be written.
61226 */
61227 SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
61228   BtShared *pBt = p->pBt;
61229   unsigned char *pP1;
61230   int rc;
61231   assert( idx>=1 && idx<=15 );
61232   sqlite3BtreeEnter(p);
61233   assert( p->inTrans==TRANS_WRITE );
61234   assert( pBt->pPage1!=0 );
61235   pP1 = pBt->pPage1->aData;
61236   rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
61237   if( rc==SQLITE_OK ){
61238     put4byte(&pP1[36 + idx*4], iMeta);
61239 #ifndef SQLITE_OMIT_AUTOVACUUM
61240     if( idx==BTREE_INCR_VACUUM ){
61241       assert( pBt->autoVacuum || iMeta==0 );
61242       assert( iMeta==0 || iMeta==1 );
61243       pBt->incrVacuum = (u8)iMeta;
61244     }
61245 #endif
61246   }
61247   sqlite3BtreeLeave(p);
61248   return rc;
61249 }
61250
61251 #ifndef SQLITE_OMIT_BTREECOUNT
61252 /*
61253 ** The first argument, pCur, is a cursor opened on some b-tree. Count the
61254 ** number of entries in the b-tree and write the result to *pnEntry.
61255 **
61256 ** SQLITE_OK is returned if the operation is successfully executed. 
61257 ** Otherwise, if an error is encountered (i.e. an IO error or database
61258 ** corruption) an SQLite error code is returned.
61259 */
61260 SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
61261   i64 nEntry = 0;                      /* Value to return in *pnEntry */
61262   int rc;                              /* Return code */
61263
61264   if( pCur->pgnoRoot==0 ){
61265     *pnEntry = 0;
61266     return SQLITE_OK;
61267   }
61268   rc = moveToRoot(pCur);
61269
61270   /* Unless an error occurs, the following loop runs one iteration for each
61271   ** page in the B-Tree structure (not including overflow pages). 
61272   */
61273   while( rc==SQLITE_OK ){
61274     int iIdx;                          /* Index of child node in parent */
61275     MemPage *pPage;                    /* Current page of the b-tree */
61276
61277     /* If this is a leaf page or the tree is not an int-key tree, then 
61278     ** this page contains countable entries. Increment the entry counter
61279     ** accordingly.
61280     */
61281     pPage = pCur->apPage[pCur->iPage];
61282     if( pPage->leaf || !pPage->intKey ){
61283       nEntry += pPage->nCell;
61284     }
61285
61286     /* pPage is a leaf node. This loop navigates the cursor so that it 
61287     ** points to the first interior cell that it points to the parent of
61288     ** the next page in the tree that has not yet been visited. The
61289     ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
61290     ** of the page, or to the number of cells in the page if the next page
61291     ** to visit is the right-child of its parent.
61292     **
61293     ** If all pages in the tree have been visited, return SQLITE_OK to the
61294     ** caller.
61295     */
61296     if( pPage->leaf ){
61297       do {
61298         if( pCur->iPage==0 ){
61299           /* All pages of the b-tree have been visited. Return successfully. */
61300           *pnEntry = nEntry;
61301           return moveToRoot(pCur);
61302         }
61303         moveToParent(pCur);
61304       }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
61305
61306       pCur->aiIdx[pCur->iPage]++;
61307       pPage = pCur->apPage[pCur->iPage];
61308     }
61309
61310     /* Descend to the child node of the cell that the cursor currently 
61311     ** points at. This is the right-child if (iIdx==pPage->nCell).
61312     */
61313     iIdx = pCur->aiIdx[pCur->iPage];
61314     if( iIdx==pPage->nCell ){
61315       rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
61316     }else{
61317       rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
61318     }
61319   }
61320
61321   /* An error has occurred. Return an error code. */
61322   return rc;
61323 }
61324 #endif
61325
61326 /*
61327 ** Return the pager associated with a BTree.  This routine is used for
61328 ** testing and debugging only.
61329 */
61330 SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
61331   return p->pBt->pPager;
61332 }
61333
61334 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
61335 /*
61336 ** Append a message to the error message string.
61337 */
61338 static void checkAppendMsg(
61339   IntegrityCk *pCheck,
61340   const char *zFormat,
61341   ...
61342 ){
61343   va_list ap;
61344   char zBuf[200];
61345   if( !pCheck->mxErr ) return;
61346   pCheck->mxErr--;
61347   pCheck->nErr++;
61348   va_start(ap, zFormat);
61349   if( pCheck->errMsg.nChar ){
61350     sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
61351   }
61352   if( pCheck->zPfx ){
61353     sqlite3_snprintf(sizeof(zBuf), zBuf, pCheck->zPfx, pCheck->v1, pCheck->v2);
61354     sqlite3StrAccumAppendAll(&pCheck->errMsg, zBuf);
61355   }
61356   sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
61357   va_end(ap);
61358   if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
61359     pCheck->mallocFailed = 1;
61360   }
61361 }
61362 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
61363
61364 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
61365
61366 /*
61367 ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
61368 ** corresponds to page iPg is already set.
61369 */
61370 static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
61371   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
61372   return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
61373 }
61374
61375 /*
61376 ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
61377 */
61378 static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
61379   assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
61380   pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
61381 }
61382
61383
61384 /*
61385 ** Add 1 to the reference count for page iPage.  If this is the second
61386 ** reference to the page, add an error message to pCheck->zErrMsg.
61387 ** Return 1 if there are 2 or more references to the page and 0 if
61388 ** if this is the first reference to the page.
61389 **
61390 ** Also check that the page number is in bounds.
61391 */
61392 static int checkRef(IntegrityCk *pCheck, Pgno iPage){
61393   if( iPage==0 ) return 1;
61394   if( iPage>pCheck->nPage ){
61395     checkAppendMsg(pCheck, "invalid page number %d", iPage);
61396     return 1;
61397   }
61398   if( getPageReferenced(pCheck, iPage) ){
61399     checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
61400     return 1;
61401   }
61402   setPageReferenced(pCheck, iPage);
61403   return 0;
61404 }
61405
61406 #ifndef SQLITE_OMIT_AUTOVACUUM
61407 /*
61408 ** Check that the entry in the pointer-map for page iChild maps to 
61409 ** page iParent, pointer type ptrType. If not, append an error message
61410 ** to pCheck.
61411 */
61412 static void checkPtrmap(
61413   IntegrityCk *pCheck,   /* Integrity check context */
61414   Pgno iChild,           /* Child page number */
61415   u8 eType,              /* Expected pointer map type */
61416   Pgno iParent           /* Expected pointer map parent page number */
61417 ){
61418   int rc;
61419   u8 ePtrmapType;
61420   Pgno iPtrmapParent;
61421
61422   rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
61423   if( rc!=SQLITE_OK ){
61424     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
61425     checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
61426     return;
61427   }
61428
61429   if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
61430     checkAppendMsg(pCheck,
61431       "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)", 
61432       iChild, eType, iParent, ePtrmapType, iPtrmapParent);
61433   }
61434 }
61435 #endif
61436
61437 /*
61438 ** Check the integrity of the freelist or of an overflow page list.
61439 ** Verify that the number of pages on the list is N.
61440 */
61441 static void checkList(
61442   IntegrityCk *pCheck,  /* Integrity checking context */
61443   int isFreeList,       /* True for a freelist.  False for overflow page list */
61444   int iPage,            /* Page number for first page in the list */
61445   int N                 /* Expected number of pages in the list */
61446 ){
61447   int i;
61448   int expected = N;
61449   int iFirst = iPage;
61450   while( N-- > 0 && pCheck->mxErr ){
61451     DbPage *pOvflPage;
61452     unsigned char *pOvflData;
61453     if( iPage<1 ){
61454       checkAppendMsg(pCheck,
61455          "%d of %d pages missing from overflow list starting at %d",
61456           N+1, expected, iFirst);
61457       break;
61458     }
61459     if( checkRef(pCheck, iPage) ) break;
61460     if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
61461       checkAppendMsg(pCheck, "failed to get page %d", iPage);
61462       break;
61463     }
61464     pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
61465     if( isFreeList ){
61466       int n = get4byte(&pOvflData[4]);
61467 #ifndef SQLITE_OMIT_AUTOVACUUM
61468       if( pCheck->pBt->autoVacuum ){
61469         checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
61470       }
61471 #endif
61472       if( n>(int)pCheck->pBt->usableSize/4-2 ){
61473         checkAppendMsg(pCheck,
61474            "freelist leaf count too big on page %d", iPage);
61475         N--;
61476       }else{
61477         for(i=0; i<n; i++){
61478           Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
61479 #ifndef SQLITE_OMIT_AUTOVACUUM
61480           if( pCheck->pBt->autoVacuum ){
61481             checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
61482           }
61483 #endif
61484           checkRef(pCheck, iFreePage);
61485         }
61486         N -= n;
61487       }
61488     }
61489 #ifndef SQLITE_OMIT_AUTOVACUUM
61490     else{
61491       /* If this database supports auto-vacuum and iPage is not the last
61492       ** page in this overflow list, check that the pointer-map entry for
61493       ** the following page matches iPage.
61494       */
61495       if( pCheck->pBt->autoVacuum && N>0 ){
61496         i = get4byte(pOvflData);
61497         checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
61498       }
61499     }
61500 #endif
61501     iPage = get4byte(pOvflData);
61502     sqlite3PagerUnref(pOvflPage);
61503   }
61504 }
61505 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
61506
61507 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
61508 /*
61509 ** Do various sanity checks on a single page of a tree.  Return
61510 ** the tree depth.  Root pages return 0.  Parents of root pages
61511 ** return 1, and so forth.
61512 ** 
61513 ** These checks are done:
61514 **
61515 **      1.  Make sure that cells and freeblocks do not overlap
61516 **          but combine to completely cover the page.
61517 **  NO  2.  Make sure cell keys are in order.
61518 **  NO  3.  Make sure no key is less than or equal to zLowerBound.
61519 **  NO  4.  Make sure no key is greater than or equal to zUpperBound.
61520 **      5.  Check the integrity of overflow pages.
61521 **      6.  Recursively call checkTreePage on all children.
61522 **      7.  Verify that the depth of all children is the same.
61523 **      8.  Make sure this page is at least 33% full or else it is
61524 **          the root of the tree.
61525 */
61526 static int checkTreePage(
61527   IntegrityCk *pCheck,  /* Context for the sanity check */
61528   int iPage,            /* Page number of the page to check */
61529   i64 *pnParentMinKey, 
61530   i64 *pnParentMaxKey
61531 ){
61532   MemPage *pPage;
61533   int i, rc, depth, d2, pgno, cnt;
61534   int hdr, cellStart;
61535   int nCell;
61536   u8 *data;
61537   BtShared *pBt;
61538   int usableSize;
61539   char *hit = 0;
61540   i64 nMinKey = 0;
61541   i64 nMaxKey = 0;
61542   const char *saved_zPfx = pCheck->zPfx;
61543   int saved_v1 = pCheck->v1;
61544   int saved_v2 = pCheck->v2;
61545
61546   /* Check that the page exists
61547   */
61548   pBt = pCheck->pBt;
61549   usableSize = pBt->usableSize;
61550   if( iPage==0 ) return 0;
61551   if( checkRef(pCheck, iPage) ) return 0;
61552   pCheck->zPfx = "Page %d: ";
61553   pCheck->v1 = iPage;
61554   if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
61555     checkAppendMsg(pCheck,
61556        "unable to get the page. error code=%d", rc);
61557     depth = -1;
61558     goto end_of_check;
61559   }
61560
61561   /* Clear MemPage.isInit to make sure the corruption detection code in
61562   ** btreeInitPage() is executed.  */
61563   pPage->isInit = 0;
61564   if( (rc = btreeInitPage(pPage))!=0 ){
61565     assert( rc==SQLITE_CORRUPT );  /* The only possible error from InitPage */
61566     checkAppendMsg(pCheck,
61567                    "btreeInitPage() returns error code %d", rc);
61568     releasePage(pPage);
61569     depth = -1;
61570     goto end_of_check;
61571   }
61572
61573   /* Check out all the cells.
61574   */
61575   depth = 0;
61576   for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
61577     u8 *pCell;
61578     u32 sz;
61579     CellInfo info;
61580
61581     /* Check payload overflow pages
61582     */
61583     pCheck->zPfx = "On tree page %d cell %d: ";
61584     pCheck->v1 = iPage;
61585     pCheck->v2 = i;
61586     pCell = findCell(pPage,i);
61587     btreeParseCellPtr(pPage, pCell, &info);
61588     sz = info.nPayload;
61589     /* For intKey pages, check that the keys are in order.
61590     */
61591     if( pPage->intKey ){
61592       if( i==0 ){
61593         nMinKey = nMaxKey = info.nKey;
61594       }else if( info.nKey <= nMaxKey ){
61595         checkAppendMsg(pCheck,
61596            "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
61597       }
61598       nMaxKey = info.nKey;
61599     }
61600     if( (sz>info.nLocal) 
61601      && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
61602     ){
61603       int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
61604       Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
61605 #ifndef SQLITE_OMIT_AUTOVACUUM
61606       if( pBt->autoVacuum ){
61607         checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
61608       }
61609 #endif
61610       checkList(pCheck, 0, pgnoOvfl, nPage);
61611     }
61612
61613     /* Check sanity of left child page.
61614     */
61615     if( !pPage->leaf ){
61616       pgno = get4byte(pCell);
61617 #ifndef SQLITE_OMIT_AUTOVACUUM
61618       if( pBt->autoVacuum ){
61619         checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
61620       }
61621 #endif
61622       d2 = checkTreePage(pCheck, pgno, &nMinKey, i==0?NULL:&nMaxKey);
61623       if( i>0 && d2!=depth ){
61624         checkAppendMsg(pCheck, "Child page depth differs");
61625       }
61626       depth = d2;
61627     }
61628   }
61629
61630   if( !pPage->leaf ){
61631     pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
61632     pCheck->zPfx = "On page %d at right child: ";
61633     pCheck->v1 = iPage;
61634 #ifndef SQLITE_OMIT_AUTOVACUUM
61635     if( pBt->autoVacuum ){
61636       checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
61637     }
61638 #endif
61639     checkTreePage(pCheck, pgno, NULL, !pPage->nCell?NULL:&nMaxKey);
61640   }
61641  
61642   /* For intKey leaf pages, check that the min/max keys are in order
61643   ** with any left/parent/right pages.
61644   */
61645   pCheck->zPfx = "Page %d: ";
61646   pCheck->v1 = iPage;
61647   if( pPage->leaf && pPage->intKey ){
61648     /* if we are a left child page */
61649     if( pnParentMinKey ){
61650       /* if we are the left most child page */
61651       if( !pnParentMaxKey ){
61652         if( nMaxKey > *pnParentMinKey ){
61653           checkAppendMsg(pCheck,
61654               "Rowid %lld out of order (max larger than parent min of %lld)",
61655               nMaxKey, *pnParentMinKey);
61656         }
61657       }else{
61658         if( nMinKey <= *pnParentMinKey ){
61659           checkAppendMsg(pCheck,
61660               "Rowid %lld out of order (min less than parent min of %lld)",
61661               nMinKey, *pnParentMinKey);
61662         }
61663         if( nMaxKey > *pnParentMaxKey ){
61664           checkAppendMsg(pCheck,
61665               "Rowid %lld out of order (max larger than parent max of %lld)",
61666               nMaxKey, *pnParentMaxKey);
61667         }
61668         *pnParentMinKey = nMaxKey;
61669       }
61670     /* else if we're a right child page */
61671     } else if( pnParentMaxKey ){
61672       if( nMinKey <= *pnParentMaxKey ){
61673         checkAppendMsg(pCheck,
61674             "Rowid %lld out of order (min less than parent max of %lld)",
61675             nMinKey, *pnParentMaxKey);
61676       }
61677     }
61678   }
61679
61680   /* Check for complete coverage of the page
61681   */
61682   data = pPage->aData;
61683   hdr = pPage->hdrOffset;
61684   hit = sqlite3PageMalloc( pBt->pageSize );
61685   pCheck->zPfx = 0;
61686   if( hit==0 ){
61687     pCheck->mallocFailed = 1;
61688   }else{
61689     int contentOffset = get2byteNotZero(&data[hdr+5]);
61690     assert( contentOffset<=usableSize );  /* Enforced by btreeInitPage() */
61691     memset(hit+contentOffset, 0, usableSize-contentOffset);
61692     memset(hit, 1, contentOffset);
61693     /* EVIDENCE-OF: R-37002-32774 The two-byte integer at offset 3 gives the
61694     ** number of cells on the page. */
61695     nCell = get2byte(&data[hdr+3]);
61696     /* EVIDENCE-OF: R-23882-45353 The cell pointer array of a b-tree page
61697     ** immediately follows the b-tree page header. */
61698     cellStart = hdr + 12 - 4*pPage->leaf;
61699     /* EVIDENCE-OF: R-02776-14802 The cell pointer array consists of K 2-byte
61700     ** integer offsets to the cell contents. */
61701     for(i=0; i<nCell; i++){
61702       int pc = get2byte(&data[cellStart+i*2]);
61703       u32 size = 65536;
61704       int j;
61705       if( pc<=usableSize-4 ){
61706         size = cellSizePtr(pPage, &data[pc]);
61707       }
61708       if( (int)(pc+size-1)>=usableSize ){
61709         pCheck->zPfx = 0;
61710         checkAppendMsg(pCheck,
61711             "Corruption detected in cell %d on page %d",i,iPage);
61712       }else{
61713         for(j=pc+size-1; j>=pc; j--) hit[j]++;
61714       }
61715     }
61716     /* EVIDENCE-OF: R-20690-50594 The second field of the b-tree page header
61717     ** is the offset of the first freeblock, or zero if there are no
61718     ** freeblocks on the page. */
61719     i = get2byte(&data[hdr+1]);
61720     while( i>0 ){
61721       int size, j;
61722       assert( i<=usableSize-4 );     /* Enforced by btreeInitPage() */
61723       size = get2byte(&data[i+2]);
61724       assert( i+size<=usableSize );  /* Enforced by btreeInitPage() */
61725       for(j=i+size-1; j>=i; j--) hit[j]++;
61726       /* EVIDENCE-OF: R-58208-19414 The first 2 bytes of a freeblock are a
61727       ** big-endian integer which is the offset in the b-tree page of the next
61728       ** freeblock in the chain, or zero if the freeblock is the last on the
61729       ** chain. */
61730       j = get2byte(&data[i]);
61731       /* EVIDENCE-OF: R-06866-39125 Freeblocks are always connected in order of
61732       ** increasing offset. */
61733       assert( j==0 || j>i+size );  /* Enforced by btreeInitPage() */
61734       assert( j<=usableSize-4 );   /* Enforced by btreeInitPage() */
61735       i = j;
61736     }
61737     for(i=cnt=0; i<usableSize; i++){
61738       if( hit[i]==0 ){
61739         cnt++;
61740       }else if( hit[i]>1 ){
61741         checkAppendMsg(pCheck,
61742           "Multiple uses for byte %d of page %d", i, iPage);
61743         break;
61744       }
61745     }
61746     /* EVIDENCE-OF: R-43263-13491 The total number of bytes in all fragments
61747     ** is stored in the fifth field of the b-tree page header.
61748     ** EVIDENCE-OF: R-07161-27322 The one-byte integer at offset 7 gives the
61749     ** number of fragmented free bytes within the cell content area.
61750     */
61751     if( cnt!=data[hdr+7] ){
61752       checkAppendMsg(pCheck,
61753           "Fragmentation of %d bytes reported as %d on page %d",
61754           cnt, data[hdr+7], iPage);
61755     }
61756   }
61757   sqlite3PageFree(hit);
61758   releasePage(pPage);
61759
61760 end_of_check:
61761   pCheck->zPfx = saved_zPfx;
61762   pCheck->v1 = saved_v1;
61763   pCheck->v2 = saved_v2;
61764   return depth+1;
61765 }
61766 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
61767
61768 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
61769 /*
61770 ** This routine does a complete check of the given BTree file.  aRoot[] is
61771 ** an array of pages numbers were each page number is the root page of
61772 ** a table.  nRoot is the number of entries in aRoot.
61773 **
61774 ** A read-only or read-write transaction must be opened before calling
61775 ** this function.
61776 **
61777 ** Write the number of error seen in *pnErr.  Except for some memory
61778 ** allocation errors,  an error message held in memory obtained from
61779 ** malloc is returned if *pnErr is non-zero.  If *pnErr==0 then NULL is
61780 ** returned.  If a memory allocation error occurs, NULL is returned.
61781 */
61782 SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
61783   Btree *p,     /* The btree to be checked */
61784   int *aRoot,   /* An array of root pages numbers for individual trees */
61785   int nRoot,    /* Number of entries in aRoot[] */
61786   int mxErr,    /* Stop reporting errors after this many */
61787   int *pnErr    /* Write number of errors seen to this variable */
61788 ){
61789   Pgno i;
61790   int nRef;
61791   IntegrityCk sCheck;
61792   BtShared *pBt = p->pBt;
61793   char zErr[100];
61794
61795   sqlite3BtreeEnter(p);
61796   assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
61797   nRef = sqlite3PagerRefcount(pBt->pPager);
61798   sCheck.pBt = pBt;
61799   sCheck.pPager = pBt->pPager;
61800   sCheck.nPage = btreePagecount(sCheck.pBt);
61801   sCheck.mxErr = mxErr;
61802   sCheck.nErr = 0;
61803   sCheck.mallocFailed = 0;
61804   sCheck.zPfx = 0;
61805   sCheck.v1 = 0;
61806   sCheck.v2 = 0;
61807   *pnErr = 0;
61808   if( sCheck.nPage==0 ){
61809     sqlite3BtreeLeave(p);
61810     return 0;
61811   }
61812
61813   sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
61814   if( !sCheck.aPgRef ){
61815     *pnErr = 1;
61816     sqlite3BtreeLeave(p);
61817     return 0;
61818   }
61819   i = PENDING_BYTE_PAGE(pBt);
61820   if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
61821   sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
61822   sCheck.errMsg.useMalloc = 2;
61823
61824   /* Check the integrity of the freelist
61825   */
61826   sCheck.zPfx = "Main freelist: ";
61827   checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
61828             get4byte(&pBt->pPage1->aData[36]));
61829   sCheck.zPfx = 0;
61830
61831   /* Check all the tables.
61832   */
61833   for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
61834     if( aRoot[i]==0 ) continue;
61835 #ifndef SQLITE_OMIT_AUTOVACUUM
61836     if( pBt->autoVacuum && aRoot[i]>1 ){
61837       checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
61838     }
61839 #endif
61840     sCheck.zPfx = "List of tree roots: ";
61841     checkTreePage(&sCheck, aRoot[i], NULL, NULL);
61842     sCheck.zPfx = 0;
61843   }
61844
61845   /* Make sure every page in the file is referenced
61846   */
61847   for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
61848 #ifdef SQLITE_OMIT_AUTOVACUUM
61849     if( getPageReferenced(&sCheck, i)==0 ){
61850       checkAppendMsg(&sCheck, "Page %d is never used", i);
61851     }
61852 #else
61853     /* If the database supports auto-vacuum, make sure no tables contain
61854     ** references to pointer-map pages.
61855     */
61856     if( getPageReferenced(&sCheck, i)==0 && 
61857        (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
61858       checkAppendMsg(&sCheck, "Page %d is never used", i);
61859     }
61860     if( getPageReferenced(&sCheck, i)!=0 && 
61861        (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
61862       checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
61863     }
61864 #endif
61865   }
61866
61867   /* Make sure this analysis did not leave any unref() pages.
61868   ** This is an internal consistency check; an integrity check
61869   ** of the integrity check.
61870   */
61871   if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
61872     checkAppendMsg(&sCheck,
61873       "Outstanding page count goes from %d to %d during this analysis",
61874       nRef, sqlite3PagerRefcount(pBt->pPager)
61875     );
61876   }
61877
61878   /* Clean  up and report errors.
61879   */
61880   sqlite3BtreeLeave(p);
61881   sqlite3_free(sCheck.aPgRef);
61882   if( sCheck.mallocFailed ){
61883     sqlite3StrAccumReset(&sCheck.errMsg);
61884     *pnErr = sCheck.nErr+1;
61885     return 0;
61886   }
61887   *pnErr = sCheck.nErr;
61888   if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
61889   return sqlite3StrAccumFinish(&sCheck.errMsg);
61890 }
61891 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
61892
61893 /*
61894 ** Return the full pathname of the underlying database file.  Return
61895 ** an empty string if the database is in-memory or a TEMP database.
61896 **
61897 ** The pager filename is invariant as long as the pager is
61898 ** open so it is safe to access without the BtShared mutex.
61899 */
61900 SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
61901   assert( p->pBt->pPager!=0 );
61902   return sqlite3PagerFilename(p->pBt->pPager, 1);
61903 }
61904
61905 /*
61906 ** Return the pathname of the journal file for this database. The return
61907 ** value of this routine is the same regardless of whether the journal file
61908 ** has been created or not.
61909 **
61910 ** The pager journal filename is invariant as long as the pager is
61911 ** open so it is safe to access without the BtShared mutex.
61912 */
61913 SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
61914   assert( p->pBt->pPager!=0 );
61915   return sqlite3PagerJournalname(p->pBt->pPager);
61916 }
61917
61918 /*
61919 ** Return non-zero if a transaction is active.
61920 */
61921 SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
61922   assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
61923   return (p && (p->inTrans==TRANS_WRITE));
61924 }
61925
61926 #ifndef SQLITE_OMIT_WAL
61927 /*
61928 ** Run a checkpoint on the Btree passed as the first argument.
61929 **
61930 ** Return SQLITE_LOCKED if this or any other connection has an open 
61931 ** transaction on the shared-cache the argument Btree is connected to.
61932 **
61933 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
61934 */
61935 SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
61936   int rc = SQLITE_OK;
61937   if( p ){
61938     BtShared *pBt = p->pBt;
61939     sqlite3BtreeEnter(p);
61940     if( pBt->inTransaction!=TRANS_NONE ){
61941       rc = SQLITE_LOCKED;
61942     }else{
61943       rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
61944     }
61945     sqlite3BtreeLeave(p);
61946   }
61947   return rc;
61948 }
61949 #endif
61950
61951 /*
61952 ** Return non-zero if a read (or write) transaction is active.
61953 */
61954 SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
61955   assert( p );
61956   assert( sqlite3_mutex_held(p->db->mutex) );
61957   return p->inTrans!=TRANS_NONE;
61958 }
61959
61960 SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
61961   assert( p );
61962   assert( sqlite3_mutex_held(p->db->mutex) );
61963   return p->nBackup!=0;
61964 }
61965
61966 /*
61967 ** This function returns a pointer to a blob of memory associated with
61968 ** a single shared-btree. The memory is used by client code for its own
61969 ** purposes (for example, to store a high-level schema associated with 
61970 ** the shared-btree). The btree layer manages reference counting issues.
61971 **
61972 ** The first time this is called on a shared-btree, nBytes bytes of memory
61973 ** are allocated, zeroed, and returned to the caller. For each subsequent 
61974 ** call the nBytes parameter is ignored and a pointer to the same blob
61975 ** of memory returned. 
61976 **
61977 ** If the nBytes parameter is 0 and the blob of memory has not yet been
61978 ** allocated, a null pointer is returned. If the blob has already been
61979 ** allocated, it is returned as normal.
61980 **
61981 ** Just before the shared-btree is closed, the function passed as the 
61982 ** xFree argument when the memory allocation was made is invoked on the 
61983 ** blob of allocated memory. The xFree function should not call sqlite3_free()
61984 ** on the memory, the btree layer does that.
61985 */
61986 SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
61987   BtShared *pBt = p->pBt;
61988   sqlite3BtreeEnter(p);
61989   if( !pBt->pSchema && nBytes ){
61990     pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
61991     pBt->xFreeSchema = xFree;
61992   }
61993   sqlite3BtreeLeave(p);
61994   return pBt->pSchema;
61995 }
61996
61997 /*
61998 ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared 
61999 ** btree as the argument handle holds an exclusive lock on the 
62000 ** sqlite_master table. Otherwise SQLITE_OK.
62001 */
62002 SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
62003   int rc;
62004   assert( sqlite3_mutex_held(p->db->mutex) );
62005   sqlite3BtreeEnter(p);
62006   rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
62007   assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
62008   sqlite3BtreeLeave(p);
62009   return rc;
62010 }
62011
62012
62013 #ifndef SQLITE_OMIT_SHARED_CACHE
62014 /*
62015 ** Obtain a lock on the table whose root page is iTab.  The
62016 ** lock is a write lock if isWritelock is true or a read lock
62017 ** if it is false.
62018 */
62019 SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
62020   int rc = SQLITE_OK;
62021   assert( p->inTrans!=TRANS_NONE );
62022   if( p->sharable ){
62023     u8 lockType = READ_LOCK + isWriteLock;
62024     assert( READ_LOCK+1==WRITE_LOCK );
62025     assert( isWriteLock==0 || isWriteLock==1 );
62026
62027     sqlite3BtreeEnter(p);
62028     rc = querySharedCacheTableLock(p, iTab, lockType);
62029     if( rc==SQLITE_OK ){
62030       rc = setSharedCacheTableLock(p, iTab, lockType);
62031     }
62032     sqlite3BtreeLeave(p);
62033   }
62034   return rc;
62035 }
62036 #endif
62037
62038 #ifndef SQLITE_OMIT_INCRBLOB
62039 /*
62040 ** Argument pCsr must be a cursor opened for writing on an 
62041 ** INTKEY table currently pointing at a valid table entry. 
62042 ** This function modifies the data stored as part of that entry.
62043 **
62044 ** Only the data content may only be modified, it is not possible to 
62045 ** change the length of the data stored. If this function is called with
62046 ** parameters that attempt to write past the end of the existing data,
62047 ** no modifications are made and SQLITE_CORRUPT is returned.
62048 */
62049 SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
62050   int rc;
62051   assert( cursorHoldsMutex(pCsr) );
62052   assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
62053   assert( pCsr->curFlags & BTCF_Incrblob );
62054
62055   rc = restoreCursorPosition(pCsr);
62056   if( rc!=SQLITE_OK ){
62057     return rc;
62058   }
62059   assert( pCsr->eState!=CURSOR_REQUIRESEEK );
62060   if( pCsr->eState!=CURSOR_VALID ){
62061     return SQLITE_ABORT;
62062   }
62063
62064   /* Save the positions of all other cursors open on this table. This is
62065   ** required in case any of them are holding references to an xFetch
62066   ** version of the b-tree page modified by the accessPayload call below.
62067   **
62068   ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
62069   ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
62070   ** saveAllCursors can only return SQLITE_OK.
62071   */
62072   VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
62073   assert( rc==SQLITE_OK );
62074
62075   /* Check some assumptions: 
62076   **   (a) the cursor is open for writing,
62077   **   (b) there is a read/write transaction open,
62078   **   (c) the connection holds a write-lock on the table (if required),
62079   **   (d) there are no conflicting read-locks, and
62080   **   (e) the cursor points at a valid row of an intKey table.
62081   */
62082   if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
62083     return SQLITE_READONLY;
62084   }
62085   assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
62086               && pCsr->pBt->inTransaction==TRANS_WRITE );
62087   assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
62088   assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
62089   assert( pCsr->apPage[pCsr->iPage]->intKey );
62090
62091   return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
62092 }
62093
62094 /* 
62095 ** Mark this cursor as an incremental blob cursor.
62096 */
62097 SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
62098   pCur->curFlags |= BTCF_Incrblob;
62099 }
62100 #endif
62101
62102 /*
62103 ** Set both the "read version" (single byte at byte offset 18) and 
62104 ** "write version" (single byte at byte offset 19) fields in the database
62105 ** header to iVersion.
62106 */
62107 SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
62108   BtShared *pBt = pBtree->pBt;
62109   int rc;                         /* Return code */
62110  
62111   assert( iVersion==1 || iVersion==2 );
62112
62113   /* If setting the version fields to 1, do not automatically open the
62114   ** WAL connection, even if the version fields are currently set to 2.
62115   */
62116   pBt->btsFlags &= ~BTS_NO_WAL;
62117   if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
62118
62119   rc = sqlite3BtreeBeginTrans(pBtree, 0);
62120   if( rc==SQLITE_OK ){
62121     u8 *aData = pBt->pPage1->aData;
62122     if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
62123       rc = sqlite3BtreeBeginTrans(pBtree, 2);
62124       if( rc==SQLITE_OK ){
62125         rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
62126         if( rc==SQLITE_OK ){
62127           aData[18] = (u8)iVersion;
62128           aData[19] = (u8)iVersion;
62129         }
62130       }
62131     }
62132   }
62133
62134   pBt->btsFlags &= ~BTS_NO_WAL;
62135   return rc;
62136 }
62137
62138 /*
62139 ** set the mask of hint flags for cursor pCsr.
62140 */
62141 SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
62142   assert( mask==BTREE_BULKLOAD || mask==BTREE_SEEK_EQ || mask==0 );
62143   pCsr->hints = mask;
62144 }
62145
62146 #ifdef SQLITE_DEBUG
62147 /*
62148 ** Return true if the cursor has a hint specified.  This routine is
62149 ** only used from within assert() statements
62150 */
62151 SQLITE_PRIVATE int sqlite3BtreeCursorHasHint(BtCursor *pCsr, unsigned int mask){
62152   return (pCsr->hints & mask)!=0;
62153 }
62154 #endif
62155
62156 /*
62157 ** Return true if the given Btree is read-only.
62158 */
62159 SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
62160   return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
62161 }
62162
62163 /*
62164 ** Return the size of the header added to each page by this module.
62165 */
62166 SQLITE_PRIVATE int sqlite3HeaderSizeBtree(void){ return ROUND8(sizeof(MemPage)); }
62167
62168 /************** End of btree.c ***********************************************/
62169 /************** Begin file backup.c ******************************************/
62170 /*
62171 ** 2009 January 28
62172 **
62173 ** The author disclaims copyright to this source code.  In place of
62174 ** a legal notice, here is a blessing:
62175 **
62176 **    May you do good and not evil.
62177 **    May you find forgiveness for yourself and forgive others.
62178 **    May you share freely, never taking more than you give.
62179 **
62180 *************************************************************************
62181 ** This file contains the implementation of the sqlite3_backup_XXX() 
62182 ** API functions and the related features.
62183 */
62184
62185 /*
62186 ** Structure allocated for each backup operation.
62187 */
62188 struct sqlite3_backup {
62189   sqlite3* pDestDb;        /* Destination database handle */
62190   Btree *pDest;            /* Destination b-tree file */
62191   u32 iDestSchema;         /* Original schema cookie in destination */
62192   int bDestLocked;         /* True once a write-transaction is open on pDest */
62193
62194   Pgno iNext;              /* Page number of the next source page to copy */
62195   sqlite3* pSrcDb;         /* Source database handle */
62196   Btree *pSrc;             /* Source b-tree file */
62197
62198   int rc;                  /* Backup process error code */
62199
62200   /* These two variables are set by every call to backup_step(). They are
62201   ** read by calls to backup_remaining() and backup_pagecount().
62202   */
62203   Pgno nRemaining;         /* Number of pages left to copy */
62204   Pgno nPagecount;         /* Total number of pages to copy */
62205
62206   int isAttached;          /* True once backup has been registered with pager */
62207   sqlite3_backup *pNext;   /* Next backup associated with source pager */
62208 };
62209
62210 /*
62211 ** THREAD SAFETY NOTES:
62212 **
62213 **   Once it has been created using backup_init(), a single sqlite3_backup
62214 **   structure may be accessed via two groups of thread-safe entry points:
62215 **
62216 **     * Via the sqlite3_backup_XXX() API function backup_step() and 
62217 **       backup_finish(). Both these functions obtain the source database
62218 **       handle mutex and the mutex associated with the source BtShared 
62219 **       structure, in that order.
62220 **
62221 **     * Via the BackupUpdate() and BackupRestart() functions, which are
62222 **       invoked by the pager layer to report various state changes in
62223 **       the page cache associated with the source database. The mutex
62224 **       associated with the source database BtShared structure will always 
62225 **       be held when either of these functions are invoked.
62226 **
62227 **   The other sqlite3_backup_XXX() API functions, backup_remaining() and
62228 **   backup_pagecount() are not thread-safe functions. If they are called
62229 **   while some other thread is calling backup_step() or backup_finish(),
62230 **   the values returned may be invalid. There is no way for a call to
62231 **   BackupUpdate() or BackupRestart() to interfere with backup_remaining()
62232 **   or backup_pagecount().
62233 **
62234 **   Depending on the SQLite configuration, the database handles and/or
62235 **   the Btree objects may have their own mutexes that require locking.
62236 **   Non-sharable Btrees (in-memory databases for example), do not have
62237 **   associated mutexes.
62238 */
62239
62240 /*
62241 ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
62242 ** in connection handle pDb. If such a database cannot be found, return
62243 ** a NULL pointer and write an error message to pErrorDb.
62244 **
62245 ** If the "temp" database is requested, it may need to be opened by this 
62246 ** function. If an error occurs while doing so, return 0 and write an 
62247 ** error message to pErrorDb.
62248 */
62249 static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
62250   int i = sqlite3FindDbName(pDb, zDb);
62251
62252   if( i==1 ){
62253     Parse *pParse;
62254     int rc = 0;
62255     pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
62256     if( pParse==0 ){
62257       sqlite3ErrorWithMsg(pErrorDb, SQLITE_NOMEM, "out of memory");
62258       rc = SQLITE_NOMEM;
62259     }else{
62260       pParse->db = pDb;
62261       if( sqlite3OpenTempDatabase(pParse) ){
62262         sqlite3ErrorWithMsg(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
62263         rc = SQLITE_ERROR;
62264       }
62265       sqlite3DbFree(pErrorDb, pParse->zErrMsg);
62266       sqlite3ParserReset(pParse);
62267       sqlite3StackFree(pErrorDb, pParse);
62268     }
62269     if( rc ){
62270       return 0;
62271     }
62272   }
62273
62274   if( i<0 ){
62275     sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
62276     return 0;
62277   }
62278
62279   return pDb->aDb[i].pBt;
62280 }
62281
62282 /*
62283 ** Attempt to set the page size of the destination to match the page size
62284 ** of the source.
62285 */
62286 static int setDestPgsz(sqlite3_backup *p){
62287   int rc;
62288   rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
62289   return rc;
62290 }
62291
62292 /*
62293 ** Check that there is no open read-transaction on the b-tree passed as the
62294 ** second argument. If there is not, return SQLITE_OK. Otherwise, if there
62295 ** is an open read-transaction, return SQLITE_ERROR and leave an error 
62296 ** message in database handle db.
62297 */
62298 static int checkReadTransaction(sqlite3 *db, Btree *p){
62299   if( sqlite3BtreeIsInReadTrans(p) ){
62300     sqlite3ErrorWithMsg(db, SQLITE_ERROR, "destination database is in use");
62301     return SQLITE_ERROR;
62302   }
62303   return SQLITE_OK;
62304 }
62305
62306 /*
62307 ** Create an sqlite3_backup process to copy the contents of zSrcDb from
62308 ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
62309 ** a pointer to the new sqlite3_backup object.
62310 **
62311 ** If an error occurs, NULL is returned and an error code and error message
62312 ** stored in database handle pDestDb.
62313 */
62314 SQLITE_API sqlite3_backup *SQLITE_STDCALL sqlite3_backup_init(
62315   sqlite3* pDestDb,                     /* Database to write to */
62316   const char *zDestDb,                  /* Name of database within pDestDb */
62317   sqlite3* pSrcDb,                      /* Database connection to read from */
62318   const char *zSrcDb                    /* Name of database within pSrcDb */
62319 ){
62320   sqlite3_backup *p;                    /* Value to return */
62321
62322 #ifdef SQLITE_ENABLE_API_ARMOR
62323   if( !sqlite3SafetyCheckOk(pSrcDb)||!sqlite3SafetyCheckOk(pDestDb) ){
62324     (void)SQLITE_MISUSE_BKPT;
62325     return 0;
62326   }
62327 #endif
62328
62329   /* Lock the source database handle. The destination database
62330   ** handle is not locked in this routine, but it is locked in
62331   ** sqlite3_backup_step(). The user is required to ensure that no
62332   ** other thread accesses the destination handle for the duration
62333   ** of the backup operation.  Any attempt to use the destination
62334   ** database connection while a backup is in progress may cause
62335   ** a malfunction or a deadlock.
62336   */
62337   sqlite3_mutex_enter(pSrcDb->mutex);
62338   sqlite3_mutex_enter(pDestDb->mutex);
62339
62340   if( pSrcDb==pDestDb ){
62341     sqlite3ErrorWithMsg(
62342         pDestDb, SQLITE_ERROR, "source and destination must be distinct"
62343     );
62344     p = 0;
62345   }else {
62346     /* Allocate space for a new sqlite3_backup object...
62347     ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
62348     ** call to sqlite3_backup_init() and is destroyed by a call to
62349     ** sqlite3_backup_finish(). */
62350     p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
62351     if( !p ){
62352       sqlite3Error(pDestDb, SQLITE_NOMEM);
62353     }
62354   }
62355
62356   /* If the allocation succeeded, populate the new object. */
62357   if( p ){
62358     p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
62359     p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
62360     p->pDestDb = pDestDb;
62361     p->pSrcDb = pSrcDb;
62362     p->iNext = 1;
62363     p->isAttached = 0;
62364
62365     if( 0==p->pSrc || 0==p->pDest 
62366      || setDestPgsz(p)==SQLITE_NOMEM 
62367      || checkReadTransaction(pDestDb, p->pDest)!=SQLITE_OK 
62368      ){
62369       /* One (or both) of the named databases did not exist or an OOM
62370       ** error was hit. Or there is a transaction open on the destination
62371       ** database. The error has already been written into the pDestDb 
62372       ** handle. All that is left to do here is free the sqlite3_backup 
62373       ** structure.  */
62374       sqlite3_free(p);
62375       p = 0;
62376     }
62377   }
62378   if( p ){
62379     p->pSrc->nBackup++;
62380   }
62381
62382   sqlite3_mutex_leave(pDestDb->mutex);
62383   sqlite3_mutex_leave(pSrcDb->mutex);
62384   return p;
62385 }
62386
62387 /*
62388 ** Argument rc is an SQLite error code. Return true if this error is 
62389 ** considered fatal if encountered during a backup operation. All errors
62390 ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
62391 */
62392 static int isFatalError(int rc){
62393   return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
62394 }
62395
62396 /*
62397 ** Parameter zSrcData points to a buffer containing the data for 
62398 ** page iSrcPg from the source database. Copy this data into the 
62399 ** destination database.
62400 */
62401 static int backupOnePage(
62402   sqlite3_backup *p,              /* Backup handle */
62403   Pgno iSrcPg,                    /* Source database page to backup */
62404   const u8 *zSrcData,             /* Source database page data */
62405   int bUpdate                     /* True for an update, false otherwise */
62406 ){
62407   Pager * const pDestPager = sqlite3BtreePager(p->pDest);
62408   const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
62409   int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
62410   const int nCopy = MIN(nSrcPgsz, nDestPgsz);
62411   const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
62412 #ifdef SQLITE_HAS_CODEC
62413   /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
62414   ** guaranteed that the shared-mutex is held by this thread, handle
62415   ** p->pSrc may not actually be the owner.  */
62416   int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
62417   int nDestReserve = sqlite3BtreeGetOptimalReserve(p->pDest);
62418 #endif
62419   int rc = SQLITE_OK;
62420   i64 iOff;
62421
62422   assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
62423   assert( p->bDestLocked );
62424   assert( !isFatalError(p->rc) );
62425   assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
62426   assert( zSrcData );
62427
62428   /* Catch the case where the destination is an in-memory database and the
62429   ** page sizes of the source and destination differ. 
62430   */
62431   if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
62432     rc = SQLITE_READONLY;
62433   }
62434
62435 #ifdef SQLITE_HAS_CODEC
62436   /* Backup is not possible if the page size of the destination is changing
62437   ** and a codec is in use.
62438   */
62439   if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
62440     rc = SQLITE_READONLY;
62441   }
62442
62443   /* Backup is not possible if the number of bytes of reserve space differ
62444   ** between source and destination.  If there is a difference, try to
62445   ** fix the destination to agree with the source.  If that is not possible,
62446   ** then the backup cannot proceed.
62447   */
62448   if( nSrcReserve!=nDestReserve ){
62449     u32 newPgsz = nSrcPgsz;
62450     rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
62451     if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
62452   }
62453 #endif
62454
62455   /* This loop runs once for each destination page spanned by the source 
62456   ** page. For each iteration, variable iOff is set to the byte offset
62457   ** of the destination page.
62458   */
62459   for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
62460     DbPage *pDestPg = 0;
62461     Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
62462     if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
62463     if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
62464      && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
62465     ){
62466       const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
62467       u8 *zDestData = sqlite3PagerGetData(pDestPg);
62468       u8 *zOut = &zDestData[iOff%nDestPgsz];
62469
62470       /* Copy the data from the source page into the destination page.
62471       ** Then clear the Btree layer MemPage.isInit flag. Both this module
62472       ** and the pager code use this trick (clearing the first byte
62473       ** of the page 'extra' space to invalidate the Btree layers
62474       ** cached parse of the page). MemPage.isInit is marked 
62475       ** "MUST BE FIRST" for this purpose.
62476       */
62477       memcpy(zOut, zIn, nCopy);
62478       ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
62479       if( iOff==0 && bUpdate==0 ){
62480         sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
62481       }
62482     }
62483     sqlite3PagerUnref(pDestPg);
62484   }
62485
62486   return rc;
62487 }
62488
62489 /*
62490 ** If pFile is currently larger than iSize bytes, then truncate it to
62491 ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
62492 ** this function is a no-op.
62493 **
62494 ** Return SQLITE_OK if everything is successful, or an SQLite error 
62495 ** code if an error occurs.
62496 */
62497 static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
62498   i64 iCurrent;
62499   int rc = sqlite3OsFileSize(pFile, &iCurrent);
62500   if( rc==SQLITE_OK && iCurrent>iSize ){
62501     rc = sqlite3OsTruncate(pFile, iSize);
62502   }
62503   return rc;
62504 }
62505
62506 /*
62507 ** Register this backup object with the associated source pager for
62508 ** callbacks when pages are changed or the cache invalidated.
62509 */
62510 static void attachBackupObject(sqlite3_backup *p){
62511   sqlite3_backup **pp;
62512   assert( sqlite3BtreeHoldsMutex(p->pSrc) );
62513   pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
62514   p->pNext = *pp;
62515   *pp = p;
62516   p->isAttached = 1;
62517 }
62518
62519 /*
62520 ** Copy nPage pages from the source b-tree to the destination.
62521 */
62522 SQLITE_API int SQLITE_STDCALL sqlite3_backup_step(sqlite3_backup *p, int nPage){
62523   int rc;
62524   int destMode;       /* Destination journal mode */
62525   int pgszSrc = 0;    /* Source page size */
62526   int pgszDest = 0;   /* Destination page size */
62527
62528 #ifdef SQLITE_ENABLE_API_ARMOR
62529   if( p==0 ) return SQLITE_MISUSE_BKPT;
62530 #endif
62531   sqlite3_mutex_enter(p->pSrcDb->mutex);
62532   sqlite3BtreeEnter(p->pSrc);
62533   if( p->pDestDb ){
62534     sqlite3_mutex_enter(p->pDestDb->mutex);
62535   }
62536
62537   rc = p->rc;
62538   if( !isFatalError(rc) ){
62539     Pager * const pSrcPager = sqlite3BtreePager(p->pSrc);     /* Source pager */
62540     Pager * const pDestPager = sqlite3BtreePager(p->pDest);   /* Dest pager */
62541     int ii;                            /* Iterator variable */
62542     int nSrcPage = -1;                 /* Size of source db in pages */
62543     int bCloseTrans = 0;               /* True if src db requires unlocking */
62544
62545     /* If the source pager is currently in a write-transaction, return
62546     ** SQLITE_BUSY immediately.
62547     */
62548     if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
62549       rc = SQLITE_BUSY;
62550     }else{
62551       rc = SQLITE_OK;
62552     }
62553
62554     /* Lock the destination database, if it is not locked already. */
62555     if( SQLITE_OK==rc && p->bDestLocked==0
62556      && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2)) 
62557     ){
62558       p->bDestLocked = 1;
62559       sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
62560     }
62561
62562     /* If there is no open read-transaction on the source database, open
62563     ** one now. If a transaction is opened here, then it will be closed
62564     ** before this function exits.
62565     */
62566     if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
62567       rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
62568       bCloseTrans = 1;
62569     }
62570
62571     /* Do not allow backup if the destination database is in WAL mode
62572     ** and the page sizes are different between source and destination */
62573     pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
62574     pgszDest = sqlite3BtreeGetPageSize(p->pDest);
62575     destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
62576     if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
62577       rc = SQLITE_READONLY;
62578     }
62579   
62580     /* Now that there is a read-lock on the source database, query the
62581     ** source pager for the number of pages in the database.
62582     */
62583     nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
62584     assert( nSrcPage>=0 );
62585     for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
62586       const Pgno iSrcPg = p->iNext;                 /* Source page number */
62587       if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
62588         DbPage *pSrcPg;                             /* Source page object */
62589         rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
62590                                  PAGER_GET_READONLY);
62591         if( rc==SQLITE_OK ){
62592           rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
62593           sqlite3PagerUnref(pSrcPg);
62594         }
62595       }
62596       p->iNext++;
62597     }
62598     if( rc==SQLITE_OK ){
62599       p->nPagecount = nSrcPage;
62600       p->nRemaining = nSrcPage+1-p->iNext;
62601       if( p->iNext>(Pgno)nSrcPage ){
62602         rc = SQLITE_DONE;
62603       }else if( !p->isAttached ){
62604         attachBackupObject(p);
62605       }
62606     }
62607   
62608     /* Update the schema version field in the destination database. This
62609     ** is to make sure that the schema-version really does change in
62610     ** the case where the source and destination databases have the
62611     ** same schema version.
62612     */
62613     if( rc==SQLITE_DONE ){
62614       if( nSrcPage==0 ){
62615         rc = sqlite3BtreeNewDb(p->pDest);
62616         nSrcPage = 1;
62617       }
62618       if( rc==SQLITE_OK || rc==SQLITE_DONE ){
62619         rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
62620       }
62621       if( rc==SQLITE_OK ){
62622         if( p->pDestDb ){
62623           sqlite3ResetAllSchemasOfConnection(p->pDestDb);
62624         }
62625         if( destMode==PAGER_JOURNALMODE_WAL ){
62626           rc = sqlite3BtreeSetVersion(p->pDest, 2);
62627         }
62628       }
62629       if( rc==SQLITE_OK ){
62630         int nDestTruncate;
62631         /* Set nDestTruncate to the final number of pages in the destination
62632         ** database. The complication here is that the destination page
62633         ** size may be different to the source page size. 
62634         **
62635         ** If the source page size is smaller than the destination page size, 
62636         ** round up. In this case the call to sqlite3OsTruncate() below will
62637         ** fix the size of the file. However it is important to call
62638         ** sqlite3PagerTruncateImage() here so that any pages in the 
62639         ** destination file that lie beyond the nDestTruncate page mark are
62640         ** journalled by PagerCommitPhaseOne() before they are destroyed
62641         ** by the file truncation.
62642         */
62643         assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
62644         assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
62645         if( pgszSrc<pgszDest ){
62646           int ratio = pgszDest/pgszSrc;
62647           nDestTruncate = (nSrcPage+ratio-1)/ratio;
62648           if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
62649             nDestTruncate--;
62650           }
62651         }else{
62652           nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
62653         }
62654         assert( nDestTruncate>0 );
62655
62656         if( pgszSrc<pgszDest ){
62657           /* If the source page-size is smaller than the destination page-size,
62658           ** two extra things may need to happen:
62659           **
62660           **   * The destination may need to be truncated, and
62661           **
62662           **   * Data stored on the pages immediately following the 
62663           **     pending-byte page in the source database may need to be
62664           **     copied into the destination database.
62665           */
62666           const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
62667           sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
62668           Pgno iPg;
62669           int nDstPage;
62670           i64 iOff;
62671           i64 iEnd;
62672
62673           assert( pFile );
62674           assert( nDestTruncate==0 
62675               || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
62676                 nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
62677              && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
62678           ));
62679
62680           /* This block ensures that all data required to recreate the original
62681           ** database has been stored in the journal for pDestPager and the
62682           ** journal synced to disk. So at this point we may safely modify
62683           ** the database file in any way, knowing that if a power failure
62684           ** occurs, the original database will be reconstructed from the 
62685           ** journal file.  */
62686           sqlite3PagerPagecount(pDestPager, &nDstPage);
62687           for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
62688             if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
62689               DbPage *pPg;
62690               rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
62691               if( rc==SQLITE_OK ){
62692                 rc = sqlite3PagerWrite(pPg);
62693                 sqlite3PagerUnref(pPg);
62694               }
62695             }
62696           }
62697           if( rc==SQLITE_OK ){
62698             rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
62699           }
62700
62701           /* Write the extra pages and truncate the database file as required */
62702           iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
62703           for(
62704             iOff=PENDING_BYTE+pgszSrc; 
62705             rc==SQLITE_OK && iOff<iEnd; 
62706             iOff+=pgszSrc
62707           ){
62708             PgHdr *pSrcPg = 0;
62709             const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
62710             rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
62711             if( rc==SQLITE_OK ){
62712               u8 *zData = sqlite3PagerGetData(pSrcPg);
62713               rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
62714             }
62715             sqlite3PagerUnref(pSrcPg);
62716           }
62717           if( rc==SQLITE_OK ){
62718             rc = backupTruncateFile(pFile, iSize);
62719           }
62720
62721           /* Sync the database file to disk. */
62722           if( rc==SQLITE_OK ){
62723             rc = sqlite3PagerSync(pDestPager, 0);
62724           }
62725         }else{
62726           sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
62727           rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
62728         }
62729     
62730         /* Finish committing the transaction to the destination database. */
62731         if( SQLITE_OK==rc
62732          && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
62733         ){
62734           rc = SQLITE_DONE;
62735         }
62736       }
62737     }
62738   
62739     /* If bCloseTrans is true, then this function opened a read transaction
62740     ** on the source database. Close the read transaction here. There is
62741     ** no need to check the return values of the btree methods here, as
62742     ** "committing" a read-only transaction cannot fail.
62743     */
62744     if( bCloseTrans ){
62745       TESTONLY( int rc2 );
62746       TESTONLY( rc2  = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
62747       TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
62748       assert( rc2==SQLITE_OK );
62749     }
62750   
62751     if( rc==SQLITE_IOERR_NOMEM ){
62752       rc = SQLITE_NOMEM;
62753     }
62754     p->rc = rc;
62755   }
62756   if( p->pDestDb ){
62757     sqlite3_mutex_leave(p->pDestDb->mutex);
62758   }
62759   sqlite3BtreeLeave(p->pSrc);
62760   sqlite3_mutex_leave(p->pSrcDb->mutex);
62761   return rc;
62762 }
62763
62764 /*
62765 ** Release all resources associated with an sqlite3_backup* handle.
62766 */
62767 SQLITE_API int SQLITE_STDCALL sqlite3_backup_finish(sqlite3_backup *p){
62768   sqlite3_backup **pp;                 /* Ptr to head of pagers backup list */
62769   sqlite3 *pSrcDb;                     /* Source database connection */
62770   int rc;                              /* Value to return */
62771
62772   /* Enter the mutexes */
62773   if( p==0 ) return SQLITE_OK;
62774   pSrcDb = p->pSrcDb;
62775   sqlite3_mutex_enter(pSrcDb->mutex);
62776   sqlite3BtreeEnter(p->pSrc);
62777   if( p->pDestDb ){
62778     sqlite3_mutex_enter(p->pDestDb->mutex);
62779   }
62780
62781   /* Detach this backup from the source pager. */
62782   if( p->pDestDb ){
62783     p->pSrc->nBackup--;
62784   }
62785   if( p->isAttached ){
62786     pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
62787     while( *pp!=p ){
62788       pp = &(*pp)->pNext;
62789     }
62790     *pp = p->pNext;
62791   }
62792
62793   /* If a transaction is still open on the Btree, roll it back. */
62794   sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
62795
62796   /* Set the error code of the destination database handle. */
62797   rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
62798   if( p->pDestDb ){
62799     sqlite3Error(p->pDestDb, rc);
62800
62801     /* Exit the mutexes and free the backup context structure. */
62802     sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
62803   }
62804   sqlite3BtreeLeave(p->pSrc);
62805   if( p->pDestDb ){
62806     /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
62807     ** call to sqlite3_backup_init() and is destroyed by a call to
62808     ** sqlite3_backup_finish(). */
62809     sqlite3_free(p);
62810   }
62811   sqlite3LeaveMutexAndCloseZombie(pSrcDb);
62812   return rc;
62813 }
62814
62815 /*
62816 ** Return the number of pages still to be backed up as of the most recent
62817 ** call to sqlite3_backup_step().
62818 */
62819 SQLITE_API int SQLITE_STDCALL sqlite3_backup_remaining(sqlite3_backup *p){
62820 #ifdef SQLITE_ENABLE_API_ARMOR
62821   if( p==0 ){
62822     (void)SQLITE_MISUSE_BKPT;
62823     return 0;
62824   }
62825 #endif
62826   return p->nRemaining;
62827 }
62828
62829 /*
62830 ** Return the total number of pages in the source database as of the most 
62831 ** recent call to sqlite3_backup_step().
62832 */
62833 SQLITE_API int SQLITE_STDCALL sqlite3_backup_pagecount(sqlite3_backup *p){
62834 #ifdef SQLITE_ENABLE_API_ARMOR
62835   if( p==0 ){
62836     (void)SQLITE_MISUSE_BKPT;
62837     return 0;
62838   }
62839 #endif
62840   return p->nPagecount;
62841 }
62842
62843 /*
62844 ** This function is called after the contents of page iPage of the
62845 ** source database have been modified. If page iPage has already been 
62846 ** copied into the destination database, then the data written to the
62847 ** destination is now invalidated. The destination copy of iPage needs
62848 ** to be updated with the new data before the backup operation is
62849 ** complete.
62850 **
62851 ** It is assumed that the mutex associated with the BtShared object
62852 ** corresponding to the source database is held when this function is
62853 ** called.
62854 */
62855 SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
62856   sqlite3_backup *p;                   /* Iterator variable */
62857   for(p=pBackup; p; p=p->pNext){
62858     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
62859     if( !isFatalError(p->rc) && iPage<p->iNext ){
62860       /* The backup process p has already copied page iPage. But now it
62861       ** has been modified by a transaction on the source pager. Copy
62862       ** the new data into the backup.
62863       */
62864       int rc;
62865       assert( p->pDestDb );
62866       sqlite3_mutex_enter(p->pDestDb->mutex);
62867       rc = backupOnePage(p, iPage, aData, 1);
62868       sqlite3_mutex_leave(p->pDestDb->mutex);
62869       assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
62870       if( rc!=SQLITE_OK ){
62871         p->rc = rc;
62872       }
62873     }
62874   }
62875 }
62876
62877 /*
62878 ** Restart the backup process. This is called when the pager layer
62879 ** detects that the database has been modified by an external database
62880 ** connection. In this case there is no way of knowing which of the
62881 ** pages that have been copied into the destination database are still 
62882 ** valid and which are not, so the entire process needs to be restarted.
62883 **
62884 ** It is assumed that the mutex associated with the BtShared object
62885 ** corresponding to the source database is held when this function is
62886 ** called.
62887 */
62888 SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
62889   sqlite3_backup *p;                   /* Iterator variable */
62890   for(p=pBackup; p; p=p->pNext){
62891     assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
62892     p->iNext = 1;
62893   }
62894 }
62895
62896 #ifndef SQLITE_OMIT_VACUUM
62897 /*
62898 ** Copy the complete content of pBtFrom into pBtTo.  A transaction
62899 ** must be active for both files.
62900 **
62901 ** The size of file pTo may be reduced by this operation. If anything 
62902 ** goes wrong, the transaction on pTo is rolled back. If successful, the 
62903 ** transaction is committed before returning.
62904 */
62905 SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
62906   int rc;
62907   sqlite3_file *pFd;              /* File descriptor for database pTo */
62908   sqlite3_backup b;
62909   sqlite3BtreeEnter(pTo);
62910   sqlite3BtreeEnter(pFrom);
62911
62912   assert( sqlite3BtreeIsInTrans(pTo) );
62913   pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
62914   if( pFd->pMethods ){
62915     i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
62916     rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
62917     if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
62918     if( rc ) goto copy_finished;
62919   }
62920
62921   /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
62922   ** to 0. This is used by the implementations of sqlite3_backup_step()
62923   ** and sqlite3_backup_finish() to detect that they are being called
62924   ** from this function, not directly by the user.
62925   */
62926   memset(&b, 0, sizeof(b));
62927   b.pSrcDb = pFrom->db;
62928   b.pSrc = pFrom;
62929   b.pDest = pTo;
62930   b.iNext = 1;
62931
62932   /* 0x7FFFFFFF is the hard limit for the number of pages in a database
62933   ** file. By passing this as the number of pages to copy to
62934   ** sqlite3_backup_step(), we can guarantee that the copy finishes 
62935   ** within a single call (unless an error occurs). The assert() statement
62936   ** checks this assumption - (p->rc) should be set to either SQLITE_DONE 
62937   ** or an error code.
62938   */
62939   sqlite3_backup_step(&b, 0x7FFFFFFF);
62940   assert( b.rc!=SQLITE_OK );
62941   rc = sqlite3_backup_finish(&b);
62942   if( rc==SQLITE_OK ){
62943     pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
62944   }else{
62945     sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
62946   }
62947
62948   assert( sqlite3BtreeIsInTrans(pTo)==0 );
62949 copy_finished:
62950   sqlite3BtreeLeave(pFrom);
62951   sqlite3BtreeLeave(pTo);
62952   return rc;
62953 }
62954 #endif /* SQLITE_OMIT_VACUUM */
62955
62956 /************** End of backup.c **********************************************/
62957 /************** Begin file vdbemem.c *****************************************/
62958 /*
62959 ** 2004 May 26
62960 **
62961 ** The author disclaims copyright to this source code.  In place of
62962 ** a legal notice, here is a blessing:
62963 **
62964 **    May you do good and not evil.
62965 **    May you find forgiveness for yourself and forgive others.
62966 **    May you share freely, never taking more than you give.
62967 **
62968 *************************************************************************
62969 **
62970 ** This file contains code use to manipulate "Mem" structure.  A "Mem"
62971 ** stores a single value in the VDBE.  Mem is an opaque structure visible
62972 ** only within the VDBE.  Interface routines refer to a Mem using the
62973 ** name sqlite_value
62974 */
62975
62976 #ifdef SQLITE_DEBUG
62977 /*
62978 ** Check invariants on a Mem object.
62979 **
62980 ** This routine is intended for use inside of assert() statements, like
62981 ** this:    assert( sqlite3VdbeCheckMemInvariants(pMem) );
62982 */
62983 SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
62984   /* If MEM_Dyn is set then Mem.xDel!=0.  
62985   ** Mem.xDel is might not be initialized if MEM_Dyn is clear.
62986   */
62987   assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
62988
62989   /* MEM_Dyn may only be set if Mem.szMalloc==0.  In this way we
62990   ** ensure that if Mem.szMalloc>0 then it is safe to do
62991   ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
62992   ** That saves a few cycles in inner loops. */
62993   assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
62994
62995   /* Cannot be both MEM_Int and MEM_Real at the same time */
62996   assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
62997
62998   /* The szMalloc field holds the correct memory allocation size */
62999   assert( p->szMalloc==0
63000        || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
63001
63002   /* If p holds a string or blob, the Mem.z must point to exactly
63003   ** one of the following:
63004   **
63005   **   (1) Memory in Mem.zMalloc and managed by the Mem object
63006   **   (2) Memory to be freed using Mem.xDel
63007   **   (3) An ephemeral string or blob
63008   **   (4) A static string or blob
63009   */
63010   if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
63011     assert( 
63012       ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
63013       ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
63014       ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
63015       ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
63016     );
63017   }
63018   return 1;
63019 }
63020 #endif
63021
63022
63023 /*
63024 ** If pMem is an object with a valid string representation, this routine
63025 ** ensures the internal encoding for the string representation is
63026 ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
63027 **
63028 ** If pMem is not a string object, or the encoding of the string
63029 ** representation is already stored using the requested encoding, then this
63030 ** routine is a no-op.
63031 **
63032 ** SQLITE_OK is returned if the conversion is successful (or not required).
63033 ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
63034 ** between formats.
63035 */
63036 SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
63037 #ifndef SQLITE_OMIT_UTF16
63038   int rc;
63039 #endif
63040   assert( (pMem->flags&MEM_RowSet)==0 );
63041   assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
63042            || desiredEnc==SQLITE_UTF16BE );
63043   if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
63044     return SQLITE_OK;
63045   }
63046   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63047 #ifdef SQLITE_OMIT_UTF16
63048   return SQLITE_ERROR;
63049 #else
63050
63051   /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
63052   ** then the encoding of the value may not have changed.
63053   */
63054   rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
63055   assert(rc==SQLITE_OK    || rc==SQLITE_NOMEM);
63056   assert(rc==SQLITE_OK    || pMem->enc!=desiredEnc);
63057   assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
63058   return rc;
63059 #endif
63060 }
63061
63062 /*
63063 ** Make sure pMem->z points to a writable allocation of at least 
63064 ** min(n,32) bytes.
63065 **
63066 ** If the bPreserve argument is true, then copy of the content of
63067 ** pMem->z into the new allocation.  pMem must be either a string or
63068 ** blob if bPreserve is true.  If bPreserve is false, any prior content
63069 ** in pMem->z is discarded.
63070 */
63071 SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
63072   assert( sqlite3VdbeCheckMemInvariants(pMem) );
63073   assert( (pMem->flags&MEM_RowSet)==0 );
63074
63075   /* If the bPreserve flag is set to true, then the memory cell must already
63076   ** contain a valid string or blob value.  */
63077   assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
63078   testcase( bPreserve && pMem->z==0 );
63079
63080   assert( pMem->szMalloc==0
63081        || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
63082   if( pMem->szMalloc<n ){
63083     if( n<32 ) n = 32;
63084     if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){
63085       pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
63086       bPreserve = 0;
63087     }else{
63088       if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
63089       pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
63090     }
63091     if( pMem->zMalloc==0 ){
63092       sqlite3VdbeMemSetNull(pMem);
63093       pMem->z = 0;
63094       pMem->szMalloc = 0;
63095       return SQLITE_NOMEM;
63096     }else{
63097       pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
63098     }
63099   }
63100
63101   if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){
63102     memcpy(pMem->zMalloc, pMem->z, pMem->n);
63103   }
63104   if( (pMem->flags&MEM_Dyn)!=0 ){
63105     assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
63106     pMem->xDel((void *)(pMem->z));
63107   }
63108
63109   pMem->z = pMem->zMalloc;
63110   pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
63111   return SQLITE_OK;
63112 }
63113
63114 /*
63115 ** Change the pMem->zMalloc allocation to be at least szNew bytes.
63116 ** If pMem->zMalloc already meets or exceeds the requested size, this
63117 ** routine is a no-op.
63118 **
63119 ** Any prior string or blob content in the pMem object may be discarded.
63120 ** The pMem->xDel destructor is called, if it exists.  Though MEM_Str
63121 ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
63122 ** values are preserved.
63123 **
63124 ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
63125 ** if unable to complete the resizing.
63126 */
63127 SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
63128   assert( szNew>0 );
63129   assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
63130   if( pMem->szMalloc<szNew ){
63131     return sqlite3VdbeMemGrow(pMem, szNew, 0);
63132   }
63133   assert( (pMem->flags & MEM_Dyn)==0 );
63134   pMem->z = pMem->zMalloc;
63135   pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
63136   return SQLITE_OK;
63137 }
63138
63139 /*
63140 ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
63141 ** MEM.zMalloc, where it can be safely written.
63142 **
63143 ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
63144 */
63145 SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
63146   int f;
63147   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63148   assert( (pMem->flags&MEM_RowSet)==0 );
63149   ExpandBlob(pMem);
63150   f = pMem->flags;
63151   if( (f&(MEM_Str|MEM_Blob)) && (pMem->szMalloc==0 || pMem->z!=pMem->zMalloc) ){
63152     if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
63153       return SQLITE_NOMEM;
63154     }
63155     pMem->z[pMem->n] = 0;
63156     pMem->z[pMem->n+1] = 0;
63157     pMem->flags |= MEM_Term;
63158 #ifdef SQLITE_DEBUG
63159     pMem->pScopyFrom = 0;
63160 #endif
63161   }
63162
63163   return SQLITE_OK;
63164 }
63165
63166 /*
63167 ** If the given Mem* has a zero-filled tail, turn it into an ordinary
63168 ** blob stored in dynamically allocated space.
63169 */
63170 #ifndef SQLITE_OMIT_INCRBLOB
63171 SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
63172   if( pMem->flags & MEM_Zero ){
63173     int nByte;
63174     assert( pMem->flags&MEM_Blob );
63175     assert( (pMem->flags&MEM_RowSet)==0 );
63176     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63177
63178     /* Set nByte to the number of bytes required to store the expanded blob. */
63179     nByte = pMem->n + pMem->u.nZero;
63180     if( nByte<=0 ){
63181       nByte = 1;
63182     }
63183     if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
63184       return SQLITE_NOMEM;
63185     }
63186
63187     memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
63188     pMem->n += pMem->u.nZero;
63189     pMem->flags &= ~(MEM_Zero|MEM_Term);
63190   }
63191   return SQLITE_OK;
63192 }
63193 #endif
63194
63195 /*
63196 ** It is already known that pMem contains an unterminated string.
63197 ** Add the zero terminator.
63198 */
63199 static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
63200   if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
63201     return SQLITE_NOMEM;
63202   }
63203   pMem->z[pMem->n] = 0;
63204   pMem->z[pMem->n+1] = 0;
63205   pMem->flags |= MEM_Term;
63206   return SQLITE_OK;
63207 }
63208
63209 /*
63210 ** Make sure the given Mem is \u0000 terminated.
63211 */
63212 SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
63213   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63214   testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
63215   testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
63216   if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
63217     return SQLITE_OK;   /* Nothing to do */
63218   }else{
63219     return vdbeMemAddTerminator(pMem);
63220   }
63221 }
63222
63223 /*
63224 ** Add MEM_Str to the set of representations for the given Mem.  Numbers
63225 ** are converted using sqlite3_snprintf().  Converting a BLOB to a string
63226 ** is a no-op.
63227 **
63228 ** Existing representations MEM_Int and MEM_Real are invalidated if
63229 ** bForce is true but are retained if bForce is false.
63230 **
63231 ** A MEM_Null value will never be passed to this function. This function is
63232 ** used for converting values to text for returning to the user (i.e. via
63233 ** sqlite3_value_text()), or for ensuring that values to be used as btree
63234 ** keys are strings. In the former case a NULL pointer is returned the
63235 ** user and the latter is an internal programming error.
63236 */
63237 SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
63238   int fg = pMem->flags;
63239   const int nByte = 32;
63240
63241   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63242   assert( !(fg&MEM_Zero) );
63243   assert( !(fg&(MEM_Str|MEM_Blob)) );
63244   assert( fg&(MEM_Int|MEM_Real) );
63245   assert( (pMem->flags&MEM_RowSet)==0 );
63246   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
63247
63248
63249   if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
63250     return SQLITE_NOMEM;
63251   }
63252
63253   /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
63254   ** string representation of the value. Then, if the required encoding
63255   ** is UTF-16le or UTF-16be do a translation.
63256   ** 
63257   ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
63258   */
63259   if( fg & MEM_Int ){
63260     sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
63261   }else{
63262     assert( fg & MEM_Real );
63263     sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
63264   }
63265   pMem->n = sqlite3Strlen30(pMem->z);
63266   pMem->enc = SQLITE_UTF8;
63267   pMem->flags |= MEM_Str|MEM_Term;
63268   if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
63269   sqlite3VdbeChangeEncoding(pMem, enc);
63270   return SQLITE_OK;
63271 }
63272
63273 /*
63274 ** Memory cell pMem contains the context of an aggregate function.
63275 ** This routine calls the finalize method for that function.  The
63276 ** result of the aggregate is stored back into pMem.
63277 **
63278 ** Return SQLITE_ERROR if the finalizer reports an error.  SQLITE_OK
63279 ** otherwise.
63280 */
63281 SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
63282   int rc = SQLITE_OK;
63283   if( ALWAYS(pFunc && pFunc->xFinalize) ){
63284     sqlite3_context ctx;
63285     Mem t;
63286     assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
63287     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63288     memset(&ctx, 0, sizeof(ctx));
63289     memset(&t, 0, sizeof(t));
63290     t.flags = MEM_Null;
63291     t.db = pMem->db;
63292     ctx.pOut = &t;
63293     ctx.pMem = pMem;
63294     ctx.pFunc = pFunc;
63295     pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
63296     assert( (pMem->flags & MEM_Dyn)==0 );
63297     if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
63298     memcpy(pMem, &t, sizeof(t));
63299     rc = ctx.isError;
63300   }
63301   return rc;
63302 }
63303
63304 /*
63305 ** If the memory cell contains a value that must be freed by
63306 ** invoking the external callback in Mem.xDel, then this routine
63307 ** will free that value.  It also sets Mem.flags to MEM_Null.
63308 **
63309 ** This is a helper routine for sqlite3VdbeMemSetNull() and
63310 ** for sqlite3VdbeMemRelease().  Use those other routines as the
63311 ** entry point for releasing Mem resources.
63312 */
63313 static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
63314   assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
63315   assert( VdbeMemDynamic(p) );
63316   if( p->flags&MEM_Agg ){
63317     sqlite3VdbeMemFinalize(p, p->u.pDef);
63318     assert( (p->flags & MEM_Agg)==0 );
63319     testcase( p->flags & MEM_Dyn );
63320   }
63321   if( p->flags&MEM_Dyn ){
63322     assert( (p->flags&MEM_RowSet)==0 );
63323     assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
63324     p->xDel((void *)p->z);
63325   }else if( p->flags&MEM_RowSet ){
63326     sqlite3RowSetClear(p->u.pRowSet);
63327   }else if( p->flags&MEM_Frame ){
63328     VdbeFrame *pFrame = p->u.pFrame;
63329     pFrame->pParent = pFrame->v->pDelFrame;
63330     pFrame->v->pDelFrame = pFrame;
63331   }
63332   p->flags = MEM_Null;
63333 }
63334
63335 /*
63336 ** Release memory held by the Mem p, both external memory cleared
63337 ** by p->xDel and memory in p->zMalloc.
63338 **
63339 ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
63340 ** the unusual case where there really is memory in p that needs
63341 ** to be freed.
63342 */
63343 static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
63344   if( VdbeMemDynamic(p) ){
63345     vdbeMemClearExternAndSetNull(p);
63346   }
63347   if( p->szMalloc ){
63348     sqlite3DbFree(p->db, p->zMalloc);
63349     p->szMalloc = 0;
63350   }
63351   p->z = 0;
63352 }
63353
63354 /*
63355 ** Release any memory resources held by the Mem.  Both the memory that is
63356 ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
63357 **
63358 ** Use this routine prior to clean up prior to abandoning a Mem, or to
63359 ** reset a Mem back to its minimum memory utilization.
63360 **
63361 ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
63362 ** prior to inserting new content into the Mem.
63363 */
63364 SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
63365   assert( sqlite3VdbeCheckMemInvariants(p) );
63366   if( VdbeMemDynamic(p) || p->szMalloc ){
63367     vdbeMemClear(p);
63368   }
63369 }
63370
63371 /*
63372 ** Convert a 64-bit IEEE double into a 64-bit signed integer.
63373 ** If the double is out of range of a 64-bit signed integer then
63374 ** return the closest available 64-bit signed integer.
63375 */
63376 static i64 doubleToInt64(double r){
63377 #ifdef SQLITE_OMIT_FLOATING_POINT
63378   /* When floating-point is omitted, double and int64 are the same thing */
63379   return r;
63380 #else
63381   /*
63382   ** Many compilers we encounter do not define constants for the
63383   ** minimum and maximum 64-bit integers, or they define them
63384   ** inconsistently.  And many do not understand the "LL" notation.
63385   ** So we define our own static constants here using nothing
63386   ** larger than a 32-bit integer constant.
63387   */
63388   static const i64 maxInt = LARGEST_INT64;
63389   static const i64 minInt = SMALLEST_INT64;
63390
63391   if( r<=(double)minInt ){
63392     return minInt;
63393   }else if( r>=(double)maxInt ){
63394     return maxInt;
63395   }else{
63396     return (i64)r;
63397   }
63398 #endif
63399 }
63400
63401 /*
63402 ** Return some kind of integer value which is the best we can do
63403 ** at representing the value that *pMem describes as an integer.
63404 ** If pMem is an integer, then the value is exact.  If pMem is
63405 ** a floating-point then the value returned is the integer part.
63406 ** If pMem is a string or blob, then we make an attempt to convert
63407 ** it into an integer and return that.  If pMem represents an
63408 ** an SQL-NULL value, return 0.
63409 **
63410 ** If pMem represents a string value, its encoding might be changed.
63411 */
63412 SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
63413   int flags;
63414   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63415   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
63416   flags = pMem->flags;
63417   if( flags & MEM_Int ){
63418     return pMem->u.i;
63419   }else if( flags & MEM_Real ){
63420     return doubleToInt64(pMem->u.r);
63421   }else if( flags & (MEM_Str|MEM_Blob) ){
63422     i64 value = 0;
63423     assert( pMem->z || pMem->n==0 );
63424     sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
63425     return value;
63426   }else{
63427     return 0;
63428   }
63429 }
63430
63431 /*
63432 ** Return the best representation of pMem that we can get into a
63433 ** double.  If pMem is already a double or an integer, return its
63434 ** value.  If it is a string or blob, try to convert it to a double.
63435 ** If it is a NULL, return 0.0.
63436 */
63437 SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
63438   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63439   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
63440   if( pMem->flags & MEM_Real ){
63441     return pMem->u.r;
63442   }else if( pMem->flags & MEM_Int ){
63443     return (double)pMem->u.i;
63444   }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
63445     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
63446     double val = (double)0;
63447     sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
63448     return val;
63449   }else{
63450     /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
63451     return (double)0;
63452   }
63453 }
63454
63455 /*
63456 ** The MEM structure is already a MEM_Real.  Try to also make it a
63457 ** MEM_Int if we can.
63458 */
63459 SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
63460   i64 ix;
63461   assert( pMem->flags & MEM_Real );
63462   assert( (pMem->flags & MEM_RowSet)==0 );
63463   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63464   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
63465
63466   ix = doubleToInt64(pMem->u.r);
63467
63468   /* Only mark the value as an integer if
63469   **
63470   **    (1) the round-trip conversion real->int->real is a no-op, and
63471   **    (2) The integer is neither the largest nor the smallest
63472   **        possible integer (ticket #3922)
63473   **
63474   ** The second and third terms in the following conditional enforces
63475   ** the second condition under the assumption that addition overflow causes
63476   ** values to wrap around.
63477   */
63478   if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
63479     pMem->u.i = ix;
63480     MemSetTypeFlag(pMem, MEM_Int);
63481   }
63482 }
63483
63484 /*
63485 ** Convert pMem to type integer.  Invalidate any prior representations.
63486 */
63487 SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
63488   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63489   assert( (pMem->flags & MEM_RowSet)==0 );
63490   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
63491
63492   pMem->u.i = sqlite3VdbeIntValue(pMem);
63493   MemSetTypeFlag(pMem, MEM_Int);
63494   return SQLITE_OK;
63495 }
63496
63497 /*
63498 ** Convert pMem so that it is of type MEM_Real.
63499 ** Invalidate any prior representations.
63500 */
63501 SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
63502   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63503   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
63504
63505   pMem->u.r = sqlite3VdbeRealValue(pMem);
63506   MemSetTypeFlag(pMem, MEM_Real);
63507   return SQLITE_OK;
63508 }
63509
63510 /*
63511 ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
63512 ** Invalidate any prior representations.
63513 **
63514 ** Every effort is made to force the conversion, even if the input
63515 ** is a string that does not look completely like a number.  Convert
63516 ** as much of the string as we can and ignore the rest.
63517 */
63518 SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
63519   if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
63520     assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
63521     assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63522     if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
63523       MemSetTypeFlag(pMem, MEM_Int);
63524     }else{
63525       pMem->u.r = sqlite3VdbeRealValue(pMem);
63526       MemSetTypeFlag(pMem, MEM_Real);
63527       sqlite3VdbeIntegerAffinity(pMem);
63528     }
63529   }
63530   assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
63531   pMem->flags &= ~(MEM_Str|MEM_Blob);
63532   return SQLITE_OK;
63533 }
63534
63535 /*
63536 ** Cast the datatype of the value in pMem according to the affinity
63537 ** "aff".  Casting is different from applying affinity in that a cast
63538 ** is forced.  In other words, the value is converted into the desired
63539 ** affinity even if that results in loss of data.  This routine is
63540 ** used (for example) to implement the SQL "cast()" operator.
63541 */
63542 SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
63543   if( pMem->flags & MEM_Null ) return;
63544   switch( aff ){
63545     case SQLITE_AFF_NONE: {   /* Really a cast to BLOB */
63546       if( (pMem->flags & MEM_Blob)==0 ){
63547         sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
63548         assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
63549         MemSetTypeFlag(pMem, MEM_Blob);
63550       }else{
63551         pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
63552       }
63553       break;
63554     }
63555     case SQLITE_AFF_NUMERIC: {
63556       sqlite3VdbeMemNumerify(pMem);
63557       break;
63558     }
63559     case SQLITE_AFF_INTEGER: {
63560       sqlite3VdbeMemIntegerify(pMem);
63561       break;
63562     }
63563     case SQLITE_AFF_REAL: {
63564       sqlite3VdbeMemRealify(pMem);
63565       break;
63566     }
63567     default: {
63568       assert( aff==SQLITE_AFF_TEXT );
63569       assert( MEM_Str==(MEM_Blob>>3) );
63570       pMem->flags |= (pMem->flags&MEM_Blob)>>3;
63571       sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
63572       assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
63573       pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
63574       break;
63575     }
63576   }
63577 }
63578
63579 /*
63580 ** Initialize bulk memory to be a consistent Mem object.
63581 **
63582 ** The minimum amount of initialization feasible is performed.
63583 */
63584 SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
63585   assert( (flags & ~MEM_TypeMask)==0 );
63586   pMem->flags = flags;
63587   pMem->db = db;
63588   pMem->szMalloc = 0;
63589 }
63590
63591
63592 /*
63593 ** Delete any previous value and set the value stored in *pMem to NULL.
63594 **
63595 ** This routine calls the Mem.xDel destructor to dispose of values that
63596 ** require the destructor.  But it preserves the Mem.zMalloc memory allocation.
63597 ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
63598 ** routine to invoke the destructor and deallocates Mem.zMalloc.
63599 **
63600 ** Use this routine to reset the Mem prior to insert a new value.
63601 **
63602 ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
63603 */
63604 SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
63605   if( VdbeMemDynamic(pMem) ){
63606     vdbeMemClearExternAndSetNull(pMem);
63607   }else{
63608     pMem->flags = MEM_Null;
63609   }
63610 }
63611 SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
63612   sqlite3VdbeMemSetNull((Mem*)p); 
63613 }
63614
63615 /*
63616 ** Delete any previous value and set the value to be a BLOB of length
63617 ** n containing all zeros.
63618 */
63619 SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
63620   sqlite3VdbeMemRelease(pMem);
63621   pMem->flags = MEM_Blob|MEM_Zero;
63622   pMem->n = 0;
63623   if( n<0 ) n = 0;
63624   pMem->u.nZero = n;
63625   pMem->enc = SQLITE_UTF8;
63626   pMem->z = 0;
63627 }
63628
63629 /*
63630 ** The pMem is known to contain content that needs to be destroyed prior
63631 ** to a value change.  So invoke the destructor, then set the value to
63632 ** a 64-bit integer.
63633 */
63634 static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
63635   sqlite3VdbeMemSetNull(pMem);
63636   pMem->u.i = val;
63637   pMem->flags = MEM_Int;
63638 }
63639
63640 /*
63641 ** Delete any previous value and set the value stored in *pMem to val,
63642 ** manifest type INTEGER.
63643 */
63644 SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
63645   if( VdbeMemDynamic(pMem) ){
63646     vdbeReleaseAndSetInt64(pMem, val);
63647   }else{
63648     pMem->u.i = val;
63649     pMem->flags = MEM_Int;
63650   }
63651 }
63652
63653 #ifndef SQLITE_OMIT_FLOATING_POINT
63654 /*
63655 ** Delete any previous value and set the value stored in *pMem to val,
63656 ** manifest type REAL.
63657 */
63658 SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
63659   sqlite3VdbeMemSetNull(pMem);
63660   if( !sqlite3IsNaN(val) ){
63661     pMem->u.r = val;
63662     pMem->flags = MEM_Real;
63663   }
63664 }
63665 #endif
63666
63667 /*
63668 ** Delete any previous value and set the value of pMem to be an
63669 ** empty boolean index.
63670 */
63671 SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
63672   sqlite3 *db = pMem->db;
63673   assert( db!=0 );
63674   assert( (pMem->flags & MEM_RowSet)==0 );
63675   sqlite3VdbeMemRelease(pMem);
63676   pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
63677   if( db->mallocFailed ){
63678     pMem->flags = MEM_Null;
63679     pMem->szMalloc = 0;
63680   }else{
63681     assert( pMem->zMalloc );
63682     pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
63683     pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
63684     assert( pMem->u.pRowSet!=0 );
63685     pMem->flags = MEM_RowSet;
63686   }
63687 }
63688
63689 /*
63690 ** Return true if the Mem object contains a TEXT or BLOB that is
63691 ** too large - whose size exceeds SQLITE_MAX_LENGTH.
63692 */
63693 SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
63694   assert( p->db!=0 );
63695   if( p->flags & (MEM_Str|MEM_Blob) ){
63696     int n = p->n;
63697     if( p->flags & MEM_Zero ){
63698       n += p->u.nZero;
63699     }
63700     return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
63701   }
63702   return 0; 
63703 }
63704
63705 #ifdef SQLITE_DEBUG
63706 /*
63707 ** This routine prepares a memory cell for modification by breaking
63708 ** its link to a shallow copy and by marking any current shallow
63709 ** copies of this cell as invalid.
63710 **
63711 ** This is used for testing and debugging only - to make sure shallow
63712 ** copies are not misused.
63713 */
63714 SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
63715   int i;
63716   Mem *pX;
63717   for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
63718     if( pX->pScopyFrom==pMem ){
63719       pX->flags |= MEM_Undefined;
63720       pX->pScopyFrom = 0;
63721     }
63722   }
63723   pMem->pScopyFrom = 0;
63724 }
63725 #endif /* SQLITE_DEBUG */
63726
63727 /*
63728 ** Size of struct Mem not including the Mem.zMalloc member.
63729 */
63730 #define MEMCELLSIZE offsetof(Mem,zMalloc)
63731
63732 /*
63733 ** Make an shallow copy of pFrom into pTo.  Prior contents of
63734 ** pTo are freed.  The pFrom->z field is not duplicated.  If
63735 ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
63736 ** and flags gets srcType (either MEM_Ephem or MEM_Static).
63737 */
63738 SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
63739   assert( (pFrom->flags & MEM_RowSet)==0 );
63740   assert( pTo->db==pFrom->db );
63741   if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
63742   memcpy(pTo, pFrom, MEMCELLSIZE);
63743   if( (pFrom->flags&MEM_Static)==0 ){
63744     pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
63745     assert( srcType==MEM_Ephem || srcType==MEM_Static );
63746     pTo->flags |= srcType;
63747   }
63748 }
63749
63750 /*
63751 ** Make a full copy of pFrom into pTo.  Prior contents of pTo are
63752 ** freed before the copy is made.
63753 */
63754 SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
63755   int rc = SQLITE_OK;
63756
63757   assert( pTo->db==pFrom->db );
63758   assert( (pFrom->flags & MEM_RowSet)==0 );
63759   if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
63760   memcpy(pTo, pFrom, MEMCELLSIZE);
63761   pTo->flags &= ~MEM_Dyn;
63762   if( pTo->flags&(MEM_Str|MEM_Blob) ){
63763     if( 0==(pFrom->flags&MEM_Static) ){
63764       pTo->flags |= MEM_Ephem;
63765       rc = sqlite3VdbeMemMakeWriteable(pTo);
63766     }
63767   }
63768
63769   return rc;
63770 }
63771
63772 /*
63773 ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
63774 ** freed. If pFrom contains ephemeral data, a copy is made.
63775 **
63776 ** pFrom contains an SQL NULL when this routine returns.
63777 */
63778 SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
63779   assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
63780   assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
63781   assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
63782
63783   sqlite3VdbeMemRelease(pTo);
63784   memcpy(pTo, pFrom, sizeof(Mem));
63785   pFrom->flags = MEM_Null;
63786   pFrom->szMalloc = 0;
63787 }
63788
63789 /*
63790 ** Change the value of a Mem to be a string or a BLOB.
63791 **
63792 ** The memory management strategy depends on the value of the xDel
63793 ** parameter. If the value passed is SQLITE_TRANSIENT, then the 
63794 ** string is copied into a (possibly existing) buffer managed by the 
63795 ** Mem structure. Otherwise, any existing buffer is freed and the
63796 ** pointer copied.
63797 **
63798 ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
63799 ** size limit) then no memory allocation occurs.  If the string can be
63800 ** stored without allocating memory, then it is.  If a memory allocation
63801 ** is required to store the string, then value of pMem is unchanged.  In
63802 ** either case, SQLITE_TOOBIG is returned.
63803 */
63804 SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
63805   Mem *pMem,          /* Memory cell to set to string value */
63806   const char *z,      /* String pointer */
63807   int n,              /* Bytes in string, or negative */
63808   u8 enc,             /* Encoding of z.  0 for BLOBs */
63809   void (*xDel)(void*) /* Destructor function */
63810 ){
63811   int nByte = n;      /* New value for pMem->n */
63812   int iLimit;         /* Maximum allowed string or blob size */
63813   u16 flags = 0;      /* New value for pMem->flags */
63814
63815   assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
63816   assert( (pMem->flags & MEM_RowSet)==0 );
63817
63818   /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
63819   if( !z ){
63820     sqlite3VdbeMemSetNull(pMem);
63821     return SQLITE_OK;
63822   }
63823
63824   if( pMem->db ){
63825     iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
63826   }else{
63827     iLimit = SQLITE_MAX_LENGTH;
63828   }
63829   flags = (enc==0?MEM_Blob:MEM_Str);
63830   if( nByte<0 ){
63831     assert( enc!=0 );
63832     if( enc==SQLITE_UTF8 ){
63833       nByte = sqlite3Strlen30(z);
63834       if( nByte>iLimit ) nByte = iLimit+1;
63835     }else{
63836       for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
63837     }
63838     flags |= MEM_Term;
63839   }
63840
63841   /* The following block sets the new values of Mem.z and Mem.xDel. It
63842   ** also sets a flag in local variable "flags" to indicate the memory
63843   ** management (one of MEM_Dyn or MEM_Static).
63844   */
63845   if( xDel==SQLITE_TRANSIENT ){
63846     int nAlloc = nByte;
63847     if( flags&MEM_Term ){
63848       nAlloc += (enc==SQLITE_UTF8?1:2);
63849     }
63850     if( nByte>iLimit ){
63851       return SQLITE_TOOBIG;
63852     }
63853     testcase( nAlloc==0 );
63854     testcase( nAlloc==31 );
63855     testcase( nAlloc==32 );
63856     if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
63857       return SQLITE_NOMEM;
63858     }
63859     memcpy(pMem->z, z, nAlloc);
63860   }else if( xDel==SQLITE_DYNAMIC ){
63861     sqlite3VdbeMemRelease(pMem);
63862     pMem->zMalloc = pMem->z = (char *)z;
63863     pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
63864   }else{
63865     sqlite3VdbeMemRelease(pMem);
63866     pMem->z = (char *)z;
63867     pMem->xDel = xDel;
63868     flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
63869   }
63870
63871   pMem->n = nByte;
63872   pMem->flags = flags;
63873   pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
63874
63875 #ifndef SQLITE_OMIT_UTF16
63876   if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
63877     return SQLITE_NOMEM;
63878   }
63879 #endif
63880
63881   if( nByte>iLimit ){
63882     return SQLITE_TOOBIG;
63883   }
63884
63885   return SQLITE_OK;
63886 }
63887
63888 /*
63889 ** Move data out of a btree key or data field and into a Mem structure.
63890 ** The data or key is taken from the entry that pCur is currently pointing
63891 ** to.  offset and amt determine what portion of the data or key to retrieve.
63892 ** key is true to get the key or false to get data.  The result is written
63893 ** into the pMem element.
63894 **
63895 ** The pMem object must have been initialized.  This routine will use
63896 ** pMem->zMalloc to hold the content from the btree, if possible.  New
63897 ** pMem->zMalloc space will be allocated if necessary.  The calling routine
63898 ** is responsible for making sure that the pMem object is eventually
63899 ** destroyed.
63900 **
63901 ** If this routine fails for any reason (malloc returns NULL or unable
63902 ** to read from the disk) then the pMem is left in an inconsistent state.
63903 */
63904 SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
63905   BtCursor *pCur,   /* Cursor pointing at record to retrieve. */
63906   u32 offset,       /* Offset from the start of data to return bytes from. */
63907   u32 amt,          /* Number of bytes to return. */
63908   int key,          /* If true, retrieve from the btree key, not data. */
63909   Mem *pMem         /* OUT: Return data in this Mem structure. */
63910 ){
63911   char *zData;        /* Data from the btree layer */
63912   u32 available = 0;  /* Number of bytes available on the local btree page */
63913   int rc = SQLITE_OK; /* Return code */
63914
63915   assert( sqlite3BtreeCursorIsValid(pCur) );
63916   assert( !VdbeMemDynamic(pMem) );
63917
63918   /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert() 
63919   ** that both the BtShared and database handle mutexes are held. */
63920   assert( (pMem->flags & MEM_RowSet)==0 );
63921   if( key ){
63922     zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
63923   }else{
63924     zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
63925   }
63926   assert( zData!=0 );
63927
63928   if( offset+amt<=available ){
63929     pMem->z = &zData[offset];
63930     pMem->flags = MEM_Blob|MEM_Ephem;
63931     pMem->n = (int)amt;
63932   }else{
63933     pMem->flags = MEM_Null;
63934     if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){
63935       if( key ){
63936         rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
63937       }else{
63938         rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
63939       }
63940       if( rc==SQLITE_OK ){
63941         pMem->z[amt] = 0;
63942         pMem->z[amt+1] = 0;
63943         pMem->flags = MEM_Blob|MEM_Term;
63944         pMem->n = (int)amt;
63945       }else{
63946         sqlite3VdbeMemRelease(pMem);
63947       }
63948     }
63949   }
63950
63951   return rc;
63952 }
63953
63954 /*
63955 ** The pVal argument is known to be a value other than NULL.
63956 ** Convert it into a string with encoding enc and return a pointer
63957 ** to a zero-terminated version of that string.
63958 */
63959 static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
63960   assert( pVal!=0 );
63961   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
63962   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
63963   assert( (pVal->flags & MEM_RowSet)==0 );
63964   assert( (pVal->flags & (MEM_Null))==0 );
63965   if( pVal->flags & (MEM_Blob|MEM_Str) ){
63966     pVal->flags |= MEM_Str;
63967     if( pVal->flags & MEM_Zero ){
63968       sqlite3VdbeMemExpandBlob(pVal);
63969     }
63970     if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
63971       sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
63972     }
63973     if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
63974       assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
63975       if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
63976         return 0;
63977       }
63978     }
63979     sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
63980   }else{
63981     sqlite3VdbeMemStringify(pVal, enc, 0);
63982     assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
63983   }
63984   assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
63985               || pVal->db->mallocFailed );
63986   if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
63987     return pVal->z;
63988   }else{
63989     return 0;
63990   }
63991 }
63992
63993 /* This function is only available internally, it is not part of the
63994 ** external API. It works in a similar way to sqlite3_value_text(),
63995 ** except the data returned is in the encoding specified by the second
63996 ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
63997 ** SQLITE_UTF8.
63998 **
63999 ** (2006-02-16:)  The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
64000 ** If that is the case, then the result must be aligned on an even byte
64001 ** boundary.
64002 */
64003 SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
64004   if( !pVal ) return 0;
64005   assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
64006   assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
64007   assert( (pVal->flags & MEM_RowSet)==0 );
64008   if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
64009     return pVal->z;
64010   }
64011   if( pVal->flags&MEM_Null ){
64012     return 0;
64013   }
64014   return valueToText(pVal, enc);
64015 }
64016
64017 /*
64018 ** Create a new sqlite3_value object.
64019 */
64020 SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
64021   Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
64022   if( p ){
64023     p->flags = MEM_Null;
64024     p->db = db;
64025   }
64026   return p;
64027 }
64028
64029 /*
64030 ** Context object passed by sqlite3Stat4ProbeSetValue() through to 
64031 ** valueNew(). See comments above valueNew() for details.
64032 */
64033 struct ValueNewStat4Ctx {
64034   Parse *pParse;
64035   Index *pIdx;
64036   UnpackedRecord **ppRec;
64037   int iVal;
64038 };
64039
64040 /*
64041 ** Allocate and return a pointer to a new sqlite3_value object. If
64042 ** the second argument to this function is NULL, the object is allocated
64043 ** by calling sqlite3ValueNew().
64044 **
64045 ** Otherwise, if the second argument is non-zero, then this function is 
64046 ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
64047 ** already been allocated, allocate the UnpackedRecord structure that 
64048 ** that function will return to its caller here. Then return a pointer to
64049 ** an sqlite3_value within the UnpackedRecord.a[] array.
64050 */
64051 static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
64052 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
64053   if( p ){
64054     UnpackedRecord *pRec = p->ppRec[0];
64055
64056     if( pRec==0 ){
64057       Index *pIdx = p->pIdx;      /* Index being probed */
64058       int nByte;                  /* Bytes of space to allocate */
64059       int i;                      /* Counter variable */
64060       int nCol = pIdx->nColumn;   /* Number of index columns including rowid */
64061   
64062       nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
64063       pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
64064       if( pRec ){
64065         pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
64066         if( pRec->pKeyInfo ){
64067           assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
64068           assert( pRec->pKeyInfo->enc==ENC(db) );
64069           pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
64070           for(i=0; i<nCol; i++){
64071             pRec->aMem[i].flags = MEM_Null;
64072             pRec->aMem[i].db = db;
64073           }
64074         }else{
64075           sqlite3DbFree(db, pRec);
64076           pRec = 0;
64077         }
64078       }
64079       if( pRec==0 ) return 0;
64080       p->ppRec[0] = pRec;
64081     }
64082   
64083     pRec->nField = p->iVal+1;
64084     return &pRec->aMem[p->iVal];
64085   }
64086 #else
64087   UNUSED_PARAMETER(p);
64088 #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
64089   return sqlite3ValueNew(db);
64090 }
64091
64092 /*
64093 ** The expression object indicated by the second argument is guaranteed
64094 ** to be a scalar SQL function. If
64095 **
64096 **   * all function arguments are SQL literals,
64097 **   * the SQLITE_FUNC_CONSTANT function flag is set, and
64098 **   * the SQLITE_FUNC_NEEDCOLL function flag is not set,
64099 **
64100 ** then this routine attempts to invoke the SQL function. Assuming no
64101 ** error occurs, output parameter (*ppVal) is set to point to a value 
64102 ** object containing the result before returning SQLITE_OK.
64103 **
64104 ** Affinity aff is applied to the result of the function before returning.
64105 ** If the result is a text value, the sqlite3_value object uses encoding 
64106 ** enc.
64107 **
64108 ** If the conditions above are not met, this function returns SQLITE_OK
64109 ** and sets (*ppVal) to NULL. Or, if an error occurs, (*ppVal) is set to
64110 ** NULL and an SQLite error code returned.
64111 */
64112 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
64113 static int valueFromFunction(
64114   sqlite3 *db,                    /* The database connection */
64115   Expr *p,                        /* The expression to evaluate */
64116   u8 enc,                         /* Encoding to use */
64117   u8 aff,                         /* Affinity to use */
64118   sqlite3_value **ppVal,          /* Write the new value here */
64119   struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
64120 ){
64121   sqlite3_context ctx;            /* Context object for function invocation */
64122   sqlite3_value **apVal = 0;      /* Function arguments */
64123   int nVal = 0;                   /* Size of apVal[] array */
64124   FuncDef *pFunc = 0;             /* Function definition */
64125   sqlite3_value *pVal = 0;        /* New value */
64126   int rc = SQLITE_OK;             /* Return code */
64127   int nName;                      /* Size of function name in bytes */
64128   ExprList *pList = 0;            /* Function arguments */
64129   int i;                          /* Iterator variable */
64130
64131   assert( pCtx!=0 );
64132   assert( (p->flags & EP_TokenOnly)==0 );
64133   pList = p->x.pList;
64134   if( pList ) nVal = pList->nExpr;
64135   nName = sqlite3Strlen30(p->u.zToken);
64136   pFunc = sqlite3FindFunction(db, p->u.zToken, nName, nVal, enc, 0);
64137   assert( pFunc );
64138   if( (pFunc->funcFlags & SQLITE_FUNC_CONSTANT)==0 
64139    || (pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
64140   ){
64141     return SQLITE_OK;
64142   }
64143
64144   if( pList ){
64145     apVal = (sqlite3_value**)sqlite3DbMallocZero(db, sizeof(apVal[0]) * nVal);
64146     if( apVal==0 ){
64147       rc = SQLITE_NOMEM;
64148       goto value_from_function_out;
64149     }
64150     for(i=0; i<nVal; i++){
64151       rc = sqlite3ValueFromExpr(db, pList->a[i].pExpr, enc, aff, &apVal[i]);
64152       if( apVal[i]==0 || rc!=SQLITE_OK ) goto value_from_function_out;
64153     }
64154   }
64155
64156   pVal = valueNew(db, pCtx);
64157   if( pVal==0 ){
64158     rc = SQLITE_NOMEM;
64159     goto value_from_function_out;
64160   }
64161
64162   assert( pCtx->pParse->rc==SQLITE_OK );
64163   memset(&ctx, 0, sizeof(ctx));
64164   ctx.pOut = pVal;
64165   ctx.pFunc = pFunc;
64166   pFunc->xFunc(&ctx, nVal, apVal);
64167   if( ctx.isError ){
64168     rc = ctx.isError;
64169     sqlite3ErrorMsg(pCtx->pParse, "%s", sqlite3_value_text(pVal));
64170   }else{
64171     sqlite3ValueApplyAffinity(pVal, aff, SQLITE_UTF8);
64172     assert( rc==SQLITE_OK );
64173     rc = sqlite3VdbeChangeEncoding(pVal, enc);
64174     if( rc==SQLITE_OK && sqlite3VdbeMemTooBig(pVal) ){
64175       rc = SQLITE_TOOBIG;
64176       pCtx->pParse->nErr++;
64177     }
64178   }
64179   pCtx->pParse->rc = rc;
64180
64181  value_from_function_out:
64182   if( rc!=SQLITE_OK ){
64183     pVal = 0;
64184   }
64185   if( apVal ){
64186     for(i=0; i<nVal; i++){
64187       sqlite3ValueFree(apVal[i]);
64188     }
64189     sqlite3DbFree(db, apVal);
64190   }
64191
64192   *ppVal = pVal;
64193   return rc;
64194 }
64195 #else
64196 # define valueFromFunction(a,b,c,d,e,f) SQLITE_OK
64197 #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
64198
64199 /*
64200 ** Extract a value from the supplied expression in the manner described
64201 ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
64202 ** using valueNew().
64203 **
64204 ** If pCtx is NULL and an error occurs after the sqlite3_value object
64205 ** has been allocated, it is freed before returning. Or, if pCtx is not
64206 ** NULL, it is assumed that the caller will free any allocated object
64207 ** in all cases.
64208 */
64209 static int valueFromExpr(
64210   sqlite3 *db,                    /* The database connection */
64211   Expr *pExpr,                    /* The expression to evaluate */
64212   u8 enc,                         /* Encoding to use */
64213   u8 affinity,                    /* Affinity to use */
64214   sqlite3_value **ppVal,          /* Write the new value here */
64215   struct ValueNewStat4Ctx *pCtx   /* Second argument for valueNew() */
64216 ){
64217   int op;
64218   char *zVal = 0;
64219   sqlite3_value *pVal = 0;
64220   int negInt = 1;
64221   const char *zNeg = "";
64222   int rc = SQLITE_OK;
64223
64224   if( !pExpr ){
64225     *ppVal = 0;
64226     return SQLITE_OK;
64227   }
64228   while( (op = pExpr->op)==TK_UPLUS ) pExpr = pExpr->pLeft;
64229   if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
64230
64231   /* Compressed expressions only appear when parsing the DEFAULT clause
64232   ** on a table column definition, and hence only when pCtx==0.  This
64233   ** check ensures that an EP_TokenOnly expression is never passed down
64234   ** into valueFromFunction(). */
64235   assert( (pExpr->flags & EP_TokenOnly)==0 || pCtx==0 );
64236
64237   if( op==TK_CAST ){
64238     u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
64239     rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
64240     testcase( rc!=SQLITE_OK );
64241     if( *ppVal ){
64242       sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
64243       sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
64244     }
64245     return rc;
64246   }
64247
64248   /* Handle negative integers in a single step.  This is needed in the
64249   ** case when the value is -9223372036854775808.
64250   */
64251   if( op==TK_UMINUS
64252    && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
64253     pExpr = pExpr->pLeft;
64254     op = pExpr->op;
64255     negInt = -1;
64256     zNeg = "-";
64257   }
64258
64259   if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
64260     pVal = valueNew(db, pCtx);
64261     if( pVal==0 ) goto no_mem;
64262     if( ExprHasProperty(pExpr, EP_IntValue) ){
64263       sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
64264     }else{
64265       zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
64266       if( zVal==0 ) goto no_mem;
64267       sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
64268     }
64269     if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
64270       sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
64271     }else{
64272       sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
64273     }
64274     if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
64275     if( enc!=SQLITE_UTF8 ){
64276       rc = sqlite3VdbeChangeEncoding(pVal, enc);
64277     }
64278   }else if( op==TK_UMINUS ) {
64279     /* This branch happens for multiple negative signs.  Ex: -(-5) */
64280     if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal) 
64281      && pVal!=0
64282     ){
64283       sqlite3VdbeMemNumerify(pVal);
64284       if( pVal->flags & MEM_Real ){
64285         pVal->u.r = -pVal->u.r;
64286       }else if( pVal->u.i==SMALLEST_INT64 ){
64287         pVal->u.r = -(double)SMALLEST_INT64;
64288         MemSetTypeFlag(pVal, MEM_Real);
64289       }else{
64290         pVal->u.i = -pVal->u.i;
64291       }
64292       sqlite3ValueApplyAffinity(pVal, affinity, enc);
64293     }
64294   }else if( op==TK_NULL ){
64295     pVal = valueNew(db, pCtx);
64296     if( pVal==0 ) goto no_mem;
64297   }
64298 #ifndef SQLITE_OMIT_BLOB_LITERAL
64299   else if( op==TK_BLOB ){
64300     int nVal;
64301     assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
64302     assert( pExpr->u.zToken[1]=='\'' );
64303     pVal = valueNew(db, pCtx);
64304     if( !pVal ) goto no_mem;
64305     zVal = &pExpr->u.zToken[2];
64306     nVal = sqlite3Strlen30(zVal)-1;
64307     assert( zVal[nVal]=='\'' );
64308     sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
64309                          0, SQLITE_DYNAMIC);
64310   }
64311 #endif
64312
64313 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
64314   else if( op==TK_FUNCTION && pCtx!=0 ){
64315     rc = valueFromFunction(db, pExpr, enc, affinity, &pVal, pCtx);
64316   }
64317 #endif
64318
64319   *ppVal = pVal;
64320   return rc;
64321
64322 no_mem:
64323   db->mallocFailed = 1;
64324   sqlite3DbFree(db, zVal);
64325   assert( *ppVal==0 );
64326 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
64327   if( pCtx==0 ) sqlite3ValueFree(pVal);
64328 #else
64329   assert( pCtx==0 ); sqlite3ValueFree(pVal);
64330 #endif
64331   return SQLITE_NOMEM;
64332 }
64333
64334 /*
64335 ** Create a new sqlite3_value object, containing the value of pExpr.
64336 **
64337 ** This only works for very simple expressions that consist of one constant
64338 ** token (i.e. "5", "5.1", "'a string'"). If the expression can
64339 ** be converted directly into a value, then the value is allocated and
64340 ** a pointer written to *ppVal. The caller is responsible for deallocating
64341 ** the value by passing it to sqlite3ValueFree() later on. If the expression
64342 ** cannot be converted to a value, then *ppVal is set to NULL.
64343 */
64344 SQLITE_PRIVATE int sqlite3ValueFromExpr(
64345   sqlite3 *db,              /* The database connection */
64346   Expr *pExpr,              /* The expression to evaluate */
64347   u8 enc,                   /* Encoding to use */
64348   u8 affinity,              /* Affinity to use */
64349   sqlite3_value **ppVal     /* Write the new value here */
64350 ){
64351   return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
64352 }
64353
64354 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
64355 /*
64356 ** The implementation of the sqlite_record() function. This function accepts
64357 ** a single argument of any type. The return value is a formatted database 
64358 ** record (a blob) containing the argument value.
64359 **
64360 ** This is used to convert the value stored in the 'sample' column of the
64361 ** sqlite_stat3 table to the record format SQLite uses internally.
64362 */
64363 static void recordFunc(
64364   sqlite3_context *context,
64365   int argc,
64366   sqlite3_value **argv
64367 ){
64368   const int file_format = 1;
64369   int iSerial;                    /* Serial type */
64370   int nSerial;                    /* Bytes of space for iSerial as varint */
64371   int nVal;                       /* Bytes of space required for argv[0] */
64372   int nRet;
64373   sqlite3 *db;
64374   u8 *aRet;
64375
64376   UNUSED_PARAMETER( argc );
64377   iSerial = sqlite3VdbeSerialType(argv[0], file_format);
64378   nSerial = sqlite3VarintLen(iSerial);
64379   nVal = sqlite3VdbeSerialTypeLen(iSerial);
64380   db = sqlite3_context_db_handle(context);
64381
64382   nRet = 1 + nSerial + nVal;
64383   aRet = sqlite3DbMallocRaw(db, nRet);
64384   if( aRet==0 ){
64385     sqlite3_result_error_nomem(context);
64386   }else{
64387     aRet[0] = nSerial+1;
64388     putVarint32(&aRet[1], iSerial);
64389     sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
64390     sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
64391     sqlite3DbFree(db, aRet);
64392   }
64393 }
64394
64395 /*
64396 ** Register built-in functions used to help read ANALYZE data.
64397 */
64398 SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
64399   static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
64400     FUNCTION(sqlite_record,   1, 0, 0, recordFunc),
64401   };
64402   int i;
64403   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
64404   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
64405   for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
64406     sqlite3FuncDefInsert(pHash, &aFunc[i]);
64407   }
64408 }
64409
64410 /*
64411 ** Attempt to extract a value from pExpr and use it to construct *ppVal.
64412 **
64413 ** If pAlloc is not NULL, then an UnpackedRecord object is created for
64414 ** pAlloc if one does not exist and the new value is added to the
64415 ** UnpackedRecord object.
64416 **
64417 ** A value is extracted in the following cases:
64418 **
64419 **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
64420 **
64421 **  * The expression is a bound variable, and this is a reprepare, or
64422 **
64423 **  * The expression is a literal value.
64424 **
64425 ** On success, *ppVal is made to point to the extracted value.  The caller
64426 ** is responsible for ensuring that the value is eventually freed.
64427 */
64428 static int stat4ValueFromExpr(
64429   Parse *pParse,                  /* Parse context */
64430   Expr *pExpr,                    /* The expression to extract a value from */
64431   u8 affinity,                    /* Affinity to use */
64432   struct ValueNewStat4Ctx *pAlloc,/* How to allocate space.  Or NULL */
64433   sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
64434 ){
64435   int rc = SQLITE_OK;
64436   sqlite3_value *pVal = 0;
64437   sqlite3 *db = pParse->db;
64438
64439   /* Skip over any TK_COLLATE nodes */
64440   pExpr = sqlite3ExprSkipCollate(pExpr);
64441
64442   if( !pExpr ){
64443     pVal = valueNew(db, pAlloc);
64444     if( pVal ){
64445       sqlite3VdbeMemSetNull((Mem*)pVal);
64446     }
64447   }else if( pExpr->op==TK_VARIABLE
64448         || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
64449   ){
64450     Vdbe *v;
64451     int iBindVar = pExpr->iColumn;
64452     sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
64453     if( (v = pParse->pReprepare)!=0 ){
64454       pVal = valueNew(db, pAlloc);
64455       if( pVal ){
64456         rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
64457         if( rc==SQLITE_OK ){
64458           sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
64459         }
64460         pVal->db = pParse->db;
64461       }
64462     }
64463   }else{
64464     rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
64465   }
64466
64467   assert( pVal==0 || pVal->db==db );
64468   *ppVal = pVal;
64469   return rc;
64470 }
64471
64472 /*
64473 ** This function is used to allocate and populate UnpackedRecord 
64474 ** structures intended to be compared against sample index keys stored 
64475 ** in the sqlite_stat4 table.
64476 **
64477 ** A single call to this function attempts to populates field iVal (leftmost 
64478 ** is 0 etc.) of the unpacked record with a value extracted from expression
64479 ** pExpr. Extraction of values is possible if:
64480 **
64481 **  * (pExpr==0). In this case the value is assumed to be an SQL NULL,
64482 **
64483 **  * The expression is a bound variable, and this is a reprepare, or
64484 **
64485 **  * The sqlite3ValueFromExpr() function is able to extract a value 
64486 **    from the expression (i.e. the expression is a literal value).
64487 **
64488 ** If a value can be extracted, the affinity passed as the 5th argument
64489 ** is applied to it before it is copied into the UnpackedRecord. Output
64490 ** parameter *pbOk is set to true if a value is extracted, or false 
64491 ** otherwise.
64492 **
64493 ** When this function is called, *ppRec must either point to an object
64494 ** allocated by an earlier call to this function, or must be NULL. If it
64495 ** is NULL and a value can be successfully extracted, a new UnpackedRecord
64496 ** is allocated (and *ppRec set to point to it) before returning.
64497 **
64498 ** Unless an error is encountered, SQLITE_OK is returned. It is not an
64499 ** error if a value cannot be extracted from pExpr. If an error does
64500 ** occur, an SQLite error code is returned.
64501 */
64502 SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
64503   Parse *pParse,                  /* Parse context */
64504   Index *pIdx,                    /* Index being probed */
64505   UnpackedRecord **ppRec,         /* IN/OUT: Probe record */
64506   Expr *pExpr,                    /* The expression to extract a value from */
64507   u8 affinity,                    /* Affinity to use */
64508   int iVal,                       /* Array element to populate */
64509   int *pbOk                       /* OUT: True if value was extracted */
64510 ){
64511   int rc;
64512   sqlite3_value *pVal = 0;
64513   struct ValueNewStat4Ctx alloc;
64514
64515   alloc.pParse = pParse;
64516   alloc.pIdx = pIdx;
64517   alloc.ppRec = ppRec;
64518   alloc.iVal = iVal;
64519
64520   rc = stat4ValueFromExpr(pParse, pExpr, affinity, &alloc, &pVal);
64521   assert( pVal==0 || pVal->db==pParse->db );
64522   *pbOk = (pVal!=0);
64523   return rc;
64524 }
64525
64526 /*
64527 ** Attempt to extract a value from expression pExpr using the methods
64528 ** as described for sqlite3Stat4ProbeSetValue() above. 
64529 **
64530 ** If successful, set *ppVal to point to a new value object and return 
64531 ** SQLITE_OK. If no value can be extracted, but no other error occurs
64532 ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
64533 ** does occur, return an SQLite error code. The final value of *ppVal
64534 ** is undefined in this case.
64535 */
64536 SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
64537   Parse *pParse,                  /* Parse context */
64538   Expr *pExpr,                    /* The expression to extract a value from */
64539   u8 affinity,                    /* Affinity to use */
64540   sqlite3_value **ppVal           /* OUT: New value object (or NULL) */
64541 ){
64542   return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
64543 }
64544
64545 /*
64546 ** Extract the iCol-th column from the nRec-byte record in pRec.  Write
64547 ** the column value into *ppVal.  If *ppVal is initially NULL then a new
64548 ** sqlite3_value object is allocated.
64549 **
64550 ** If *ppVal is initially NULL then the caller is responsible for 
64551 ** ensuring that the value written into *ppVal is eventually freed.
64552 */
64553 SQLITE_PRIVATE int sqlite3Stat4Column(
64554   sqlite3 *db,                    /* Database handle */
64555   const void *pRec,               /* Pointer to buffer containing record */
64556   int nRec,                       /* Size of buffer pRec in bytes */
64557   int iCol,                       /* Column to extract */
64558   sqlite3_value **ppVal           /* OUT: Extracted value */
64559 ){
64560   u32 t;                          /* a column type code */
64561   int nHdr;                       /* Size of the header in the record */
64562   int iHdr;                       /* Next unread header byte */
64563   int iField;                     /* Next unread data byte */
64564   int szField;                    /* Size of the current data field */
64565   int i;                          /* Column index */
64566   u8 *a = (u8*)pRec;              /* Typecast byte array */
64567   Mem *pMem = *ppVal;             /* Write result into this Mem object */
64568
64569   assert( iCol>0 );
64570   iHdr = getVarint32(a, nHdr);
64571   if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
64572   iField = nHdr;
64573   for(i=0; i<=iCol; i++){
64574     iHdr += getVarint32(&a[iHdr], t);
64575     testcase( iHdr==nHdr );
64576     testcase( iHdr==nHdr+1 );
64577     if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
64578     szField = sqlite3VdbeSerialTypeLen(t);
64579     iField += szField;
64580   }
64581   testcase( iField==nRec );
64582   testcase( iField==nRec+1 );
64583   if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
64584   if( pMem==0 ){
64585     pMem = *ppVal = sqlite3ValueNew(db);
64586     if( pMem==0 ) return SQLITE_NOMEM;
64587   }
64588   sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
64589   pMem->enc = ENC(db);
64590   return SQLITE_OK;
64591 }
64592
64593 /*
64594 ** Unless it is NULL, the argument must be an UnpackedRecord object returned
64595 ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
64596 ** the object.
64597 */
64598 SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
64599   if( pRec ){
64600     int i;
64601     int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
64602     Mem *aMem = pRec->aMem;
64603     sqlite3 *db = aMem[0].db;
64604     for(i=0; i<nCol; i++){
64605       if( aMem[i].szMalloc ) sqlite3DbFree(db, aMem[i].zMalloc);
64606     }
64607     sqlite3KeyInfoUnref(pRec->pKeyInfo);
64608     sqlite3DbFree(db, pRec);
64609   }
64610 }
64611 #endif /* ifdef SQLITE_ENABLE_STAT4 */
64612
64613 /*
64614 ** Change the string value of an sqlite3_value object
64615 */
64616 SQLITE_PRIVATE void sqlite3ValueSetStr(
64617   sqlite3_value *v,     /* Value to be set */
64618   int n,                /* Length of string z */
64619   const void *z,        /* Text of the new string */
64620   u8 enc,               /* Encoding to use */
64621   void (*xDel)(void*)   /* Destructor for the string */
64622 ){
64623   if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
64624 }
64625
64626 /*
64627 ** Free an sqlite3_value object
64628 */
64629 SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
64630   if( !v ) return;
64631   sqlite3VdbeMemRelease((Mem *)v);
64632   sqlite3DbFree(((Mem*)v)->db, v);
64633 }
64634
64635 /*
64636 ** Return the number of bytes in the sqlite3_value object assuming
64637 ** that it uses the encoding "enc"
64638 */
64639 SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
64640   Mem *p = (Mem*)pVal;
64641   if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
64642     if( p->flags & MEM_Zero ){
64643       return p->n + p->u.nZero;
64644     }else{
64645       return p->n;
64646     }
64647   }
64648   return 0;
64649 }
64650
64651 /************** End of vdbemem.c *********************************************/
64652 /************** Begin file vdbeaux.c *****************************************/
64653 /*
64654 ** 2003 September 6
64655 **
64656 ** The author disclaims copyright to this source code.  In place of
64657 ** a legal notice, here is a blessing:
64658 **
64659 **    May you do good and not evil.
64660 **    May you find forgiveness for yourself and forgive others.
64661 **    May you share freely, never taking more than you give.
64662 **
64663 *************************************************************************
64664 ** This file contains code used for creating, destroying, and populating
64665 ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.) 
64666 */
64667
64668 /*
64669 ** Create a new virtual database engine.
64670 */
64671 SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
64672   sqlite3 *db = pParse->db;
64673   Vdbe *p;
64674   p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
64675   if( p==0 ) return 0;
64676   p->db = db;
64677   if( db->pVdbe ){
64678     db->pVdbe->pPrev = p;
64679   }
64680   p->pNext = db->pVdbe;
64681   p->pPrev = 0;
64682   db->pVdbe = p;
64683   p->magic = VDBE_MAGIC_INIT;
64684   p->pParse = pParse;
64685   assert( pParse->aLabel==0 );
64686   assert( pParse->nLabel==0 );
64687   assert( pParse->nOpAlloc==0 );
64688   return p;
64689 }
64690
64691 /*
64692 ** Remember the SQL string for a prepared statement.
64693 */
64694 SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
64695   assert( isPrepareV2==1 || isPrepareV2==0 );
64696   if( p==0 ) return;
64697 #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
64698   if( !isPrepareV2 ) return;
64699 #endif
64700   assert( p->zSql==0 );
64701   p->zSql = sqlite3DbStrNDup(p->db, z, n);
64702   p->isPrepareV2 = (u8)isPrepareV2;
64703 }
64704
64705 /*
64706 ** Return the SQL associated with a prepared statement
64707 */
64708 SQLITE_API const char *SQLITE_STDCALL sqlite3_sql(sqlite3_stmt *pStmt){
64709   Vdbe *p = (Vdbe *)pStmt;
64710   return (p && p->isPrepareV2) ? p->zSql : 0;
64711 }
64712
64713 /*
64714 ** Swap all content between two VDBE structures.
64715 */
64716 SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
64717   Vdbe tmp, *pTmp;
64718   char *zTmp;
64719   tmp = *pA;
64720   *pA = *pB;
64721   *pB = tmp;
64722   pTmp = pA->pNext;
64723   pA->pNext = pB->pNext;
64724   pB->pNext = pTmp;
64725   pTmp = pA->pPrev;
64726   pA->pPrev = pB->pPrev;
64727   pB->pPrev = pTmp;
64728   zTmp = pA->zSql;
64729   pA->zSql = pB->zSql;
64730   pB->zSql = zTmp;
64731   pB->isPrepareV2 = pA->isPrepareV2;
64732 }
64733
64734 /*
64735 ** Resize the Vdbe.aOp array so that it is at least nOp elements larger 
64736 ** than its current size. nOp is guaranteed to be less than or equal
64737 ** to 1024/sizeof(Op).
64738 **
64739 ** If an out-of-memory error occurs while resizing the array, return
64740 ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain 
64741 ** unchanged (this is so that any opcodes already allocated can be 
64742 ** correctly deallocated along with the rest of the Vdbe).
64743 */
64744 static int growOpArray(Vdbe *v, int nOp){
64745   VdbeOp *pNew;
64746   Parse *p = v->pParse;
64747
64748   /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
64749   ** more frequent reallocs and hence provide more opportunities for 
64750   ** simulated OOM faults.  SQLITE_TEST_REALLOC_STRESS is generally used
64751   ** during testing only.  With SQLITE_TEST_REALLOC_STRESS grow the op array
64752   ** by the minimum* amount required until the size reaches 512.  Normal
64753   ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
64754   ** size of the op array or add 1KB of space, whichever is smaller. */
64755 #ifdef SQLITE_TEST_REALLOC_STRESS
64756   int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
64757 #else
64758   int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
64759   UNUSED_PARAMETER(nOp);
64760 #endif
64761
64762   assert( nOp<=(1024/sizeof(Op)) );
64763   assert( nNew>=(p->nOpAlloc+nOp) );
64764   pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
64765   if( pNew ){
64766     p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
64767     v->aOp = pNew;
64768   }
64769   return (pNew ? SQLITE_OK : SQLITE_NOMEM);
64770 }
64771
64772 #ifdef SQLITE_DEBUG
64773 /* This routine is just a convenient place to set a breakpoint that will
64774 ** fire after each opcode is inserted and displayed using
64775 ** "PRAGMA vdbe_addoptrace=on".
64776 */
64777 static void test_addop_breakpoint(void){
64778   static int n = 0;
64779   n++;
64780 }
64781 #endif
64782
64783 /*
64784 ** Add a new instruction to the list of instructions current in the
64785 ** VDBE.  Return the address of the new instruction.
64786 **
64787 ** Parameters:
64788 **
64789 **    p               Pointer to the VDBE
64790 **
64791 **    op              The opcode for this instruction
64792 **
64793 **    p1, p2, p3      Operands
64794 **
64795 ** Use the sqlite3VdbeResolveLabel() function to fix an address and
64796 ** the sqlite3VdbeChangeP4() function to change the value of the P4
64797 ** operand.
64798 */
64799 SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
64800   int i;
64801   VdbeOp *pOp;
64802
64803   i = p->nOp;
64804   assert( p->magic==VDBE_MAGIC_INIT );
64805   assert( op>0 && op<0xff );
64806   if( p->pParse->nOpAlloc<=i ){
64807     if( growOpArray(p, 1) ){
64808       return 1;
64809     }
64810   }
64811   p->nOp++;
64812   pOp = &p->aOp[i];
64813   pOp->opcode = (u8)op;
64814   pOp->p5 = 0;
64815   pOp->p1 = p1;
64816   pOp->p2 = p2;
64817   pOp->p3 = p3;
64818   pOp->p4.p = 0;
64819   pOp->p4type = P4_NOTUSED;
64820 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
64821   pOp->zComment = 0;
64822 #endif
64823 #ifdef SQLITE_DEBUG
64824   if( p->db->flags & SQLITE_VdbeAddopTrace ){
64825     int jj, kk;
64826     Parse *pParse = p->pParse;
64827     for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
64828       struct yColCache *x = pParse->aColCache + jj;
64829       if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
64830       printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
64831       kk++;
64832     }
64833     if( kk ) printf("\n");
64834     sqlite3VdbePrintOp(0, i, &p->aOp[i]);
64835     test_addop_breakpoint();
64836   }
64837 #endif
64838 #ifdef VDBE_PROFILE
64839   pOp->cycles = 0;
64840   pOp->cnt = 0;
64841 #endif
64842 #ifdef SQLITE_VDBE_COVERAGE
64843   pOp->iSrcLine = 0;
64844 #endif
64845   return i;
64846 }
64847 SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
64848   return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
64849 }
64850 SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
64851   return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
64852 }
64853 SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
64854   return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
64855 }
64856
64857
64858 /*
64859 ** Add an opcode that includes the p4 value as a pointer.
64860 */
64861 SQLITE_PRIVATE int sqlite3VdbeAddOp4(
64862   Vdbe *p,            /* Add the opcode to this VM */
64863   int op,             /* The new opcode */
64864   int p1,             /* The P1 operand */
64865   int p2,             /* The P2 operand */
64866   int p3,             /* The P3 operand */
64867   const char *zP4,    /* The P4 operand */
64868   int p4type          /* P4 operand type */
64869 ){
64870   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
64871   sqlite3VdbeChangeP4(p, addr, zP4, p4type);
64872   return addr;
64873 }
64874
64875 /*
64876 ** Add an OP_ParseSchema opcode.  This routine is broken out from
64877 ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
64878 ** as having been used.
64879 **
64880 ** The zWhere string must have been obtained from sqlite3_malloc().
64881 ** This routine will take ownership of the allocated memory.
64882 */
64883 SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
64884   int j;
64885   int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
64886   sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
64887   for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
64888 }
64889
64890 /*
64891 ** Add an opcode that includes the p4 value as an integer.
64892 */
64893 SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
64894   Vdbe *p,            /* Add the opcode to this VM */
64895   int op,             /* The new opcode */
64896   int p1,             /* The P1 operand */
64897   int p2,             /* The P2 operand */
64898   int p3,             /* The P3 operand */
64899   int p4              /* The P4 operand as an integer */
64900 ){
64901   int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
64902   sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
64903   return addr;
64904 }
64905
64906 /*
64907 ** Create a new symbolic label for an instruction that has yet to be
64908 ** coded.  The symbolic label is really just a negative number.  The
64909 ** label can be used as the P2 value of an operation.  Later, when
64910 ** the label is resolved to a specific address, the VDBE will scan
64911 ** through its operation list and change all values of P2 which match
64912 ** the label into the resolved address.
64913 **
64914 ** The VDBE knows that a P2 value is a label because labels are
64915 ** always negative and P2 values are suppose to be non-negative.
64916 ** Hence, a negative P2 value is a label that has yet to be resolved.
64917 **
64918 ** Zero is returned if a malloc() fails.
64919 */
64920 SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
64921   Parse *p = v->pParse;
64922   int i = p->nLabel++;
64923   assert( v->magic==VDBE_MAGIC_INIT );
64924   if( (i & (i-1))==0 ){
64925     p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel, 
64926                                        (i*2+1)*sizeof(p->aLabel[0]));
64927   }
64928   if( p->aLabel ){
64929     p->aLabel[i] = -1;
64930   }
64931   return -1-i;
64932 }
64933
64934 /*
64935 ** Resolve label "x" to be the address of the next instruction to
64936 ** be inserted.  The parameter "x" must have been obtained from
64937 ** a prior call to sqlite3VdbeMakeLabel().
64938 */
64939 SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
64940   Parse *p = v->pParse;
64941   int j = -1-x;
64942   assert( v->magic==VDBE_MAGIC_INIT );
64943   assert( j<p->nLabel );
64944   if( ALWAYS(j>=0) && p->aLabel ){
64945     p->aLabel[j] = v->nOp;
64946   }
64947   p->iFixedOp = v->nOp - 1;
64948 }
64949
64950 /*
64951 ** Mark the VDBE as one that can only be run one time.
64952 */
64953 SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
64954   p->runOnlyOnce = 1;
64955 }
64956
64957 #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
64958
64959 /*
64960 ** The following type and function are used to iterate through all opcodes
64961 ** in a Vdbe main program and each of the sub-programs (triggers) it may 
64962 ** invoke directly or indirectly. It should be used as follows:
64963 **
64964 **   Op *pOp;
64965 **   VdbeOpIter sIter;
64966 **
64967 **   memset(&sIter, 0, sizeof(sIter));
64968 **   sIter.v = v;                            // v is of type Vdbe* 
64969 **   while( (pOp = opIterNext(&sIter)) ){
64970 **     // Do something with pOp
64971 **   }
64972 **   sqlite3DbFree(v->db, sIter.apSub);
64973 ** 
64974 */
64975 typedef struct VdbeOpIter VdbeOpIter;
64976 struct VdbeOpIter {
64977   Vdbe *v;                   /* Vdbe to iterate through the opcodes of */
64978   SubProgram **apSub;        /* Array of subprograms */
64979   int nSub;                  /* Number of entries in apSub */
64980   int iAddr;                 /* Address of next instruction to return */
64981   int iSub;                  /* 0 = main program, 1 = first sub-program etc. */
64982 };
64983 static Op *opIterNext(VdbeOpIter *p){
64984   Vdbe *v = p->v;
64985   Op *pRet = 0;
64986   Op *aOp;
64987   int nOp;
64988
64989   if( p->iSub<=p->nSub ){
64990
64991     if( p->iSub==0 ){
64992       aOp = v->aOp;
64993       nOp = v->nOp;
64994     }else{
64995       aOp = p->apSub[p->iSub-1]->aOp;
64996       nOp = p->apSub[p->iSub-1]->nOp;
64997     }
64998     assert( p->iAddr<nOp );
64999
65000     pRet = &aOp[p->iAddr];
65001     p->iAddr++;
65002     if( p->iAddr==nOp ){
65003       p->iSub++;
65004       p->iAddr = 0;
65005     }
65006   
65007     if( pRet->p4type==P4_SUBPROGRAM ){
65008       int nByte = (p->nSub+1)*sizeof(SubProgram*);
65009       int j;
65010       for(j=0; j<p->nSub; j++){
65011         if( p->apSub[j]==pRet->p4.pProgram ) break;
65012       }
65013       if( j==p->nSub ){
65014         p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
65015         if( !p->apSub ){
65016           pRet = 0;
65017         }else{
65018           p->apSub[p->nSub++] = pRet->p4.pProgram;
65019         }
65020       }
65021     }
65022   }
65023
65024   return pRet;
65025 }
65026
65027 /*
65028 ** Check if the program stored in the VM associated with pParse may
65029 ** throw an ABORT exception (causing the statement, but not entire transaction
65030 ** to be rolled back). This condition is true if the main program or any
65031 ** sub-programs contains any of the following:
65032 **
65033 **   *  OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
65034 **   *  OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
65035 **   *  OP_Destroy
65036 **   *  OP_VUpdate
65037 **   *  OP_VRename
65038 **   *  OP_FkCounter with P2==0 (immediate foreign key constraint)
65039 **
65040 ** Then check that the value of Parse.mayAbort is true if an
65041 ** ABORT may be thrown, or false otherwise. Return true if it does
65042 ** match, or false otherwise. This function is intended to be used as
65043 ** part of an assert statement in the compiler. Similar to:
65044 **
65045 **   assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
65046 */
65047 SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
65048   int hasAbort = 0;
65049   int hasFkCounter = 0;
65050   Op *pOp;
65051   VdbeOpIter sIter;
65052   memset(&sIter, 0, sizeof(sIter));
65053   sIter.v = v;
65054
65055   while( (pOp = opIterNext(&sIter))!=0 ){
65056     int opcode = pOp->opcode;
65057     if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename 
65058      || ((opcode==OP_Halt || opcode==OP_HaltIfNull) 
65059       && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
65060     ){
65061       hasAbort = 1;
65062       break;
65063     }
65064 #ifndef SQLITE_OMIT_FOREIGN_KEY
65065     if( opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1 ){
65066       hasFkCounter = 1;
65067     }
65068 #endif
65069   }
65070   sqlite3DbFree(v->db, sIter.apSub);
65071
65072   /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
65073   ** If malloc failed, then the while() loop above may not have iterated
65074   ** through all opcodes and hasAbort may be set incorrectly. Return
65075   ** true for this case to prevent the assert() in the callers frame
65076   ** from failing.  */
65077   return ( v->db->mallocFailed || hasAbort==mayAbort || hasFkCounter );
65078 }
65079 #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
65080
65081 /*
65082 ** Loop through the program looking for P2 values that are negative
65083 ** on jump instructions.  Each such value is a label.  Resolve the
65084 ** label by setting the P2 value to its correct non-zero value.
65085 **
65086 ** This routine is called once after all opcodes have been inserted.
65087 **
65088 ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument 
65089 ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by 
65090 ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
65091 **
65092 ** The Op.opflags field is set on all opcodes.
65093 */
65094 static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
65095   int i;
65096   int nMaxArgs = *pMaxFuncArgs;
65097   Op *pOp;
65098   Parse *pParse = p->pParse;
65099   int *aLabel = pParse->aLabel;
65100   p->readOnly = 1;
65101   p->bIsReader = 0;
65102   for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
65103     u8 opcode = pOp->opcode;
65104
65105     /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
65106     ** cases from this switch! */
65107     switch( opcode ){
65108       case OP_Function:
65109       case OP_AggStep: {
65110         if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
65111         break;
65112       }
65113       case OP_Transaction: {
65114         if( pOp->p2!=0 ) p->readOnly = 0;
65115         /* fall thru */
65116       }
65117       case OP_AutoCommit:
65118       case OP_Savepoint: {
65119         p->bIsReader = 1;
65120         break;
65121       }
65122 #ifndef SQLITE_OMIT_WAL
65123       case OP_Checkpoint:
65124 #endif
65125       case OP_Vacuum:
65126       case OP_JournalMode: {
65127         p->readOnly = 0;
65128         p->bIsReader = 1;
65129         break;
65130       }
65131 #ifndef SQLITE_OMIT_VIRTUALTABLE
65132       case OP_VUpdate: {
65133         if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
65134         break;
65135       }
65136       case OP_VFilter: {
65137         int n;
65138         assert( p->nOp - i >= 3 );
65139         assert( pOp[-1].opcode==OP_Integer );
65140         n = pOp[-1].p1;
65141         if( n>nMaxArgs ) nMaxArgs = n;
65142         break;
65143       }
65144 #endif
65145       case OP_Next:
65146       case OP_NextIfOpen:
65147       case OP_SorterNext: {
65148         pOp->p4.xAdvance = sqlite3BtreeNext;
65149         pOp->p4type = P4_ADVANCE;
65150         break;
65151       }
65152       case OP_Prev:
65153       case OP_PrevIfOpen: {
65154         pOp->p4.xAdvance = sqlite3BtreePrevious;
65155         pOp->p4type = P4_ADVANCE;
65156         break;
65157       }
65158     }
65159
65160     pOp->opflags = sqlite3OpcodeProperty[opcode];
65161     if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
65162       assert( -1-pOp->p2<pParse->nLabel );
65163       pOp->p2 = aLabel[-1-pOp->p2];
65164     }
65165   }
65166   sqlite3DbFree(p->db, pParse->aLabel);
65167   pParse->aLabel = 0;
65168   pParse->nLabel = 0;
65169   *pMaxFuncArgs = nMaxArgs;
65170   assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
65171 }
65172
65173 /*
65174 ** Return the address of the next instruction to be inserted.
65175 */
65176 SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
65177   assert( p->magic==VDBE_MAGIC_INIT );
65178   return p->nOp;
65179 }
65180
65181 /*
65182 ** This function returns a pointer to the array of opcodes associated with
65183 ** the Vdbe passed as the first argument. It is the callers responsibility
65184 ** to arrange for the returned array to be eventually freed using the 
65185 ** vdbeFreeOpArray() function.
65186 **
65187 ** Before returning, *pnOp is set to the number of entries in the returned
65188 ** array. Also, *pnMaxArg is set to the larger of its current value and 
65189 ** the number of entries in the Vdbe.apArg[] array required to execute the 
65190 ** returned program.
65191 */
65192 SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
65193   VdbeOp *aOp = p->aOp;
65194   assert( aOp && !p->db->mallocFailed );
65195
65196   /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
65197   assert( DbMaskAllZero(p->btreeMask) );
65198
65199   resolveP2Values(p, pnMaxArg);
65200   *pnOp = p->nOp;
65201   p->aOp = 0;
65202   return aOp;
65203 }
65204
65205 /*
65206 ** Add a whole list of operations to the operation stack.  Return the
65207 ** address of the first operation added.
65208 */
65209 SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp, int iLineno){
65210   int addr;
65211   assert( p->magic==VDBE_MAGIC_INIT );
65212   if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
65213     return 0;
65214   }
65215   addr = p->nOp;
65216   if( ALWAYS(nOp>0) ){
65217     int i;
65218     VdbeOpList const *pIn = aOp;
65219     for(i=0; i<nOp; i++, pIn++){
65220       int p2 = pIn->p2;
65221       VdbeOp *pOut = &p->aOp[i+addr];
65222       pOut->opcode = pIn->opcode;
65223       pOut->p1 = pIn->p1;
65224       if( p2<0 ){
65225         assert( sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP );
65226         pOut->p2 = addr + ADDR(p2);
65227       }else{
65228         pOut->p2 = p2;
65229       }
65230       pOut->p3 = pIn->p3;
65231       pOut->p4type = P4_NOTUSED;
65232       pOut->p4.p = 0;
65233       pOut->p5 = 0;
65234 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
65235       pOut->zComment = 0;
65236 #endif
65237 #ifdef SQLITE_VDBE_COVERAGE
65238       pOut->iSrcLine = iLineno+i;
65239 #else
65240       (void)iLineno;
65241 #endif
65242 #ifdef SQLITE_DEBUG
65243       if( p->db->flags & SQLITE_VdbeAddopTrace ){
65244         sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
65245       }
65246 #endif
65247     }
65248     p->nOp += nOp;
65249   }
65250   return addr;
65251 }
65252
65253 #if defined(SQLITE_ENABLE_STMT_SCANSTATUS)
65254 /*
65255 ** Add an entry to the array of counters managed by sqlite3_stmt_scanstatus().
65256 */
65257 SQLITE_PRIVATE void sqlite3VdbeScanStatus(
65258   Vdbe *p,                        /* VM to add scanstatus() to */
65259   int addrExplain,                /* Address of OP_Explain (or 0) */
65260   int addrLoop,                   /* Address of loop counter */ 
65261   int addrVisit,                  /* Address of rows visited counter */
65262   LogEst nEst,                    /* Estimated number of output rows */
65263   const char *zName               /* Name of table or index being scanned */
65264 ){
65265   int nByte = (p->nScan+1) * sizeof(ScanStatus);
65266   ScanStatus *aNew;
65267   aNew = (ScanStatus*)sqlite3DbRealloc(p->db, p->aScan, nByte);
65268   if( aNew ){
65269     ScanStatus *pNew = &aNew[p->nScan++];
65270     pNew->addrExplain = addrExplain;
65271     pNew->addrLoop = addrLoop;
65272     pNew->addrVisit = addrVisit;
65273     pNew->nEst = nEst;
65274     pNew->zName = sqlite3DbStrDup(p->db, zName);
65275     p->aScan = aNew;
65276   }
65277 }
65278 #endif
65279
65280
65281 /*
65282 ** Change the value of the P1 operand for a specific instruction.
65283 ** This routine is useful when a large program is loaded from a
65284 ** static array using sqlite3VdbeAddOpList but we want to make a
65285 ** few minor changes to the program.
65286 */
65287 SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
65288   assert( p!=0 );
65289   if( ((u32)p->nOp)>addr ){
65290     p->aOp[addr].p1 = val;
65291   }
65292 }
65293
65294 /*
65295 ** Change the value of the P2 operand for a specific instruction.
65296 ** This routine is useful for setting a jump destination.
65297 */
65298 SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
65299   assert( p!=0 );
65300   if( ((u32)p->nOp)>addr ){
65301     p->aOp[addr].p2 = val;
65302   }
65303 }
65304
65305 /*
65306 ** Change the value of the P3 operand for a specific instruction.
65307 */
65308 SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
65309   assert( p!=0 );
65310   if( ((u32)p->nOp)>addr ){
65311     p->aOp[addr].p3 = val;
65312   }
65313 }
65314
65315 /*
65316 ** Change the value of the P5 operand for the most recently
65317 ** added operation.
65318 */
65319 SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
65320   assert( p!=0 );
65321   if( p->aOp ){
65322     assert( p->nOp>0 );
65323     p->aOp[p->nOp-1].p5 = val;
65324   }
65325 }
65326
65327 /*
65328 ** Change the P2 operand of instruction addr so that it points to
65329 ** the address of the next instruction to be coded.
65330 */
65331 SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
65332   sqlite3VdbeChangeP2(p, addr, p->nOp);
65333   p->pParse->iFixedOp = p->nOp - 1;
65334 }
65335
65336
65337 /*
65338 ** If the input FuncDef structure is ephemeral, then free it.  If
65339 ** the FuncDef is not ephermal, then do nothing.
65340 */
65341 static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
65342   if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
65343     sqlite3DbFree(db, pDef);
65344   }
65345 }
65346
65347 static void vdbeFreeOpArray(sqlite3 *, Op *, int);
65348
65349 /*
65350 ** Delete a P4 value if necessary.
65351 */
65352 static void freeP4(sqlite3 *db, int p4type, void *p4){
65353   if( p4 ){
65354     assert( db );
65355     switch( p4type ){
65356       case P4_REAL:
65357       case P4_INT64:
65358       case P4_DYNAMIC:
65359       case P4_INTARRAY: {
65360         sqlite3DbFree(db, p4);
65361         break;
65362       }
65363       case P4_KEYINFO: {
65364         if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
65365         break;
65366       }
65367       case P4_MPRINTF: {
65368         if( db->pnBytesFreed==0 ) sqlite3_free(p4);
65369         break;
65370       }
65371       case P4_FUNCDEF: {
65372         freeEphemeralFunction(db, (FuncDef*)p4);
65373         break;
65374       }
65375       case P4_MEM: {
65376         if( db->pnBytesFreed==0 ){
65377           sqlite3ValueFree((sqlite3_value*)p4);
65378         }else{
65379           Mem *p = (Mem*)p4;
65380           if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
65381           sqlite3DbFree(db, p);
65382         }
65383         break;
65384       }
65385       case P4_VTAB : {
65386         if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
65387         break;
65388       }
65389     }
65390   }
65391 }
65392
65393 /*
65394 ** Free the space allocated for aOp and any p4 values allocated for the
65395 ** opcodes contained within. If aOp is not NULL it is assumed to contain 
65396 ** nOp entries. 
65397 */
65398 static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
65399   if( aOp ){
65400     Op *pOp;
65401     for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
65402       freeP4(db, pOp->p4type, pOp->p4.p);
65403 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
65404       sqlite3DbFree(db, pOp->zComment);
65405 #endif     
65406     }
65407   }
65408   sqlite3DbFree(db, aOp);
65409 }
65410
65411 /*
65412 ** Link the SubProgram object passed as the second argument into the linked
65413 ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
65414 ** objects when the VM is no longer required.
65415 */
65416 SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
65417   p->pNext = pVdbe->pProgram;
65418   pVdbe->pProgram = p;
65419 }
65420
65421 /*
65422 ** Change the opcode at addr into OP_Noop
65423 */
65424 SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
65425   if( addr<p->nOp ){
65426     VdbeOp *pOp = &p->aOp[addr];
65427     sqlite3 *db = p->db;
65428     freeP4(db, pOp->p4type, pOp->p4.p);
65429     memset(pOp, 0, sizeof(pOp[0]));
65430     pOp->opcode = OP_Noop;
65431     if( addr==p->nOp-1 ) p->nOp--;
65432   }
65433 }
65434
65435 /*
65436 ** If the last opcode is "op" and it is not a jump destination,
65437 ** then remove it.  Return true if and only if an opcode was removed.
65438 */
65439 SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
65440   if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
65441     sqlite3VdbeChangeToNoop(p, p->nOp-1);
65442     return 1;
65443   }else{
65444     return 0;
65445   }
65446 }
65447
65448 /*
65449 ** Change the value of the P4 operand for a specific instruction.
65450 ** This routine is useful when a large program is loaded from a
65451 ** static array using sqlite3VdbeAddOpList but we want to make a
65452 ** few minor changes to the program.
65453 **
65454 ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
65455 ** the string is made into memory obtained from sqlite3_malloc().
65456 ** A value of n==0 means copy bytes of zP4 up to and including the
65457 ** first null byte.  If n>0 then copy n+1 bytes of zP4.
65458 ** 
65459 ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
65460 ** to a string or structure that is guaranteed to exist for the lifetime of
65461 ** the Vdbe. In these cases we can just copy the pointer.
65462 **
65463 ** If addr<0 then change P4 on the most recently inserted instruction.
65464 */
65465 SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
65466   Op *pOp;
65467   sqlite3 *db;
65468   assert( p!=0 );
65469   db = p->db;
65470   assert( p->magic==VDBE_MAGIC_INIT );
65471   if( p->aOp==0 || db->mallocFailed ){
65472     if( n!=P4_VTAB ){
65473       freeP4(db, n, (void*)*(char**)&zP4);
65474     }
65475     return;
65476   }
65477   assert( p->nOp>0 );
65478   assert( addr<p->nOp );
65479   if( addr<0 ){
65480     addr = p->nOp - 1;
65481   }
65482   pOp = &p->aOp[addr];
65483   assert( pOp->p4type==P4_NOTUSED
65484        || pOp->p4type==P4_INT32
65485        || pOp->p4type==P4_KEYINFO );
65486   freeP4(db, pOp->p4type, pOp->p4.p);
65487   pOp->p4.p = 0;
65488   if( n==P4_INT32 ){
65489     /* Note: this cast is safe, because the origin data point was an int
65490     ** that was cast to a (const char *). */
65491     pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
65492     pOp->p4type = P4_INT32;
65493   }else if( zP4==0 ){
65494     pOp->p4.p = 0;
65495     pOp->p4type = P4_NOTUSED;
65496   }else if( n==P4_KEYINFO ){
65497     pOp->p4.p = (void*)zP4;
65498     pOp->p4type = P4_KEYINFO;
65499   }else if( n==P4_VTAB ){
65500     pOp->p4.p = (void*)zP4;
65501     pOp->p4type = P4_VTAB;
65502     sqlite3VtabLock((VTable *)zP4);
65503     assert( ((VTable *)zP4)->db==p->db );
65504   }else if( n<0 ){
65505     pOp->p4.p = (void*)zP4;
65506     pOp->p4type = (signed char)n;
65507   }else{
65508     if( n==0 ) n = sqlite3Strlen30(zP4);
65509     pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
65510     pOp->p4type = P4_DYNAMIC;
65511   }
65512 }
65513
65514 /*
65515 ** Set the P4 on the most recently added opcode to the KeyInfo for the
65516 ** index given.
65517 */
65518 SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
65519   Vdbe *v = pParse->pVdbe;
65520   assert( v!=0 );
65521   assert( pIdx!=0 );
65522   sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
65523                       P4_KEYINFO);
65524 }
65525
65526 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
65527 /*
65528 ** Change the comment on the most recently coded instruction.  Or
65529 ** insert a No-op and add the comment to that new instruction.  This
65530 ** makes the code easier to read during debugging.  None of this happens
65531 ** in a production build.
65532 */
65533 static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
65534   assert( p->nOp>0 || p->aOp==0 );
65535   assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
65536   if( p->nOp ){
65537     assert( p->aOp );
65538     sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
65539     p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
65540   }
65541 }
65542 SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
65543   va_list ap;
65544   if( p ){
65545     va_start(ap, zFormat);
65546     vdbeVComment(p, zFormat, ap);
65547     va_end(ap);
65548   }
65549 }
65550 SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
65551   va_list ap;
65552   if( p ){
65553     sqlite3VdbeAddOp0(p, OP_Noop);
65554     va_start(ap, zFormat);
65555     vdbeVComment(p, zFormat, ap);
65556     va_end(ap);
65557   }
65558 }
65559 #endif  /* NDEBUG */
65560
65561 #ifdef SQLITE_VDBE_COVERAGE
65562 /*
65563 ** Set the value if the iSrcLine field for the previously coded instruction.
65564 */
65565 SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
65566   sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
65567 }
65568 #endif /* SQLITE_VDBE_COVERAGE */
65569
65570 /*
65571 ** Return the opcode for a given address.  If the address is -1, then
65572 ** return the most recently inserted opcode.
65573 **
65574 ** If a memory allocation error has occurred prior to the calling of this
65575 ** routine, then a pointer to a dummy VdbeOp will be returned.  That opcode
65576 ** is readable but not writable, though it is cast to a writable value.
65577 ** The return of a dummy opcode allows the call to continue functioning
65578 ** after an OOM fault without having to check to see if the return from 
65579 ** this routine is a valid pointer.  But because the dummy.opcode is 0,
65580 ** dummy will never be written to.  This is verified by code inspection and
65581 ** by running with Valgrind.
65582 */
65583 SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
65584   /* C89 specifies that the constant "dummy" will be initialized to all
65585   ** zeros, which is correct.  MSVC generates a warning, nevertheless. */
65586   static VdbeOp dummy;  /* Ignore the MSVC warning about no initializer */
65587   assert( p->magic==VDBE_MAGIC_INIT );
65588   if( addr<0 ){
65589     addr = p->nOp - 1;
65590   }
65591   assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
65592   if( p->db->mallocFailed ){
65593     return (VdbeOp*)&dummy;
65594   }else{
65595     return &p->aOp[addr];
65596   }
65597 }
65598
65599 #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
65600 /*
65601 ** Return an integer value for one of the parameters to the opcode pOp
65602 ** determined by character c.
65603 */
65604 static int translateP(char c, const Op *pOp){
65605   if( c=='1' ) return pOp->p1;
65606   if( c=='2' ) return pOp->p2;
65607   if( c=='3' ) return pOp->p3;
65608   if( c=='4' ) return pOp->p4.i;
65609   return pOp->p5;
65610 }
65611
65612 /*
65613 ** Compute a string for the "comment" field of a VDBE opcode listing.
65614 **
65615 ** The Synopsis: field in comments in the vdbe.c source file gets converted
65616 ** to an extra string that is appended to the sqlite3OpcodeName().  In the
65617 ** absence of other comments, this synopsis becomes the comment on the opcode.
65618 ** Some translation occurs:
65619 **
65620 **       "PX"      ->  "r[X]"
65621 **       "PX@PY"   ->  "r[X..X+Y-1]"  or "r[x]" if y is 0 or 1
65622 **       "PX@PY+1" ->  "r[X..X+Y]"    or "r[x]" if y is 0
65623 **       "PY..PY"  ->  "r[X..Y]"      or "r[x]" if y<=x
65624 */
65625 static int displayComment(
65626   const Op *pOp,     /* The opcode to be commented */
65627   const char *zP4,   /* Previously obtained value for P4 */
65628   char *zTemp,       /* Write result here */
65629   int nTemp          /* Space available in zTemp[] */
65630 ){
65631   const char *zOpName;
65632   const char *zSynopsis;
65633   int nOpName;
65634   int ii, jj;
65635   zOpName = sqlite3OpcodeName(pOp->opcode);
65636   nOpName = sqlite3Strlen30(zOpName);
65637   if( zOpName[nOpName+1] ){
65638     int seenCom = 0;
65639     char c;
65640     zSynopsis = zOpName += nOpName + 1;
65641     for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
65642       if( c=='P' ){
65643         c = zSynopsis[++ii];
65644         if( c=='4' ){
65645           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
65646         }else if( c=='X' ){
65647           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
65648           seenCom = 1;
65649         }else{
65650           int v1 = translateP(c, pOp);
65651           int v2;
65652           sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
65653           if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
65654             ii += 3;
65655             jj += sqlite3Strlen30(zTemp+jj);
65656             v2 = translateP(zSynopsis[ii], pOp);
65657             if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
65658               ii += 2;
65659               v2++;
65660             }
65661             if( v2>1 ){
65662               sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
65663             }
65664           }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
65665             ii += 4;
65666           }
65667         }
65668         jj += sqlite3Strlen30(zTemp+jj);
65669       }else{
65670         zTemp[jj++] = c;
65671       }
65672     }
65673     if( !seenCom && jj<nTemp-5 && pOp->zComment ){
65674       sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
65675       jj += sqlite3Strlen30(zTemp+jj);
65676     }
65677     if( jj<nTemp ) zTemp[jj] = 0;
65678   }else if( pOp->zComment ){
65679     sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
65680     jj = sqlite3Strlen30(zTemp);
65681   }else{
65682     zTemp[0] = 0;
65683     jj = 0;
65684   }
65685   return jj;
65686 }
65687 #endif /* SQLITE_DEBUG */
65688
65689
65690 #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
65691      || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
65692 /*
65693 ** Compute a string that describes the P4 parameter for an opcode.
65694 ** Use zTemp for any required temporary buffer space.
65695 */
65696 static char *displayP4(Op *pOp, char *zTemp, int nTemp){
65697   char *zP4 = zTemp;
65698   assert( nTemp>=20 );
65699   switch( pOp->p4type ){
65700     case P4_KEYINFO: {
65701       int i, j;
65702       KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
65703       assert( pKeyInfo->aSortOrder!=0 );
65704       sqlite3_snprintf(nTemp, zTemp, "k(%d", pKeyInfo->nField);
65705       i = sqlite3Strlen30(zTemp);
65706       for(j=0; j<pKeyInfo->nField; j++){
65707         CollSeq *pColl = pKeyInfo->aColl[j];
65708         const char *zColl = pColl ? pColl->zName : "nil";
65709         int n = sqlite3Strlen30(zColl);
65710         if( n==6 && memcmp(zColl,"BINARY",6)==0 ){
65711           zColl = "B";
65712           n = 1;
65713         }
65714         if( i+n>nTemp-6 ){
65715           memcpy(&zTemp[i],",...",4);
65716           break;
65717         }
65718         zTemp[i++] = ',';
65719         if( pKeyInfo->aSortOrder[j] ){
65720           zTemp[i++] = '-';
65721         }
65722         memcpy(&zTemp[i], zColl, n+1);
65723         i += n;
65724       }
65725       zTemp[i++] = ')';
65726       zTemp[i] = 0;
65727       assert( i<nTemp );
65728       break;
65729     }
65730     case P4_COLLSEQ: {
65731       CollSeq *pColl = pOp->p4.pColl;
65732       sqlite3_snprintf(nTemp, zTemp, "(%.20s)", pColl->zName);
65733       break;
65734     }
65735     case P4_FUNCDEF: {
65736       FuncDef *pDef = pOp->p4.pFunc;
65737       sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
65738       break;
65739     }
65740     case P4_INT64: {
65741       sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
65742       break;
65743     }
65744     case P4_INT32: {
65745       sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
65746       break;
65747     }
65748     case P4_REAL: {
65749       sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
65750       break;
65751     }
65752     case P4_MEM: {
65753       Mem *pMem = pOp->p4.pMem;
65754       if( pMem->flags & MEM_Str ){
65755         zP4 = pMem->z;
65756       }else if( pMem->flags & MEM_Int ){
65757         sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
65758       }else if( pMem->flags & MEM_Real ){
65759         sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->u.r);
65760       }else if( pMem->flags & MEM_Null ){
65761         sqlite3_snprintf(nTemp, zTemp, "NULL");
65762       }else{
65763         assert( pMem->flags & MEM_Blob );
65764         zP4 = "(blob)";
65765       }
65766       break;
65767     }
65768 #ifndef SQLITE_OMIT_VIRTUALTABLE
65769     case P4_VTAB: {
65770       sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
65771       sqlite3_snprintf(nTemp, zTemp, "vtab:%p", pVtab);
65772       break;
65773     }
65774 #endif
65775     case P4_INTARRAY: {
65776       sqlite3_snprintf(nTemp, zTemp, "intarray");
65777       break;
65778     }
65779     case P4_SUBPROGRAM: {
65780       sqlite3_snprintf(nTemp, zTemp, "program");
65781       break;
65782     }
65783     case P4_ADVANCE: {
65784       zTemp[0] = 0;
65785       break;
65786     }
65787     default: {
65788       zP4 = pOp->p4.z;
65789       if( zP4==0 ){
65790         zP4 = zTemp;
65791         zTemp[0] = 0;
65792       }
65793     }
65794   }
65795   assert( zP4!=0 );
65796   return zP4;
65797 }
65798 #endif
65799
65800 /*
65801 ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
65802 **
65803 ** The prepared statements need to know in advance the complete set of
65804 ** attached databases that will be use.  A mask of these databases
65805 ** is maintained in p->btreeMask.  The p->lockMask value is the subset of
65806 ** p->btreeMask of databases that will require a lock.
65807 */
65808 SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
65809   assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
65810   assert( i<(int)sizeof(p->btreeMask)*8 );
65811   DbMaskSet(p->btreeMask, i);
65812   if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
65813     DbMaskSet(p->lockMask, i);
65814   }
65815 }
65816
65817 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
65818 /*
65819 ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
65820 ** this routine obtains the mutex associated with each BtShared structure
65821 ** that may be accessed by the VM passed as an argument. In doing so it also
65822 ** sets the BtShared.db member of each of the BtShared structures, ensuring
65823 ** that the correct busy-handler callback is invoked if required.
65824 **
65825 ** If SQLite is not threadsafe but does support shared-cache mode, then
65826 ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
65827 ** of all of BtShared structures accessible via the database handle 
65828 ** associated with the VM.
65829 **
65830 ** If SQLite is not threadsafe and does not support shared-cache mode, this
65831 ** function is a no-op.
65832 **
65833 ** The p->btreeMask field is a bitmask of all btrees that the prepared 
65834 ** statement p will ever use.  Let N be the number of bits in p->btreeMask
65835 ** corresponding to btrees that use shared cache.  Then the runtime of
65836 ** this routine is N*N.  But as N is rarely more than 1, this should not
65837 ** be a problem.
65838 */
65839 SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
65840   int i;
65841   sqlite3 *db;
65842   Db *aDb;
65843   int nDb;
65844   if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
65845   db = p->db;
65846   aDb = db->aDb;
65847   nDb = db->nDb;
65848   for(i=0; i<nDb; i++){
65849     if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
65850       sqlite3BtreeEnter(aDb[i].pBt);
65851     }
65852   }
65853 }
65854 #endif
65855
65856 #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
65857 /*
65858 ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
65859 */
65860 SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
65861   int i;
65862   sqlite3 *db;
65863   Db *aDb;
65864   int nDb;
65865   if( DbMaskAllZero(p->lockMask) ) return;  /* The common case */
65866   db = p->db;
65867   aDb = db->aDb;
65868   nDb = db->nDb;
65869   for(i=0; i<nDb; i++){
65870     if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
65871       sqlite3BtreeLeave(aDb[i].pBt);
65872     }
65873   }
65874 }
65875 #endif
65876
65877 #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
65878 /*
65879 ** Print a single opcode.  This routine is used for debugging only.
65880 */
65881 SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
65882   char *zP4;
65883   char zPtr[50];
65884   char zCom[100];
65885   static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
65886   if( pOut==0 ) pOut = stdout;
65887   zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
65888 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
65889   displayComment(pOp, zP4, zCom, sizeof(zCom));
65890 #else
65891   zCom[0] = 0;
65892 #endif
65893   /* NB:  The sqlite3OpcodeName() function is implemented by code created
65894   ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
65895   ** information from the vdbe.c source text */
65896   fprintf(pOut, zFormat1, pc, 
65897       sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
65898       zCom
65899   );
65900   fflush(pOut);
65901 }
65902 #endif
65903
65904 /*
65905 ** Release an array of N Mem elements
65906 */
65907 static void releaseMemArray(Mem *p, int N){
65908   if( p && N ){
65909     Mem *pEnd = &p[N];
65910     sqlite3 *db = p->db;
65911     u8 malloc_failed = db->mallocFailed;
65912     if( db->pnBytesFreed ){
65913       do{
65914         if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
65915       }while( (++p)<pEnd );
65916       return;
65917     }
65918     do{
65919       assert( (&p[1])==pEnd || p[0].db==p[1].db );
65920       assert( sqlite3VdbeCheckMemInvariants(p) );
65921
65922       /* This block is really an inlined version of sqlite3VdbeMemRelease()
65923       ** that takes advantage of the fact that the memory cell value is 
65924       ** being set to NULL after releasing any dynamic resources.
65925       **
65926       ** The justification for duplicating code is that according to 
65927       ** callgrind, this causes a certain test case to hit the CPU 4.7 
65928       ** percent less (x86 linux, gcc version 4.1.2, -O6) than if 
65929       ** sqlite3MemRelease() were called from here. With -O2, this jumps
65930       ** to 6.6 percent. The test case is inserting 1000 rows into a table 
65931       ** with no indexes using a single prepared INSERT statement, bind() 
65932       ** and reset(). Inserts are grouped into a transaction.
65933       */
65934       testcase( p->flags & MEM_Agg );
65935       testcase( p->flags & MEM_Dyn );
65936       testcase( p->flags & MEM_Frame );
65937       testcase( p->flags & MEM_RowSet );
65938       if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
65939         sqlite3VdbeMemRelease(p);
65940       }else if( p->szMalloc ){
65941         sqlite3DbFree(db, p->zMalloc);
65942         p->szMalloc = 0;
65943       }
65944
65945       p->flags = MEM_Undefined;
65946     }while( (++p)<pEnd );
65947     db->mallocFailed = malloc_failed;
65948   }
65949 }
65950
65951 /*
65952 ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
65953 ** allocated by the OP_Program opcode in sqlite3VdbeExec().
65954 */
65955 SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
65956   int i;
65957   Mem *aMem = VdbeFrameMem(p);
65958   VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
65959   for(i=0; i<p->nChildCsr; i++){
65960     sqlite3VdbeFreeCursor(p->v, apCsr[i]);
65961   }
65962   releaseMemArray(aMem, p->nChildMem);
65963   sqlite3DbFree(p->v->db, p);
65964 }
65965
65966 #ifndef SQLITE_OMIT_EXPLAIN
65967 /*
65968 ** Give a listing of the program in the virtual machine.
65969 **
65970 ** The interface is the same as sqlite3VdbeExec().  But instead of
65971 ** running the code, it invokes the callback once for each instruction.
65972 ** This feature is used to implement "EXPLAIN".
65973 **
65974 ** When p->explain==1, each instruction is listed.  When
65975 ** p->explain==2, only OP_Explain instructions are listed and these
65976 ** are shown in a different format.  p->explain==2 is used to implement
65977 ** EXPLAIN QUERY PLAN.
65978 **
65979 ** When p->explain==1, first the main program is listed, then each of
65980 ** the trigger subprograms are listed one by one.
65981 */
65982 SQLITE_PRIVATE int sqlite3VdbeList(
65983   Vdbe *p                   /* The VDBE */
65984 ){
65985   int nRow;                            /* Stop when row count reaches this */
65986   int nSub = 0;                        /* Number of sub-vdbes seen so far */
65987   SubProgram **apSub = 0;              /* Array of sub-vdbes */
65988   Mem *pSub = 0;                       /* Memory cell hold array of subprogs */
65989   sqlite3 *db = p->db;                 /* The database connection */
65990   int i;                               /* Loop counter */
65991   int rc = SQLITE_OK;                  /* Return code */
65992   Mem *pMem = &p->aMem[1];             /* First Mem of result set */
65993
65994   assert( p->explain );
65995   assert( p->magic==VDBE_MAGIC_RUN );
65996   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
65997
65998   /* Even though this opcode does not use dynamic strings for
65999   ** the result, result columns may become dynamic if the user calls
66000   ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
66001   */
66002   releaseMemArray(pMem, 8);
66003   p->pResultSet = 0;
66004
66005   if( p->rc==SQLITE_NOMEM ){
66006     /* This happens if a malloc() inside a call to sqlite3_column_text() or
66007     ** sqlite3_column_text16() failed.  */
66008     db->mallocFailed = 1;
66009     return SQLITE_ERROR;
66010   }
66011
66012   /* When the number of output rows reaches nRow, that means the
66013   ** listing has finished and sqlite3_step() should return SQLITE_DONE.
66014   ** nRow is the sum of the number of rows in the main program, plus
66015   ** the sum of the number of rows in all trigger subprograms encountered
66016   ** so far.  The nRow value will increase as new trigger subprograms are
66017   ** encountered, but p->pc will eventually catch up to nRow.
66018   */
66019   nRow = p->nOp;
66020   if( p->explain==1 ){
66021     /* The first 8 memory cells are used for the result set.  So we will
66022     ** commandeer the 9th cell to use as storage for an array of pointers
66023     ** to trigger subprograms.  The VDBE is guaranteed to have at least 9
66024     ** cells.  */
66025     assert( p->nMem>9 );
66026     pSub = &p->aMem[9];
66027     if( pSub->flags&MEM_Blob ){
66028       /* On the first call to sqlite3_step(), pSub will hold a NULL.  It is
66029       ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
66030       nSub = pSub->n/sizeof(Vdbe*);
66031       apSub = (SubProgram **)pSub->z;
66032     }
66033     for(i=0; i<nSub; i++){
66034       nRow += apSub[i]->nOp;
66035     }
66036   }
66037
66038   do{
66039     i = p->pc++;
66040   }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
66041   if( i>=nRow ){
66042     p->rc = SQLITE_OK;
66043     rc = SQLITE_DONE;
66044   }else if( db->u1.isInterrupted ){
66045     p->rc = SQLITE_INTERRUPT;
66046     rc = SQLITE_ERROR;
66047     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
66048   }else{
66049     char *zP4;
66050     Op *pOp;
66051     if( i<p->nOp ){
66052       /* The output line number is small enough that we are still in the
66053       ** main program. */
66054       pOp = &p->aOp[i];
66055     }else{
66056       /* We are currently listing subprograms.  Figure out which one and
66057       ** pick up the appropriate opcode. */
66058       int j;
66059       i -= p->nOp;
66060       for(j=0; i>=apSub[j]->nOp; j++){
66061         i -= apSub[j]->nOp;
66062       }
66063       pOp = &apSub[j]->aOp[i];
66064     }
66065     if( p->explain==1 ){
66066       pMem->flags = MEM_Int;
66067       pMem->u.i = i;                                /* Program counter */
66068       pMem++;
66069   
66070       pMem->flags = MEM_Static|MEM_Str|MEM_Term;
66071       pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
66072       assert( pMem->z!=0 );
66073       pMem->n = sqlite3Strlen30(pMem->z);
66074       pMem->enc = SQLITE_UTF8;
66075       pMem++;
66076
66077       /* When an OP_Program opcode is encounter (the only opcode that has
66078       ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
66079       ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
66080       ** has not already been seen.
66081       */
66082       if( pOp->p4type==P4_SUBPROGRAM ){
66083         int nByte = (nSub+1)*sizeof(SubProgram*);
66084         int j;
66085         for(j=0; j<nSub; j++){
66086           if( apSub[j]==pOp->p4.pProgram ) break;
66087         }
66088         if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
66089           apSub = (SubProgram **)pSub->z;
66090           apSub[nSub++] = pOp->p4.pProgram;
66091           pSub->flags |= MEM_Blob;
66092           pSub->n = nSub*sizeof(SubProgram*);
66093         }
66094       }
66095     }
66096
66097     pMem->flags = MEM_Int;
66098     pMem->u.i = pOp->p1;                          /* P1 */
66099     pMem++;
66100
66101     pMem->flags = MEM_Int;
66102     pMem->u.i = pOp->p2;                          /* P2 */
66103     pMem++;
66104
66105     pMem->flags = MEM_Int;
66106     pMem->u.i = pOp->p3;                          /* P3 */
66107     pMem++;
66108
66109     if( sqlite3VdbeMemClearAndResize(pMem, 32) ){ /* P4 */
66110       assert( p->db->mallocFailed );
66111       return SQLITE_ERROR;
66112     }
66113     pMem->flags = MEM_Str|MEM_Term;
66114     zP4 = displayP4(pOp, pMem->z, 32);
66115     if( zP4!=pMem->z ){
66116       sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
66117     }else{
66118       assert( pMem->z!=0 );
66119       pMem->n = sqlite3Strlen30(pMem->z);
66120       pMem->enc = SQLITE_UTF8;
66121     }
66122     pMem++;
66123
66124     if( p->explain==1 ){
66125       if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
66126         assert( p->db->mallocFailed );
66127         return SQLITE_ERROR;
66128       }
66129       pMem->flags = MEM_Str|MEM_Term;
66130       pMem->n = 2;
66131       sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5);   /* P5 */
66132       pMem->enc = SQLITE_UTF8;
66133       pMem++;
66134   
66135 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
66136       if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
66137         assert( p->db->mallocFailed );
66138         return SQLITE_ERROR;
66139       }
66140       pMem->flags = MEM_Str|MEM_Term;
66141       pMem->n = displayComment(pOp, zP4, pMem->z, 500);
66142       pMem->enc = SQLITE_UTF8;
66143 #else
66144       pMem->flags = MEM_Null;                       /* Comment */
66145 #endif
66146     }
66147
66148     p->nResColumn = 8 - 4*(p->explain-1);
66149     p->pResultSet = &p->aMem[1];
66150     p->rc = SQLITE_OK;
66151     rc = SQLITE_ROW;
66152   }
66153   return rc;
66154 }
66155 #endif /* SQLITE_OMIT_EXPLAIN */
66156
66157 #ifdef SQLITE_DEBUG
66158 /*
66159 ** Print the SQL that was used to generate a VDBE program.
66160 */
66161 SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
66162   const char *z = 0;
66163   if( p->zSql ){
66164     z = p->zSql;
66165   }else if( p->nOp>=1 ){
66166     const VdbeOp *pOp = &p->aOp[0];
66167     if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
66168       z = pOp->p4.z;
66169       while( sqlite3Isspace(*z) ) z++;
66170     }
66171   }
66172   if( z ) printf("SQL: [%s]\n", z);
66173 }
66174 #endif
66175
66176 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
66177 /*
66178 ** Print an IOTRACE message showing SQL content.
66179 */
66180 SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
66181   int nOp = p->nOp;
66182   VdbeOp *pOp;
66183   if( sqlite3IoTrace==0 ) return;
66184   if( nOp<1 ) return;
66185   pOp = &p->aOp[0];
66186   if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
66187     int i, j;
66188     char z[1000];
66189     sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
66190     for(i=0; sqlite3Isspace(z[i]); i++){}
66191     for(j=0; z[i]; i++){
66192       if( sqlite3Isspace(z[i]) ){
66193         if( z[i-1]!=' ' ){
66194           z[j++] = ' ';
66195         }
66196       }else{
66197         z[j++] = z[i];
66198       }
66199     }
66200     z[j] = 0;
66201     sqlite3IoTrace("SQL %s\n", z);
66202   }
66203 }
66204 #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
66205
66206 /*
66207 ** Allocate space from a fixed size buffer and return a pointer to
66208 ** that space.  If insufficient space is available, return NULL.
66209 **
66210 ** The pBuf parameter is the initial value of a pointer which will
66211 ** receive the new memory.  pBuf is normally NULL.  If pBuf is not
66212 ** NULL, it means that memory space has already been allocated and that
66213 ** this routine should not allocate any new memory.  When pBuf is not
66214 ** NULL simply return pBuf.  Only allocate new memory space when pBuf
66215 ** is NULL.
66216 **
66217 ** nByte is the number of bytes of space needed.
66218 **
66219 ** *ppFrom points to available space and pEnd points to the end of the
66220 ** available space.  When space is allocated, *ppFrom is advanced past
66221 ** the end of the allocated space.
66222 **
66223 ** *pnByte is a counter of the number of bytes of space that have failed
66224 ** to allocate.  If there is insufficient space in *ppFrom to satisfy the
66225 ** request, then increment *pnByte by the amount of the request.
66226 */
66227 static void *allocSpace(
66228   void *pBuf,          /* Where return pointer will be stored */
66229   int nByte,           /* Number of bytes to allocate */
66230   u8 **ppFrom,         /* IN/OUT: Allocate from *ppFrom */
66231   u8 *pEnd,            /* Pointer to 1 byte past the end of *ppFrom buffer */
66232   int *pnByte          /* If allocation cannot be made, increment *pnByte */
66233 ){
66234   assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
66235   if( pBuf ) return pBuf;
66236   nByte = ROUND8(nByte);
66237   if( &(*ppFrom)[nByte] <= pEnd ){
66238     pBuf = (void*)*ppFrom;
66239     *ppFrom += nByte;
66240   }else{
66241     *pnByte += nByte;
66242   }
66243   return pBuf;
66244 }
66245
66246 /*
66247 ** Rewind the VDBE back to the beginning in preparation for
66248 ** running it.
66249 */
66250 SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
66251 #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
66252   int i;
66253 #endif
66254   assert( p!=0 );
66255   assert( p->magic==VDBE_MAGIC_INIT );
66256
66257   /* There should be at least one opcode.
66258   */
66259   assert( p->nOp>0 );
66260
66261   /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
66262   p->magic = VDBE_MAGIC_RUN;
66263
66264 #ifdef SQLITE_DEBUG
66265   for(i=1; i<p->nMem; i++){
66266     assert( p->aMem[i].db==p->db );
66267   }
66268 #endif
66269   p->pc = -1;
66270   p->rc = SQLITE_OK;
66271   p->errorAction = OE_Abort;
66272   p->magic = VDBE_MAGIC_RUN;
66273   p->nChange = 0;
66274   p->cacheCtr = 1;
66275   p->minWriteFileFormat = 255;
66276   p->iStatement = 0;
66277   p->nFkConstraint = 0;
66278 #ifdef VDBE_PROFILE
66279   for(i=0; i<p->nOp; i++){
66280     p->aOp[i].cnt = 0;
66281     p->aOp[i].cycles = 0;
66282   }
66283 #endif
66284 }
66285
66286 /*
66287 ** Prepare a virtual machine for execution for the first time after
66288 ** creating the virtual machine.  This involves things such
66289 ** as allocating registers and initializing the program counter.
66290 ** After the VDBE has be prepped, it can be executed by one or more
66291 ** calls to sqlite3VdbeExec().  
66292 **
66293 ** This function may be called exactly once on each virtual machine.
66294 ** After this routine is called the VM has been "packaged" and is ready
66295 ** to run.  After this routine is called, further calls to 
66296 ** sqlite3VdbeAddOp() functions are prohibited.  This routine disconnects
66297 ** the Vdbe from the Parse object that helped generate it so that the
66298 ** the Vdbe becomes an independent entity and the Parse object can be
66299 ** destroyed.
66300 **
66301 ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
66302 ** to its initial state after it has been run.
66303 */
66304 SQLITE_PRIVATE void sqlite3VdbeMakeReady(
66305   Vdbe *p,                       /* The VDBE */
66306   Parse *pParse                  /* Parsing context */
66307 ){
66308   sqlite3 *db;                   /* The database connection */
66309   int nVar;                      /* Number of parameters */
66310   int nMem;                      /* Number of VM memory registers */
66311   int nCursor;                   /* Number of cursors required */
66312   int nArg;                      /* Number of arguments in subprograms */
66313   int nOnce;                     /* Number of OP_Once instructions */
66314   int n;                         /* Loop counter */
66315   u8 *zCsr;                      /* Memory available for allocation */
66316   u8 *zEnd;                      /* First byte past allocated memory */
66317   int nByte;                     /* How much extra memory is needed */
66318
66319   assert( p!=0 );
66320   assert( p->nOp>0 );
66321   assert( pParse!=0 );
66322   assert( p->magic==VDBE_MAGIC_INIT );
66323   assert( pParse==p->pParse );
66324   db = p->db;
66325   assert( db->mallocFailed==0 );
66326   nVar = pParse->nVar;
66327   nMem = pParse->nMem;
66328   nCursor = pParse->nTab;
66329   nArg = pParse->nMaxArg;
66330   nOnce = pParse->nOnce;
66331   if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
66332   
66333   /* For each cursor required, also allocate a memory cell. Memory
66334   ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
66335   ** the vdbe program. Instead they are used to allocate space for
66336   ** VdbeCursor/BtCursor structures. The blob of memory associated with 
66337   ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
66338   ** stores the blob of memory associated with cursor 1, etc.
66339   **
66340   ** See also: allocateCursor().
66341   */
66342   nMem += nCursor;
66343
66344   /* Allocate space for memory registers, SQL variables, VDBE cursors and 
66345   ** an array to marshal SQL function arguments in.
66346   */
66347   zCsr = (u8*)&p->aOp[p->nOp];            /* Memory avaliable for allocation */
66348   zEnd = (u8*)&p->aOp[pParse->nOpAlloc];  /* First byte past end of zCsr[] */
66349
66350   resolveP2Values(p, &nArg);
66351   p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
66352   if( pParse->explain && nMem<10 ){
66353     nMem = 10;
66354   }
66355   memset(zCsr, 0, zEnd-zCsr);
66356   zCsr += (zCsr - (u8*)0)&7;
66357   assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
66358   p->expired = 0;
66359
66360   /* Memory for registers, parameters, cursor, etc, is allocated in two
66361   ** passes.  On the first pass, we try to reuse unused space at the 
66362   ** end of the opcode array.  If we are unable to satisfy all memory
66363   ** requirements by reusing the opcode array tail, then the second
66364   ** pass will fill in the rest using a fresh allocation.  
66365   **
66366   ** This two-pass approach that reuses as much memory as possible from
66367   ** the leftover space at the end of the opcode array can significantly
66368   ** reduce the amount of memory held by a prepared statement.
66369   */
66370   do {
66371     nByte = 0;
66372     p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
66373     p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
66374     p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
66375     p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
66376     p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
66377                           &zCsr, zEnd, &nByte);
66378     p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
66379 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
66380     p->anExec = allocSpace(p->anExec, p->nOp*sizeof(i64), &zCsr, zEnd, &nByte);
66381 #endif
66382     if( nByte ){
66383       p->pFree = sqlite3DbMallocZero(db, nByte);
66384     }
66385     zCsr = p->pFree;
66386     zEnd = &zCsr[nByte];
66387   }while( nByte && !db->mallocFailed );
66388
66389   p->nCursor = nCursor;
66390   p->nOnceFlag = nOnce;
66391   if( p->aVar ){
66392     p->nVar = (ynVar)nVar;
66393     for(n=0; n<nVar; n++){
66394       p->aVar[n].flags = MEM_Null;
66395       p->aVar[n].db = db;
66396     }
66397   }
66398   if( p->azVar && pParse->nzVar>0 ){
66399     p->nzVar = pParse->nzVar;
66400     memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
66401     memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
66402   }
66403   if( p->aMem ){
66404     p->aMem--;                      /* aMem[] goes from 1..nMem */
66405     p->nMem = nMem;                 /*       not from 0..nMem-1 */
66406     for(n=1; n<=nMem; n++){
66407       p->aMem[n].flags = MEM_Undefined;
66408       p->aMem[n].db = db;
66409     }
66410   }
66411   p->explain = pParse->explain;
66412   sqlite3VdbeRewind(p);
66413 }
66414
66415 /*
66416 ** Close a VDBE cursor and release all the resources that cursor 
66417 ** happens to hold.
66418 */
66419 SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
66420   if( pCx==0 ){
66421     return;
66422   }
66423   sqlite3VdbeSorterClose(p->db, pCx);
66424   if( pCx->pBt ){
66425     sqlite3BtreeClose(pCx->pBt);
66426     /* The pCx->pCursor will be close automatically, if it exists, by
66427     ** the call above. */
66428   }else if( pCx->pCursor ){
66429     sqlite3BtreeCloseCursor(pCx->pCursor);
66430   }
66431 #ifndef SQLITE_OMIT_VIRTUALTABLE
66432   else if( pCx->pVtabCursor ){
66433     sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
66434     const sqlite3_module *pModule = pVtabCursor->pVtab->pModule;
66435     assert( pVtabCursor->pVtab->nRef>0 );
66436     pVtabCursor->pVtab->nRef--;
66437     pModule->xClose(pVtabCursor);
66438   }
66439 #endif
66440 }
66441
66442 /*
66443 ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
66444 ** is used, for example, when a trigger sub-program is halted to restore
66445 ** control to the main program.
66446 */
66447 SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
66448   Vdbe *v = pFrame->v;
66449 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
66450   v->anExec = pFrame->anExec;
66451 #endif
66452   v->aOnceFlag = pFrame->aOnceFlag;
66453   v->nOnceFlag = pFrame->nOnceFlag;
66454   v->aOp = pFrame->aOp;
66455   v->nOp = pFrame->nOp;
66456   v->aMem = pFrame->aMem;
66457   v->nMem = pFrame->nMem;
66458   v->apCsr = pFrame->apCsr;
66459   v->nCursor = pFrame->nCursor;
66460   v->db->lastRowid = pFrame->lastRowid;
66461   v->nChange = pFrame->nChange;
66462   v->db->nChange = pFrame->nDbChange;
66463   return pFrame->pc;
66464 }
66465
66466 /*
66467 ** Close all cursors.
66468 **
66469 ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory 
66470 ** cell array. This is necessary as the memory cell array may contain
66471 ** pointers to VdbeFrame objects, which may in turn contain pointers to
66472 ** open cursors.
66473 */
66474 static void closeAllCursors(Vdbe *p){
66475   if( p->pFrame ){
66476     VdbeFrame *pFrame;
66477     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
66478     sqlite3VdbeFrameRestore(pFrame);
66479     p->pFrame = 0;
66480     p->nFrame = 0;
66481   }
66482   assert( p->nFrame==0 );
66483
66484   if( p->apCsr ){
66485     int i;
66486     for(i=0; i<p->nCursor; i++){
66487       VdbeCursor *pC = p->apCsr[i];
66488       if( pC ){
66489         sqlite3VdbeFreeCursor(p, pC);
66490         p->apCsr[i] = 0;
66491       }
66492     }
66493   }
66494   if( p->aMem ){
66495     releaseMemArray(&p->aMem[1], p->nMem);
66496   }
66497   while( p->pDelFrame ){
66498     VdbeFrame *pDel = p->pDelFrame;
66499     p->pDelFrame = pDel->pParent;
66500     sqlite3VdbeFrameDelete(pDel);
66501   }
66502
66503   /* Delete any auxdata allocations made by the VM */
66504   if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p, -1, 0);
66505   assert( p->pAuxData==0 );
66506 }
66507
66508 /*
66509 ** Clean up the VM after a single run.
66510 */
66511 static void Cleanup(Vdbe *p){
66512   sqlite3 *db = p->db;
66513
66514 #ifdef SQLITE_DEBUG
66515   /* Execute assert() statements to ensure that the Vdbe.apCsr[] and 
66516   ** Vdbe.aMem[] arrays have already been cleaned up.  */
66517   int i;
66518   if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
66519   if( p->aMem ){
66520     for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
66521   }
66522 #endif
66523
66524   sqlite3DbFree(db, p->zErrMsg);
66525   p->zErrMsg = 0;
66526   p->pResultSet = 0;
66527 }
66528
66529 /*
66530 ** Set the number of result columns that will be returned by this SQL
66531 ** statement. This is now set at compile time, rather than during
66532 ** execution of the vdbe program so that sqlite3_column_count() can
66533 ** be called on an SQL statement before sqlite3_step().
66534 */
66535 SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
66536   Mem *pColName;
66537   int n;
66538   sqlite3 *db = p->db;
66539
66540   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
66541   sqlite3DbFree(db, p->aColName);
66542   n = nResColumn*COLNAME_N;
66543   p->nResColumn = (u16)nResColumn;
66544   p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
66545   if( p->aColName==0 ) return;
66546   while( n-- > 0 ){
66547     pColName->flags = MEM_Null;
66548     pColName->db = p->db;
66549     pColName++;
66550   }
66551 }
66552
66553 /*
66554 ** Set the name of the idx'th column to be returned by the SQL statement.
66555 ** zName must be a pointer to a nul terminated string.
66556 **
66557 ** This call must be made after a call to sqlite3VdbeSetNumCols().
66558 **
66559 ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
66560 ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
66561 ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
66562 */
66563 SQLITE_PRIVATE int sqlite3VdbeSetColName(
66564   Vdbe *p,                         /* Vdbe being configured */
66565   int idx,                         /* Index of column zName applies to */
66566   int var,                         /* One of the COLNAME_* constants */
66567   const char *zName,               /* Pointer to buffer containing name */
66568   void (*xDel)(void*)              /* Memory management strategy for zName */
66569 ){
66570   int rc;
66571   Mem *pColName;
66572   assert( idx<p->nResColumn );
66573   assert( var<COLNAME_N );
66574   if( p->db->mallocFailed ){
66575     assert( !zName || xDel!=SQLITE_DYNAMIC );
66576     return SQLITE_NOMEM;
66577   }
66578   assert( p->aColName!=0 );
66579   pColName = &(p->aColName[idx+var*p->nResColumn]);
66580   rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
66581   assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
66582   return rc;
66583 }
66584
66585 /*
66586 ** A read or write transaction may or may not be active on database handle
66587 ** db. If a transaction is active, commit it. If there is a
66588 ** write-transaction spanning more than one database file, this routine
66589 ** takes care of the master journal trickery.
66590 */
66591 static int vdbeCommit(sqlite3 *db, Vdbe *p){
66592   int i;
66593   int nTrans = 0;  /* Number of databases with an active write-transaction */
66594   int rc = SQLITE_OK;
66595   int needXcommit = 0;
66596
66597 #ifdef SQLITE_OMIT_VIRTUALTABLE
66598   /* With this option, sqlite3VtabSync() is defined to be simply 
66599   ** SQLITE_OK so p is not used. 
66600   */
66601   UNUSED_PARAMETER(p);
66602 #endif
66603
66604   /* Before doing anything else, call the xSync() callback for any
66605   ** virtual module tables written in this transaction. This has to
66606   ** be done before determining whether a master journal file is 
66607   ** required, as an xSync() callback may add an attached database
66608   ** to the transaction.
66609   */
66610   rc = sqlite3VtabSync(db, p);
66611
66612   /* This loop determines (a) if the commit hook should be invoked and
66613   ** (b) how many database files have open write transactions, not 
66614   ** including the temp database. (b) is important because if more than 
66615   ** one database file has an open write transaction, a master journal
66616   ** file is required for an atomic commit.
66617   */ 
66618   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
66619     Btree *pBt = db->aDb[i].pBt;
66620     if( sqlite3BtreeIsInTrans(pBt) ){
66621       needXcommit = 1;
66622       if( i!=1 ) nTrans++;
66623       sqlite3BtreeEnter(pBt);
66624       rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
66625       sqlite3BtreeLeave(pBt);
66626     }
66627   }
66628   if( rc!=SQLITE_OK ){
66629     return rc;
66630   }
66631
66632   /* If there are any write-transactions at all, invoke the commit hook */
66633   if( needXcommit && db->xCommitCallback ){
66634     rc = db->xCommitCallback(db->pCommitArg);
66635     if( rc ){
66636       return SQLITE_CONSTRAINT_COMMITHOOK;
66637     }
66638   }
66639
66640   /* The simple case - no more than one database file (not counting the
66641   ** TEMP database) has a transaction active.   There is no need for the
66642   ** master-journal.
66643   **
66644   ** If the return value of sqlite3BtreeGetFilename() is a zero length
66645   ** string, it means the main database is :memory: or a temp file.  In 
66646   ** that case we do not support atomic multi-file commits, so use the 
66647   ** simple case then too.
66648   */
66649   if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
66650    || nTrans<=1
66651   ){
66652     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
66653       Btree *pBt = db->aDb[i].pBt;
66654       if( pBt ){
66655         rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
66656       }
66657     }
66658
66659     /* Do the commit only if all databases successfully complete phase 1. 
66660     ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
66661     ** IO error while deleting or truncating a journal file. It is unlikely,
66662     ** but could happen. In this case abandon processing and return the error.
66663     */
66664     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
66665       Btree *pBt = db->aDb[i].pBt;
66666       if( pBt ){
66667         rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
66668       }
66669     }
66670     if( rc==SQLITE_OK ){
66671       sqlite3VtabCommit(db);
66672     }
66673   }
66674
66675   /* The complex case - There is a multi-file write-transaction active.
66676   ** This requires a master journal file to ensure the transaction is
66677   ** committed atomically.
66678   */
66679 #ifndef SQLITE_OMIT_DISKIO
66680   else{
66681     sqlite3_vfs *pVfs = db->pVfs;
66682     int needSync = 0;
66683     char *zMaster = 0;   /* File-name for the master journal */
66684     char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
66685     sqlite3_file *pMaster = 0;
66686     i64 offset = 0;
66687     int res;
66688     int retryCount = 0;
66689     int nMainFile;
66690
66691     /* Select a master journal file name */
66692     nMainFile = sqlite3Strlen30(zMainFile);
66693     zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
66694     if( zMaster==0 ) return SQLITE_NOMEM;
66695     do {
66696       u32 iRandom;
66697       if( retryCount ){
66698         if( retryCount>100 ){
66699           sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
66700           sqlite3OsDelete(pVfs, zMaster, 0);
66701           break;
66702         }else if( retryCount==1 ){
66703           sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
66704         }
66705       }
66706       retryCount++;
66707       sqlite3_randomness(sizeof(iRandom), &iRandom);
66708       sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
66709                                (iRandom>>8)&0xffffff, iRandom&0xff);
66710       /* The antipenultimate character of the master journal name must
66711       ** be "9" to avoid name collisions when using 8+3 filenames. */
66712       assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
66713       sqlite3FileSuffix3(zMainFile, zMaster);
66714       rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
66715     }while( rc==SQLITE_OK && res );
66716     if( rc==SQLITE_OK ){
66717       /* Open the master journal. */
66718       rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster, 
66719           SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
66720           SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
66721       );
66722     }
66723     if( rc!=SQLITE_OK ){
66724       sqlite3DbFree(db, zMaster);
66725       return rc;
66726     }
66727  
66728     /* Write the name of each database file in the transaction into the new
66729     ** master journal file. If an error occurs at this point close
66730     ** and delete the master journal file. All the individual journal files
66731     ** still have 'null' as the master journal pointer, so they will roll
66732     ** back independently if a failure occurs.
66733     */
66734     for(i=0; i<db->nDb; i++){
66735       Btree *pBt = db->aDb[i].pBt;
66736       if( sqlite3BtreeIsInTrans(pBt) ){
66737         char const *zFile = sqlite3BtreeGetJournalname(pBt);
66738         if( zFile==0 ){
66739           continue;  /* Ignore TEMP and :memory: databases */
66740         }
66741         assert( zFile[0]!=0 );
66742         if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
66743           needSync = 1;
66744         }
66745         rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
66746         offset += sqlite3Strlen30(zFile)+1;
66747         if( rc!=SQLITE_OK ){
66748           sqlite3OsCloseFree(pMaster);
66749           sqlite3OsDelete(pVfs, zMaster, 0);
66750           sqlite3DbFree(db, zMaster);
66751           return rc;
66752         }
66753       }
66754     }
66755
66756     /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
66757     ** flag is set this is not required.
66758     */
66759     if( needSync 
66760      && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
66761      && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
66762     ){
66763       sqlite3OsCloseFree(pMaster);
66764       sqlite3OsDelete(pVfs, zMaster, 0);
66765       sqlite3DbFree(db, zMaster);
66766       return rc;
66767     }
66768
66769     /* Sync all the db files involved in the transaction. The same call
66770     ** sets the master journal pointer in each individual journal. If
66771     ** an error occurs here, do not delete the master journal file.
66772     **
66773     ** If the error occurs during the first call to
66774     ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
66775     ** master journal file will be orphaned. But we cannot delete it,
66776     ** in case the master journal file name was written into the journal
66777     ** file before the failure occurred.
66778     */
66779     for(i=0; rc==SQLITE_OK && i<db->nDb; i++){ 
66780       Btree *pBt = db->aDb[i].pBt;
66781       if( pBt ){
66782         rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
66783       }
66784     }
66785     sqlite3OsCloseFree(pMaster);
66786     assert( rc!=SQLITE_BUSY );
66787     if( rc!=SQLITE_OK ){
66788       sqlite3DbFree(db, zMaster);
66789       return rc;
66790     }
66791
66792     /* Delete the master journal file. This commits the transaction. After
66793     ** doing this the directory is synced again before any individual
66794     ** transaction files are deleted.
66795     */
66796     rc = sqlite3OsDelete(pVfs, zMaster, needSync);
66797     sqlite3DbFree(db, zMaster);
66798     zMaster = 0;
66799     if( rc ){
66800       return rc;
66801     }
66802
66803     /* All files and directories have already been synced, so the following
66804     ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
66805     ** deleting or truncating journals. If something goes wrong while
66806     ** this is happening we don't really care. The integrity of the
66807     ** transaction is already guaranteed, but some stray 'cold' journals
66808     ** may be lying around. Returning an error code won't help matters.
66809     */
66810     disable_simulated_io_errors();
66811     sqlite3BeginBenignMalloc();
66812     for(i=0; i<db->nDb; i++){ 
66813       Btree *pBt = db->aDb[i].pBt;
66814       if( pBt ){
66815         sqlite3BtreeCommitPhaseTwo(pBt, 1);
66816       }
66817     }
66818     sqlite3EndBenignMalloc();
66819     enable_simulated_io_errors();
66820
66821     sqlite3VtabCommit(db);
66822   }
66823 #endif
66824
66825   return rc;
66826 }
66827
66828 /* 
66829 ** This routine checks that the sqlite3.nVdbeActive count variable
66830 ** matches the number of vdbe's in the list sqlite3.pVdbe that are
66831 ** currently active. An assertion fails if the two counts do not match.
66832 ** This is an internal self-check only - it is not an essential processing
66833 ** step.
66834 **
66835 ** This is a no-op if NDEBUG is defined.
66836 */
66837 #ifndef NDEBUG
66838 static void checkActiveVdbeCnt(sqlite3 *db){
66839   Vdbe *p;
66840   int cnt = 0;
66841   int nWrite = 0;
66842   int nRead = 0;
66843   p = db->pVdbe;
66844   while( p ){
66845     if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
66846       cnt++;
66847       if( p->readOnly==0 ) nWrite++;
66848       if( p->bIsReader ) nRead++;
66849     }
66850     p = p->pNext;
66851   }
66852   assert( cnt==db->nVdbeActive );
66853   assert( nWrite==db->nVdbeWrite );
66854   assert( nRead==db->nVdbeRead );
66855 }
66856 #else
66857 #define checkActiveVdbeCnt(x)
66858 #endif
66859
66860 /*
66861 ** If the Vdbe passed as the first argument opened a statement-transaction,
66862 ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
66863 ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
66864 ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the 
66865 ** statement transaction is committed.
66866 **
66867 ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned. 
66868 ** Otherwise SQLITE_OK.
66869 */
66870 SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
66871   sqlite3 *const db = p->db;
66872   int rc = SQLITE_OK;
66873
66874   /* If p->iStatement is greater than zero, then this Vdbe opened a 
66875   ** statement transaction that should be closed here. The only exception
66876   ** is that an IO error may have occurred, causing an emergency rollback.
66877   ** In this case (db->nStatement==0), and there is nothing to do.
66878   */
66879   if( db->nStatement && p->iStatement ){
66880     int i;
66881     const int iSavepoint = p->iStatement-1;
66882
66883     assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
66884     assert( db->nStatement>0 );
66885     assert( p->iStatement==(db->nStatement+db->nSavepoint) );
66886
66887     for(i=0; i<db->nDb; i++){ 
66888       int rc2 = SQLITE_OK;
66889       Btree *pBt = db->aDb[i].pBt;
66890       if( pBt ){
66891         if( eOp==SAVEPOINT_ROLLBACK ){
66892           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
66893         }
66894         if( rc2==SQLITE_OK ){
66895           rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
66896         }
66897         if( rc==SQLITE_OK ){
66898           rc = rc2;
66899         }
66900       }
66901     }
66902     db->nStatement--;
66903     p->iStatement = 0;
66904
66905     if( rc==SQLITE_OK ){
66906       if( eOp==SAVEPOINT_ROLLBACK ){
66907         rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
66908       }
66909       if( rc==SQLITE_OK ){
66910         rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
66911       }
66912     }
66913
66914     /* If the statement transaction is being rolled back, also restore the 
66915     ** database handles deferred constraint counter to the value it had when 
66916     ** the statement transaction was opened.  */
66917     if( eOp==SAVEPOINT_ROLLBACK ){
66918       db->nDeferredCons = p->nStmtDefCons;
66919       db->nDeferredImmCons = p->nStmtDefImmCons;
66920     }
66921   }
66922   return rc;
66923 }
66924
66925 /*
66926 ** This function is called when a transaction opened by the database 
66927 ** handle associated with the VM passed as an argument is about to be 
66928 ** committed. If there are outstanding deferred foreign key constraint
66929 ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
66930 **
66931 ** If there are outstanding FK violations and this function returns 
66932 ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
66933 ** and write an error message to it. Then return SQLITE_ERROR.
66934 */
66935 #ifndef SQLITE_OMIT_FOREIGN_KEY
66936 SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
66937   sqlite3 *db = p->db;
66938   if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0) 
66939    || (!deferred && p->nFkConstraint>0) 
66940   ){
66941     p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
66942     p->errorAction = OE_Abort;
66943     sqlite3SetString(&p->zErrMsg, db, "FOREIGN KEY constraint failed");
66944     return SQLITE_ERROR;
66945   }
66946   return SQLITE_OK;
66947 }
66948 #endif
66949
66950 /*
66951 ** This routine is called the when a VDBE tries to halt.  If the VDBE
66952 ** has made changes and is in autocommit mode, then commit those
66953 ** changes.  If a rollback is needed, then do the rollback.
66954 **
66955 ** This routine is the only way to move the state of a VM from
66956 ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT.  It is harmless to
66957 ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
66958 **
66959 ** Return an error code.  If the commit could not complete because of
66960 ** lock contention, return SQLITE_BUSY.  If SQLITE_BUSY is returned, it
66961 ** means the close did not happen and needs to be repeated.
66962 */
66963 SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
66964   int rc;                         /* Used to store transient return codes */
66965   sqlite3 *db = p->db;
66966
66967   /* This function contains the logic that determines if a statement or
66968   ** transaction will be committed or rolled back as a result of the
66969   ** execution of this virtual machine. 
66970   **
66971   ** If any of the following errors occur:
66972   **
66973   **     SQLITE_NOMEM
66974   **     SQLITE_IOERR
66975   **     SQLITE_FULL
66976   **     SQLITE_INTERRUPT
66977   **
66978   ** Then the internal cache might have been left in an inconsistent
66979   ** state.  We need to rollback the statement transaction, if there is
66980   ** one, or the complete transaction if there is no statement transaction.
66981   */
66982
66983   if( p->db->mallocFailed ){
66984     p->rc = SQLITE_NOMEM;
66985   }
66986   if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
66987   closeAllCursors(p);
66988   if( p->magic!=VDBE_MAGIC_RUN ){
66989     return SQLITE_OK;
66990   }
66991   checkActiveVdbeCnt(db);
66992
66993   /* No commit or rollback needed if the program never started or if the
66994   ** SQL statement does not read or write a database file.  */
66995   if( p->pc>=0 && p->bIsReader ){
66996     int mrc;   /* Primary error code from p->rc */
66997     int eStatementOp = 0;
66998     int isSpecialError;            /* Set to true if a 'special' error */
66999
67000     /* Lock all btrees used by the statement */
67001     sqlite3VdbeEnter(p);
67002
67003     /* Check for one of the special errors */
67004     mrc = p->rc & 0xff;
67005     isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
67006                      || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
67007     if( isSpecialError ){
67008       /* If the query was read-only and the error code is SQLITE_INTERRUPT, 
67009       ** no rollback is necessary. Otherwise, at least a savepoint 
67010       ** transaction must be rolled back to restore the database to a 
67011       ** consistent state.
67012       **
67013       ** Even if the statement is read-only, it is important to perform
67014       ** a statement or transaction rollback operation. If the error 
67015       ** occurred while writing to the journal, sub-journal or database
67016       ** file as part of an effort to free up cache space (see function
67017       ** pagerStress() in pager.c), the rollback is required to restore 
67018       ** the pager to a consistent state.
67019       */
67020       if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
67021         if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
67022           eStatementOp = SAVEPOINT_ROLLBACK;
67023         }else{
67024           /* We are forced to roll back the active transaction. Before doing
67025           ** so, abort any other statements this handle currently has active.
67026           */
67027           sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
67028           sqlite3CloseSavepoints(db);
67029           db->autoCommit = 1;
67030           p->nChange = 0;
67031         }
67032       }
67033     }
67034
67035     /* Check for immediate foreign key violations. */
67036     if( p->rc==SQLITE_OK ){
67037       sqlite3VdbeCheckFk(p, 0);
67038     }
67039   
67040     /* If the auto-commit flag is set and this is the only active writer 
67041     ** VM, then we do either a commit or rollback of the current transaction. 
67042     **
67043     ** Note: This block also runs if one of the special errors handled 
67044     ** above has occurred. 
67045     */
67046     if( !sqlite3VtabInSync(db) 
67047      && db->autoCommit 
67048      && db->nVdbeWrite==(p->readOnly==0) 
67049     ){
67050       if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
67051         rc = sqlite3VdbeCheckFk(p, 1);
67052         if( rc!=SQLITE_OK ){
67053           if( NEVER(p->readOnly) ){
67054             sqlite3VdbeLeave(p);
67055             return SQLITE_ERROR;
67056           }
67057           rc = SQLITE_CONSTRAINT_FOREIGNKEY;
67058         }else{ 
67059           /* The auto-commit flag is true, the vdbe program was successful 
67060           ** or hit an 'OR FAIL' constraint and there are no deferred foreign
67061           ** key constraints to hold up the transaction. This means a commit 
67062           ** is required. */
67063           rc = vdbeCommit(db, p);
67064         }
67065         if( rc==SQLITE_BUSY && p->readOnly ){
67066           sqlite3VdbeLeave(p);
67067           return SQLITE_BUSY;
67068         }else if( rc!=SQLITE_OK ){
67069           p->rc = rc;
67070           sqlite3RollbackAll(db, SQLITE_OK);
67071           p->nChange = 0;
67072         }else{
67073           db->nDeferredCons = 0;
67074           db->nDeferredImmCons = 0;
67075           db->flags &= ~SQLITE_DeferFKs;
67076           sqlite3CommitInternalChanges(db);
67077         }
67078       }else{
67079         sqlite3RollbackAll(db, SQLITE_OK);
67080         p->nChange = 0;
67081       }
67082       db->nStatement = 0;
67083     }else if( eStatementOp==0 ){
67084       if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
67085         eStatementOp = SAVEPOINT_RELEASE;
67086       }else if( p->errorAction==OE_Abort ){
67087         eStatementOp = SAVEPOINT_ROLLBACK;
67088       }else{
67089         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
67090         sqlite3CloseSavepoints(db);
67091         db->autoCommit = 1;
67092         p->nChange = 0;
67093       }
67094     }
67095   
67096     /* If eStatementOp is non-zero, then a statement transaction needs to
67097     ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
67098     ** do so. If this operation returns an error, and the current statement
67099     ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
67100     ** current statement error code.
67101     */
67102     if( eStatementOp ){
67103       rc = sqlite3VdbeCloseStatement(p, eStatementOp);
67104       if( rc ){
67105         if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
67106           p->rc = rc;
67107           sqlite3DbFree(db, p->zErrMsg);
67108           p->zErrMsg = 0;
67109         }
67110         sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
67111         sqlite3CloseSavepoints(db);
67112         db->autoCommit = 1;
67113         p->nChange = 0;
67114       }
67115     }
67116   
67117     /* If this was an INSERT, UPDATE or DELETE and no statement transaction
67118     ** has been rolled back, update the database connection change-counter. 
67119     */
67120     if( p->changeCntOn ){
67121       if( eStatementOp!=SAVEPOINT_ROLLBACK ){
67122         sqlite3VdbeSetChanges(db, p->nChange);
67123       }else{
67124         sqlite3VdbeSetChanges(db, 0);
67125       }
67126       p->nChange = 0;
67127     }
67128
67129     /* Release the locks */
67130     sqlite3VdbeLeave(p);
67131   }
67132
67133   /* We have successfully halted and closed the VM.  Record this fact. */
67134   if( p->pc>=0 ){
67135     db->nVdbeActive--;
67136     if( !p->readOnly ) db->nVdbeWrite--;
67137     if( p->bIsReader ) db->nVdbeRead--;
67138     assert( db->nVdbeActive>=db->nVdbeRead );
67139     assert( db->nVdbeRead>=db->nVdbeWrite );
67140     assert( db->nVdbeWrite>=0 );
67141   }
67142   p->magic = VDBE_MAGIC_HALT;
67143   checkActiveVdbeCnt(db);
67144   if( p->db->mallocFailed ){
67145     p->rc = SQLITE_NOMEM;
67146   }
67147
67148   /* If the auto-commit flag is set to true, then any locks that were held
67149   ** by connection db have now been released. Call sqlite3ConnectionUnlocked() 
67150   ** to invoke any required unlock-notify callbacks.
67151   */
67152   if( db->autoCommit ){
67153     sqlite3ConnectionUnlocked(db);
67154   }
67155
67156   assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
67157   return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
67158 }
67159
67160
67161 /*
67162 ** Each VDBE holds the result of the most recent sqlite3_step() call
67163 ** in p->rc.  This routine sets that result back to SQLITE_OK.
67164 */
67165 SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
67166   p->rc = SQLITE_OK;
67167 }
67168
67169 /*
67170 ** Copy the error code and error message belonging to the VDBE passed
67171 ** as the first argument to its database handle (so that they will be 
67172 ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
67173 **
67174 ** This function does not clear the VDBE error code or message, just
67175 ** copies them to the database handle.
67176 */
67177 SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
67178   sqlite3 *db = p->db;
67179   int rc = p->rc;
67180   if( p->zErrMsg ){
67181     u8 mallocFailed = db->mallocFailed;
67182     sqlite3BeginBenignMalloc();
67183     if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
67184     sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
67185     sqlite3EndBenignMalloc();
67186     db->mallocFailed = mallocFailed;
67187     db->errCode = rc;
67188   }else{
67189     sqlite3Error(db, rc);
67190   }
67191   return rc;
67192 }
67193
67194 #ifdef SQLITE_ENABLE_SQLLOG
67195 /*
67196 ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run, 
67197 ** invoke it.
67198 */
67199 static void vdbeInvokeSqllog(Vdbe *v){
67200   if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
67201     char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
67202     assert( v->db->init.busy==0 );
67203     if( zExpanded ){
67204       sqlite3GlobalConfig.xSqllog(
67205           sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
67206       );
67207       sqlite3DbFree(v->db, zExpanded);
67208     }
67209   }
67210 }
67211 #else
67212 # define vdbeInvokeSqllog(x)
67213 #endif
67214
67215 /*
67216 ** Clean up a VDBE after execution but do not delete the VDBE just yet.
67217 ** Write any error messages into *pzErrMsg.  Return the result code.
67218 **
67219 ** After this routine is run, the VDBE should be ready to be executed
67220 ** again.
67221 **
67222 ** To look at it another way, this routine resets the state of the
67223 ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
67224 ** VDBE_MAGIC_INIT.
67225 */
67226 SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
67227   sqlite3 *db;
67228   db = p->db;
67229
67230   /* If the VM did not run to completion or if it encountered an
67231   ** error, then it might not have been halted properly.  So halt
67232   ** it now.
67233   */
67234   sqlite3VdbeHalt(p);
67235
67236   /* If the VDBE has be run even partially, then transfer the error code
67237   ** and error message from the VDBE into the main database structure.  But
67238   ** if the VDBE has just been set to run but has not actually executed any
67239   ** instructions yet, leave the main database error information unchanged.
67240   */
67241   if( p->pc>=0 ){
67242     vdbeInvokeSqllog(p);
67243     sqlite3VdbeTransferError(p);
67244     sqlite3DbFree(db, p->zErrMsg);
67245     p->zErrMsg = 0;
67246     if( p->runOnlyOnce ) p->expired = 1;
67247   }else if( p->rc && p->expired ){
67248     /* The expired flag was set on the VDBE before the first call
67249     ** to sqlite3_step(). For consistency (since sqlite3_step() was
67250     ** called), set the database error in this case as well.
67251     */
67252     sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
67253     sqlite3DbFree(db, p->zErrMsg);
67254     p->zErrMsg = 0;
67255   }
67256
67257   /* Reclaim all memory used by the VDBE
67258   */
67259   Cleanup(p);
67260
67261   /* Save profiling information from this VDBE run.
67262   */
67263 #ifdef VDBE_PROFILE
67264   {
67265     FILE *out = fopen("vdbe_profile.out", "a");
67266     if( out ){
67267       int i;
67268       fprintf(out, "---- ");
67269       for(i=0; i<p->nOp; i++){
67270         fprintf(out, "%02x", p->aOp[i].opcode);
67271       }
67272       fprintf(out, "\n");
67273       if( p->zSql ){
67274         char c, pc = 0;
67275         fprintf(out, "-- ");
67276         for(i=0; (c = p->zSql[i])!=0; i++){
67277           if( pc=='\n' ) fprintf(out, "-- ");
67278           putc(c, out);
67279           pc = c;
67280         }
67281         if( pc!='\n' ) fprintf(out, "\n");
67282       }
67283       for(i=0; i<p->nOp; i++){
67284         char zHdr[100];
67285         sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
67286            p->aOp[i].cnt,
67287            p->aOp[i].cycles,
67288            p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
67289         );
67290         fprintf(out, "%s", zHdr);
67291         sqlite3VdbePrintOp(out, i, &p->aOp[i]);
67292       }
67293       fclose(out);
67294     }
67295   }
67296 #endif
67297   p->iCurrentTime = 0;
67298   p->magic = VDBE_MAGIC_INIT;
67299   return p->rc & db->errMask;
67300 }
67301  
67302 /*
67303 ** Clean up and delete a VDBE after execution.  Return an integer which is
67304 ** the result code.  Write any error message text into *pzErrMsg.
67305 */
67306 SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
67307   int rc = SQLITE_OK;
67308   if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
67309     rc = sqlite3VdbeReset(p);
67310     assert( (rc & p->db->errMask)==rc );
67311   }
67312   sqlite3VdbeDelete(p);
67313   return rc;
67314 }
67315
67316 /*
67317 ** If parameter iOp is less than zero, then invoke the destructor for
67318 ** all auxiliary data pointers currently cached by the VM passed as
67319 ** the first argument.
67320 **
67321 ** Or, if iOp is greater than or equal to zero, then the destructor is
67322 ** only invoked for those auxiliary data pointers created by the user 
67323 ** function invoked by the OP_Function opcode at instruction iOp of 
67324 ** VM pVdbe, and only then if:
67325 **
67326 **    * the associated function parameter is the 32nd or later (counting
67327 **      from left to right), or
67328 **
67329 **    * the corresponding bit in argument mask is clear (where the first
67330 **      function parameter corresponds to bit 0 etc.).
67331 */
67332 SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
67333   AuxData **pp = &pVdbe->pAuxData;
67334   while( *pp ){
67335     AuxData *pAux = *pp;
67336     if( (iOp<0)
67337      || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
67338     ){
67339       testcase( pAux->iArg==31 );
67340       if( pAux->xDelete ){
67341         pAux->xDelete(pAux->pAux);
67342       }
67343       *pp = pAux->pNext;
67344       sqlite3DbFree(pVdbe->db, pAux);
67345     }else{
67346       pp= &pAux->pNext;
67347     }
67348   }
67349 }
67350
67351 /*
67352 ** Free all memory associated with the Vdbe passed as the second argument,
67353 ** except for object itself, which is preserved.
67354 **
67355 ** The difference between this function and sqlite3VdbeDelete() is that
67356 ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
67357 ** the database connection and frees the object itself.
67358 */
67359 SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
67360   SubProgram *pSub, *pNext;
67361   int i;
67362   assert( p->db==0 || p->db==db );
67363   releaseMemArray(p->aVar, p->nVar);
67364   releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
67365   for(pSub=p->pProgram; pSub; pSub=pNext){
67366     pNext = pSub->pNext;
67367     vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
67368     sqlite3DbFree(db, pSub);
67369   }
67370   for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
67371   vdbeFreeOpArray(db, p->aOp, p->nOp);
67372   sqlite3DbFree(db, p->aColName);
67373   sqlite3DbFree(db, p->zSql);
67374   sqlite3DbFree(db, p->pFree);
67375 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
67376   for(i=0; i<p->nScan; i++){
67377     sqlite3DbFree(db, p->aScan[i].zName);
67378   }
67379   sqlite3DbFree(db, p->aScan);
67380 #endif
67381 }
67382
67383 /*
67384 ** Delete an entire VDBE.
67385 */
67386 SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
67387   sqlite3 *db;
67388
67389   if( NEVER(p==0) ) return;
67390   db = p->db;
67391   assert( sqlite3_mutex_held(db->mutex) );
67392   sqlite3VdbeClearObject(db, p);
67393   if( p->pPrev ){
67394     p->pPrev->pNext = p->pNext;
67395   }else{
67396     assert( db->pVdbe==p );
67397     db->pVdbe = p->pNext;
67398   }
67399   if( p->pNext ){
67400     p->pNext->pPrev = p->pPrev;
67401   }
67402   p->magic = VDBE_MAGIC_DEAD;
67403   p->db = 0;
67404   sqlite3DbFree(db, p);
67405 }
67406
67407 /*
67408 ** The cursor "p" has a pending seek operation that has not yet been
67409 ** carried out.  Seek the cursor now.  If an error occurs, return
67410 ** the appropriate error code.
67411 */
67412 static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
67413   int res, rc;
67414 #ifdef SQLITE_TEST
67415   extern int sqlite3_search_count;
67416 #endif
67417   assert( p->deferredMoveto );
67418   assert( p->isTable );
67419   rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
67420   if( rc ) return rc;
67421   if( res!=0 ) return SQLITE_CORRUPT_BKPT;
67422 #ifdef SQLITE_TEST
67423   sqlite3_search_count++;
67424 #endif
67425   p->deferredMoveto = 0;
67426   p->cacheStatus = CACHE_STALE;
67427   return SQLITE_OK;
67428 }
67429
67430 /*
67431 ** Something has moved cursor "p" out of place.  Maybe the row it was
67432 ** pointed to was deleted out from under it.  Or maybe the btree was
67433 ** rebalanced.  Whatever the cause, try to restore "p" to the place it
67434 ** is supposed to be pointing.  If the row was deleted out from under the
67435 ** cursor, set the cursor to point to a NULL row.
67436 */
67437 static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
67438   int isDifferentRow, rc;
67439   assert( p->pCursor!=0 );
67440   assert( sqlite3BtreeCursorHasMoved(p->pCursor) );
67441   rc = sqlite3BtreeCursorRestore(p->pCursor, &isDifferentRow);
67442   p->cacheStatus = CACHE_STALE;
67443   if( isDifferentRow ) p->nullRow = 1;
67444   return rc;
67445 }
67446
67447 /*
67448 ** Check to ensure that the cursor is valid.  Restore the cursor
67449 ** if need be.  Return any I/O error from the restore operation.
67450 */
67451 SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
67452   if( sqlite3BtreeCursorHasMoved(p->pCursor) ){
67453     return handleMovedCursor(p);
67454   }
67455   return SQLITE_OK;
67456 }
67457
67458 /*
67459 ** Make sure the cursor p is ready to read or write the row to which it
67460 ** was last positioned.  Return an error code if an OOM fault or I/O error
67461 ** prevents us from positioning the cursor to its correct position.
67462 **
67463 ** If a MoveTo operation is pending on the given cursor, then do that
67464 ** MoveTo now.  If no move is pending, check to see if the row has been
67465 ** deleted out from under the cursor and if it has, mark the row as
67466 ** a NULL row.
67467 **
67468 ** If the cursor is already pointing to the correct row and that row has
67469 ** not been deleted out from under the cursor, then this routine is a no-op.
67470 */
67471 SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
67472   if( p->deferredMoveto ){
67473     return handleDeferredMoveto(p);
67474   }
67475   if( p->pCursor && sqlite3BtreeCursorHasMoved(p->pCursor) ){
67476     return handleMovedCursor(p);
67477   }
67478   return SQLITE_OK;
67479 }
67480
67481 /*
67482 ** The following functions:
67483 **
67484 ** sqlite3VdbeSerialType()
67485 ** sqlite3VdbeSerialTypeLen()
67486 ** sqlite3VdbeSerialLen()
67487 ** sqlite3VdbeSerialPut()
67488 ** sqlite3VdbeSerialGet()
67489 **
67490 ** encapsulate the code that serializes values for storage in SQLite
67491 ** data and index records. Each serialized value consists of a
67492 ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
67493 ** integer, stored as a varint.
67494 **
67495 ** In an SQLite index record, the serial type is stored directly before
67496 ** the blob of data that it corresponds to. In a table record, all serial
67497 ** types are stored at the start of the record, and the blobs of data at
67498 ** the end. Hence these functions allow the caller to handle the
67499 ** serial-type and data blob separately.
67500 **
67501 ** The following table describes the various storage classes for data:
67502 **
67503 **   serial type        bytes of data      type
67504 **   --------------     ---------------    ---------------
67505 **      0                     0            NULL
67506 **      1                     1            signed integer
67507 **      2                     2            signed integer
67508 **      3                     3            signed integer
67509 **      4                     4            signed integer
67510 **      5                     6            signed integer
67511 **      6                     8            signed integer
67512 **      7                     8            IEEE float
67513 **      8                     0            Integer constant 0
67514 **      9                     0            Integer constant 1
67515 **     10,11                               reserved for expansion
67516 **    N>=12 and even       (N-12)/2        BLOB
67517 **    N>=13 and odd        (N-13)/2        text
67518 **
67519 ** The 8 and 9 types were added in 3.3.0, file format 4.  Prior versions
67520 ** of SQLite will not understand those serial types.
67521 */
67522
67523 /*
67524 ** Return the serial-type for the value stored in pMem.
67525 */
67526 SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
67527   int flags = pMem->flags;
67528   u32 n;
67529
67530   if( flags&MEM_Null ){
67531     return 0;
67532   }
67533   if( flags&MEM_Int ){
67534     /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
67535 #   define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
67536     i64 i = pMem->u.i;
67537     u64 u;
67538     if( i<0 ){
67539       u = ~i;
67540     }else{
67541       u = i;
67542     }
67543     if( u<=127 ){
67544       return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
67545     }
67546     if( u<=32767 ) return 2;
67547     if( u<=8388607 ) return 3;
67548     if( u<=2147483647 ) return 4;
67549     if( u<=MAX_6BYTE ) return 5;
67550     return 6;
67551   }
67552   if( flags&MEM_Real ){
67553     return 7;
67554   }
67555   assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
67556   assert( pMem->n>=0 );
67557   n = (u32)pMem->n;
67558   if( flags & MEM_Zero ){
67559     n += pMem->u.nZero;
67560   }
67561   return ((n*2) + 12 + ((flags&MEM_Str)!=0));
67562 }
67563
67564 /*
67565 ** Return the length of the data corresponding to the supplied serial-type.
67566 */
67567 SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
67568   if( serial_type>=12 ){
67569     return (serial_type-12)/2;
67570   }else{
67571     static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
67572     return aSize[serial_type];
67573   }
67574 }
67575
67576 /*
67577 ** If we are on an architecture with mixed-endian floating 
67578 ** points (ex: ARM7) then swap the lower 4 bytes with the 
67579 ** upper 4 bytes.  Return the result.
67580 **
67581 ** For most architectures, this is a no-op.
67582 **
67583 ** (later):  It is reported to me that the mixed-endian problem
67584 ** on ARM7 is an issue with GCC, not with the ARM7 chip.  It seems
67585 ** that early versions of GCC stored the two words of a 64-bit
67586 ** float in the wrong order.  And that error has been propagated
67587 ** ever since.  The blame is not necessarily with GCC, though.
67588 ** GCC might have just copying the problem from a prior compiler.
67589 ** I am also told that newer versions of GCC that follow a different
67590 ** ABI get the byte order right.
67591 **
67592 ** Developers using SQLite on an ARM7 should compile and run their
67593 ** application using -DSQLITE_DEBUG=1 at least once.  With DEBUG
67594 ** enabled, some asserts below will ensure that the byte order of
67595 ** floating point values is correct.
67596 **
67597 ** (2007-08-30)  Frank van Vugt has studied this problem closely
67598 ** and has send his findings to the SQLite developers.  Frank
67599 ** writes that some Linux kernels offer floating point hardware
67600 ** emulation that uses only 32-bit mantissas instead of a full 
67601 ** 48-bits as required by the IEEE standard.  (This is the
67602 ** CONFIG_FPE_FASTFPE option.)  On such systems, floating point
67603 ** byte swapping becomes very complicated.  To avoid problems,
67604 ** the necessary byte swapping is carried out using a 64-bit integer
67605 ** rather than a 64-bit float.  Frank assures us that the code here
67606 ** works for him.  We, the developers, have no way to independently
67607 ** verify this, but Frank seems to know what he is talking about
67608 ** so we trust him.
67609 */
67610 #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
67611 static u64 floatSwap(u64 in){
67612   union {
67613     u64 r;
67614     u32 i[2];
67615   } u;
67616   u32 t;
67617
67618   u.r = in;
67619   t = u.i[0];
67620   u.i[0] = u.i[1];
67621   u.i[1] = t;
67622   return u.r;
67623 }
67624 # define swapMixedEndianFloat(X)  X = floatSwap(X)
67625 #else
67626 # define swapMixedEndianFloat(X)
67627 #endif
67628
67629 /*
67630 ** Write the serialized data blob for the value stored in pMem into 
67631 ** buf. It is assumed that the caller has allocated sufficient space.
67632 ** Return the number of bytes written.
67633 **
67634 ** nBuf is the amount of space left in buf[].  The caller is responsible
67635 ** for allocating enough space to buf[] to hold the entire field, exclusive
67636 ** of the pMem->u.nZero bytes for a MEM_Zero value.
67637 **
67638 ** Return the number of bytes actually written into buf[].  The number
67639 ** of bytes in the zero-filled tail is included in the return value only
67640 ** if those bytes were zeroed in buf[].
67641 */ 
67642 SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
67643   u32 len;
67644
67645   /* Integer and Real */
67646   if( serial_type<=7 && serial_type>0 ){
67647     u64 v;
67648     u32 i;
67649     if( serial_type==7 ){
67650       assert( sizeof(v)==sizeof(pMem->u.r) );
67651       memcpy(&v, &pMem->u.r, sizeof(v));
67652       swapMixedEndianFloat(v);
67653     }else{
67654       v = pMem->u.i;
67655     }
67656     len = i = sqlite3VdbeSerialTypeLen(serial_type);
67657     assert( i>0 );
67658     do{
67659       buf[--i] = (u8)(v&0xFF);
67660       v >>= 8;
67661     }while( i );
67662     return len;
67663   }
67664
67665   /* String or blob */
67666   if( serial_type>=12 ){
67667     assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
67668              == (int)sqlite3VdbeSerialTypeLen(serial_type) );
67669     len = pMem->n;
67670     memcpy(buf, pMem->z, len);
67671     return len;
67672   }
67673
67674   /* NULL or constants 0 or 1 */
67675   return 0;
67676 }
67677
67678 /* Input "x" is a sequence of unsigned characters that represent a
67679 ** big-endian integer.  Return the equivalent native integer
67680 */
67681 #define ONE_BYTE_INT(x)    ((i8)(x)[0])
67682 #define TWO_BYTE_INT(x)    (256*(i8)((x)[0])|(x)[1])
67683 #define THREE_BYTE_INT(x)  (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
67684 #define FOUR_BYTE_UINT(x)  (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
67685 #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
67686
67687 /*
67688 ** Deserialize the data blob pointed to by buf as serial type serial_type
67689 ** and store the result in pMem.  Return the number of bytes read.
67690 **
67691 ** This function is implemented as two separate routines for performance.
67692 ** The few cases that require local variables are broken out into a separate
67693 ** routine so that in most cases the overhead of moving the stack pointer
67694 ** is avoided.
67695 */ 
67696 static u32 SQLITE_NOINLINE serialGet(
67697   const unsigned char *buf,     /* Buffer to deserialize from */
67698   u32 serial_type,              /* Serial type to deserialize */
67699   Mem *pMem                     /* Memory cell to write value into */
67700 ){
67701   u64 x = FOUR_BYTE_UINT(buf);
67702   u32 y = FOUR_BYTE_UINT(buf+4);
67703   x = (x<<32) + y;
67704   if( serial_type==6 ){
67705     /* EVIDENCE-OF: R-29851-52272 Value is a big-endian 64-bit
67706     ** twos-complement integer. */
67707     pMem->u.i = *(i64*)&x;
67708     pMem->flags = MEM_Int;
67709     testcase( pMem->u.i<0 );
67710   }else{
67711     /* EVIDENCE-OF: R-57343-49114 Value is a big-endian IEEE 754-2008 64-bit
67712     ** floating point number. */
67713 #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
67714     /* Verify that integers and floating point values use the same
67715     ** byte order.  Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
67716     ** defined that 64-bit floating point values really are mixed
67717     ** endian.
67718     */
67719     static const u64 t1 = ((u64)0x3ff00000)<<32;
67720     static const double r1 = 1.0;
67721     u64 t2 = t1;
67722     swapMixedEndianFloat(t2);
67723     assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
67724 #endif
67725     assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
67726     swapMixedEndianFloat(x);
67727     memcpy(&pMem->u.r, &x, sizeof(x));
67728     pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
67729   }
67730   return 8;
67731 }
67732 SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
67733   const unsigned char *buf,     /* Buffer to deserialize from */
67734   u32 serial_type,              /* Serial type to deserialize */
67735   Mem *pMem                     /* Memory cell to write value into */
67736 ){
67737   switch( serial_type ){
67738     case 10:   /* Reserved for future use */
67739     case 11:   /* Reserved for future use */
67740     case 0: {  /* Null */
67741       /* EVIDENCE-OF: R-24078-09375 Value is a NULL. */
67742       pMem->flags = MEM_Null;
67743       break;
67744     }
67745     case 1: {
67746       /* EVIDENCE-OF: R-44885-25196 Value is an 8-bit twos-complement
67747       ** integer. */
67748       pMem->u.i = ONE_BYTE_INT(buf);
67749       pMem->flags = MEM_Int;
67750       testcase( pMem->u.i<0 );
67751       return 1;
67752     }
67753     case 2: { /* 2-byte signed integer */
67754       /* EVIDENCE-OF: R-49794-35026 Value is a big-endian 16-bit
67755       ** twos-complement integer. */
67756       pMem->u.i = TWO_BYTE_INT(buf);
67757       pMem->flags = MEM_Int;
67758       testcase( pMem->u.i<0 );
67759       return 2;
67760     }
67761     case 3: { /* 3-byte signed integer */
67762       /* EVIDENCE-OF: R-37839-54301 Value is a big-endian 24-bit
67763       ** twos-complement integer. */
67764       pMem->u.i = THREE_BYTE_INT(buf);
67765       pMem->flags = MEM_Int;
67766       testcase( pMem->u.i<0 );
67767       return 3;
67768     }
67769     case 4: { /* 4-byte signed integer */
67770       /* EVIDENCE-OF: R-01849-26079 Value is a big-endian 32-bit
67771       ** twos-complement integer. */
67772       pMem->u.i = FOUR_BYTE_INT(buf);
67773       pMem->flags = MEM_Int;
67774       testcase( pMem->u.i<0 );
67775       return 4;
67776     }
67777     case 5: { /* 6-byte signed integer */
67778       /* EVIDENCE-OF: R-50385-09674 Value is a big-endian 48-bit
67779       ** twos-complement integer. */
67780       pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
67781       pMem->flags = MEM_Int;
67782       testcase( pMem->u.i<0 );
67783       return 6;
67784     }
67785     case 6:   /* 8-byte signed integer */
67786     case 7: { /* IEEE floating point */
67787       /* These use local variables, so do them in a separate routine
67788       ** to avoid having to move the frame pointer in the common case */
67789       return serialGet(buf,serial_type,pMem);
67790     }
67791     case 8:    /* Integer 0 */
67792     case 9: {  /* Integer 1 */
67793       /* EVIDENCE-OF: R-12976-22893 Value is the integer 0. */
67794       /* EVIDENCE-OF: R-18143-12121 Value is the integer 1. */
67795       pMem->u.i = serial_type-8;
67796       pMem->flags = MEM_Int;
67797       return 0;
67798     }
67799     default: {
67800       /* EVIDENCE-OF: R-14606-31564 Value is a BLOB that is (N-12)/2 bytes in
67801       ** length.
67802       ** EVIDENCE-OF: R-28401-00140 Value is a string in the text encoding and
67803       ** (N-13)/2 bytes in length. */
67804       static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
67805       pMem->z = (char *)buf;
67806       pMem->n = (serial_type-12)/2;
67807       pMem->flags = aFlag[serial_type&1];
67808       return pMem->n;
67809     }
67810   }
67811   return 0;
67812 }
67813 /*
67814 ** This routine is used to allocate sufficient space for an UnpackedRecord
67815 ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
67816 ** the first argument is a pointer to KeyInfo structure pKeyInfo.
67817 **
67818 ** The space is either allocated using sqlite3DbMallocRaw() or from within
67819 ** the unaligned buffer passed via the second and third arguments (presumably
67820 ** stack space). If the former, then *ppFree is set to a pointer that should
67821 ** be eventually freed by the caller using sqlite3DbFree(). Or, if the 
67822 ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
67823 ** before returning.
67824 **
67825 ** If an OOM error occurs, NULL is returned.
67826 */
67827 SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
67828   KeyInfo *pKeyInfo,              /* Description of the record */
67829   char *pSpace,                   /* Unaligned space available */
67830   int szSpace,                    /* Size of pSpace[] in bytes */
67831   char **ppFree                   /* OUT: Caller should free this pointer */
67832 ){
67833   UnpackedRecord *p;              /* Unpacked record to return */
67834   int nOff;                       /* Increment pSpace by nOff to align it */
67835   int nByte;                      /* Number of bytes required for *p */
67836
67837   /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
67838   ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift 
67839   ** it by.  If pSpace is already 8-byte aligned, nOff should be zero.
67840   */
67841   nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
67842   nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
67843   if( nByte>szSpace+nOff ){
67844     p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
67845     *ppFree = (char *)p;
67846     if( !p ) return 0;
67847   }else{
67848     p = (UnpackedRecord*)&pSpace[nOff];
67849     *ppFree = 0;
67850   }
67851
67852   p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
67853   assert( pKeyInfo->aSortOrder!=0 );
67854   p->pKeyInfo = pKeyInfo;
67855   p->nField = pKeyInfo->nField + 1;
67856   return p;
67857 }
67858
67859 /*
67860 ** Given the nKey-byte encoding of a record in pKey[], populate the 
67861 ** UnpackedRecord structure indicated by the fourth argument with the
67862 ** contents of the decoded record.
67863 */ 
67864 SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
67865   KeyInfo *pKeyInfo,     /* Information about the record format */
67866   int nKey,              /* Size of the binary record */
67867   const void *pKey,      /* The binary record */
67868   UnpackedRecord *p      /* Populate this structure before returning. */
67869 ){
67870   const unsigned char *aKey = (const unsigned char *)pKey;
67871   int d; 
67872   u32 idx;                        /* Offset in aKey[] to read from */
67873   u16 u;                          /* Unsigned loop counter */
67874   u32 szHdr;
67875   Mem *pMem = p->aMem;
67876
67877   p->default_rc = 0;
67878   assert( EIGHT_BYTE_ALIGNMENT(pMem) );
67879   idx = getVarint32(aKey, szHdr);
67880   d = szHdr;
67881   u = 0;
67882   while( idx<szHdr && d<=nKey ){
67883     u32 serial_type;
67884
67885     idx += getVarint32(&aKey[idx], serial_type);
67886     pMem->enc = pKeyInfo->enc;
67887     pMem->db = pKeyInfo->db;
67888     /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
67889     pMem->szMalloc = 0;
67890     d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
67891     pMem++;
67892     if( (++u)>=p->nField ) break;
67893   }
67894   assert( u<=pKeyInfo->nField + 1 );
67895   p->nField = u;
67896 }
67897
67898 #if SQLITE_DEBUG
67899 /*
67900 ** This function compares two index or table record keys in the same way
67901 ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
67902 ** this function deserializes and compares values using the
67903 ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
67904 ** in assert() statements to ensure that the optimized code in
67905 ** sqlite3VdbeRecordCompare() returns results with these two primitives.
67906 **
67907 ** Return true if the result of comparison is equivalent to desiredResult.
67908 ** Return false if there is a disagreement.
67909 */
67910 static int vdbeRecordCompareDebug(
67911   int nKey1, const void *pKey1, /* Left key */
67912   const UnpackedRecord *pPKey2, /* Right key */
67913   int desiredResult             /* Correct answer */
67914 ){
67915   u32 d1;            /* Offset into aKey[] of next data element */
67916   u32 idx1;          /* Offset into aKey[] of next header element */
67917   u32 szHdr1;        /* Number of bytes in header */
67918   int i = 0;
67919   int rc = 0;
67920   const unsigned char *aKey1 = (const unsigned char *)pKey1;
67921   KeyInfo *pKeyInfo;
67922   Mem mem1;
67923
67924   pKeyInfo = pPKey2->pKeyInfo;
67925   if( pKeyInfo->db==0 ) return 1;
67926   mem1.enc = pKeyInfo->enc;
67927   mem1.db = pKeyInfo->db;
67928   /* mem1.flags = 0;  // Will be initialized by sqlite3VdbeSerialGet() */
67929   VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
67930
67931   /* Compilers may complain that mem1.u.i is potentially uninitialized.
67932   ** We could initialize it, as shown here, to silence those complaints.
67933   ** But in fact, mem1.u.i will never actually be used uninitialized, and doing 
67934   ** the unnecessary initialization has a measurable negative performance
67935   ** impact, since this routine is a very high runner.  And so, we choose
67936   ** to ignore the compiler warnings and leave this variable uninitialized.
67937   */
67938   /*  mem1.u.i = 0;  // not needed, here to silence compiler warning */
67939   
67940   idx1 = getVarint32(aKey1, szHdr1);
67941   d1 = szHdr1;
67942   assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
67943   assert( pKeyInfo->aSortOrder!=0 );
67944   assert( pKeyInfo->nField>0 );
67945   assert( idx1<=szHdr1 || CORRUPT_DB );
67946   do{
67947     u32 serial_type1;
67948
67949     /* Read the serial types for the next element in each key. */
67950     idx1 += getVarint32( aKey1+idx1, serial_type1 );
67951
67952     /* Verify that there is enough key space remaining to avoid
67953     ** a buffer overread.  The "d1+serial_type1+2" subexpression will
67954     ** always be greater than or equal to the amount of required key space.
67955     ** Use that approximation to avoid the more expensive call to
67956     ** sqlite3VdbeSerialTypeLen() in the common case.
67957     */
67958     if( d1+serial_type1+2>(u32)nKey1
67959      && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1 
67960     ){
67961       break;
67962     }
67963
67964     /* Extract the values to be compared.
67965     */
67966     d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
67967
67968     /* Do the comparison
67969     */
67970     rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
67971     if( rc!=0 ){
67972       assert( mem1.szMalloc==0 );  /* See comment below */
67973       if( pKeyInfo->aSortOrder[i] ){
67974         rc = -rc;  /* Invert the result for DESC sort order. */
67975       }
67976       goto debugCompareEnd;
67977     }
67978     i++;
67979   }while( idx1<szHdr1 && i<pPKey2->nField );
67980
67981   /* No memory allocation is ever used on mem1.  Prove this using
67982   ** the following assert().  If the assert() fails, it indicates a
67983   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
67984   */
67985   assert( mem1.szMalloc==0 );
67986
67987   /* rc==0 here means that one of the keys ran out of fields and
67988   ** all the fields up to that point were equal. Return the default_rc
67989   ** value.  */
67990   rc = pPKey2->default_rc;
67991
67992 debugCompareEnd:
67993   if( desiredResult==0 && rc==0 ) return 1;
67994   if( desiredResult<0 && rc<0 ) return 1;
67995   if( desiredResult>0 && rc>0 ) return 1;
67996   if( CORRUPT_DB ) return 1;
67997   if( pKeyInfo->db->mallocFailed ) return 1;
67998   return 0;
67999 }
68000 #endif
68001
68002 #if SQLITE_DEBUG
68003 /*
68004 ** Count the number of fields (a.k.a. columns) in the record given by
68005 ** pKey,nKey.  The verify that this count is less than or equal to the
68006 ** limit given by pKeyInfo->nField + pKeyInfo->nXField.
68007 **
68008 ** If this constraint is not satisfied, it means that the high-speed
68009 ** vdbeRecordCompareInt() and vdbeRecordCompareString() routines will
68010 ** not work correctly.  If this assert() ever fires, it probably means
68011 ** that the KeyInfo.nField or KeyInfo.nXField values were computed
68012 ** incorrectly.
68013 */
68014 static void vdbeAssertFieldCountWithinLimits(
68015   int nKey, const void *pKey,   /* The record to verify */ 
68016   const KeyInfo *pKeyInfo       /* Compare size with this KeyInfo */
68017 ){
68018   int nField = 0;
68019   u32 szHdr;
68020   u32 idx;
68021   u32 notUsed;
68022   const unsigned char *aKey = (const unsigned char*)pKey;
68023
68024   if( CORRUPT_DB ) return;
68025   idx = getVarint32(aKey, szHdr);
68026   assert( nKey>=0 );
68027   assert( szHdr<=(u32)nKey );
68028   while( idx<szHdr ){
68029     idx += getVarint32(aKey+idx, notUsed);
68030     nField++;
68031   }
68032   assert( nField <= pKeyInfo->nField+pKeyInfo->nXField );
68033 }
68034 #else
68035 # define vdbeAssertFieldCountWithinLimits(A,B,C)
68036 #endif
68037
68038 /*
68039 ** Both *pMem1 and *pMem2 contain string values. Compare the two values
68040 ** using the collation sequence pColl. As usual, return a negative , zero
68041 ** or positive value if *pMem1 is less than, equal to or greater than 
68042 ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
68043 */
68044 static int vdbeCompareMemString(
68045   const Mem *pMem1,
68046   const Mem *pMem2,
68047   const CollSeq *pColl,
68048   u8 *prcErr                      /* If an OOM occurs, set to SQLITE_NOMEM */
68049 ){
68050   if( pMem1->enc==pColl->enc ){
68051     /* The strings are already in the correct encoding.  Call the
68052      ** comparison function directly */
68053     return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
68054   }else{
68055     int rc;
68056     const void *v1, *v2;
68057     int n1, n2;
68058     Mem c1;
68059     Mem c2;
68060     sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
68061     sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
68062     sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
68063     sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
68064     v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
68065     n1 = v1==0 ? 0 : c1.n;
68066     v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
68067     n2 = v2==0 ? 0 : c2.n;
68068     rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
68069     sqlite3VdbeMemRelease(&c1);
68070     sqlite3VdbeMemRelease(&c2);
68071     if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM;
68072     return rc;
68073   }
68074 }
68075
68076 /*
68077 ** Compare two blobs.  Return negative, zero, or positive if the first
68078 ** is less than, equal to, or greater than the second, respectively.
68079 ** If one blob is a prefix of the other, then the shorter is the lessor.
68080 */
68081 static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
68082   int c = memcmp(pB1->z, pB2->z, pB1->n>pB2->n ? pB2->n : pB1->n);
68083   if( c ) return c;
68084   return pB1->n - pB2->n;
68085 }
68086
68087
68088 /*
68089 ** Compare the values contained by the two memory cells, returning
68090 ** negative, zero or positive if pMem1 is less than, equal to, or greater
68091 ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
68092 ** and reals) sorted numerically, followed by text ordered by the collating
68093 ** sequence pColl and finally blob's ordered by memcmp().
68094 **
68095 ** Two NULL values are considered equal by this function.
68096 */
68097 SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
68098   int f1, f2;
68099   int combined_flags;
68100
68101   f1 = pMem1->flags;
68102   f2 = pMem2->flags;
68103   combined_flags = f1|f2;
68104   assert( (combined_flags & MEM_RowSet)==0 );
68105  
68106   /* If one value is NULL, it is less than the other. If both values
68107   ** are NULL, return 0.
68108   */
68109   if( combined_flags&MEM_Null ){
68110     return (f2&MEM_Null) - (f1&MEM_Null);
68111   }
68112
68113   /* If one value is a number and the other is not, the number is less.
68114   ** If both are numbers, compare as reals if one is a real, or as integers
68115   ** if both values are integers.
68116   */
68117   if( combined_flags&(MEM_Int|MEM_Real) ){
68118     double r1, r2;
68119     if( (f1 & f2 & MEM_Int)!=0 ){
68120       if( pMem1->u.i < pMem2->u.i ) return -1;
68121       if( pMem1->u.i > pMem2->u.i ) return 1;
68122       return 0;
68123     }
68124     if( (f1&MEM_Real)!=0 ){
68125       r1 = pMem1->u.r;
68126     }else if( (f1&MEM_Int)!=0 ){
68127       r1 = (double)pMem1->u.i;
68128     }else{
68129       return 1;
68130     }
68131     if( (f2&MEM_Real)!=0 ){
68132       r2 = pMem2->u.r;
68133     }else if( (f2&MEM_Int)!=0 ){
68134       r2 = (double)pMem2->u.i;
68135     }else{
68136       return -1;
68137     }
68138     if( r1<r2 ) return -1;
68139     if( r1>r2 ) return 1;
68140     return 0;
68141   }
68142
68143   /* If one value is a string and the other is a blob, the string is less.
68144   ** If both are strings, compare using the collating functions.
68145   */
68146   if( combined_flags&MEM_Str ){
68147     if( (f1 & MEM_Str)==0 ){
68148       return 1;
68149     }
68150     if( (f2 & MEM_Str)==0 ){
68151       return -1;
68152     }
68153
68154     assert( pMem1->enc==pMem2->enc );
68155     assert( pMem1->enc==SQLITE_UTF8 || 
68156             pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
68157
68158     /* The collation sequence must be defined at this point, even if
68159     ** the user deletes the collation sequence after the vdbe program is
68160     ** compiled (this was not always the case).
68161     */
68162     assert( !pColl || pColl->xCmp );
68163
68164     if( pColl ){
68165       return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
68166     }
68167     /* If a NULL pointer was passed as the collate function, fall through
68168     ** to the blob case and use memcmp().  */
68169   }
68170  
68171   /* Both values must be blobs.  Compare using memcmp().  */
68172   return sqlite3BlobCompare(pMem1, pMem2);
68173 }
68174
68175
68176 /*
68177 ** The first argument passed to this function is a serial-type that
68178 ** corresponds to an integer - all values between 1 and 9 inclusive 
68179 ** except 7. The second points to a buffer containing an integer value
68180 ** serialized according to serial_type. This function deserializes
68181 ** and returns the value.
68182 */
68183 static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
68184   u32 y;
68185   assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
68186   switch( serial_type ){
68187     case 0:
68188     case 1:
68189       testcase( aKey[0]&0x80 );
68190       return ONE_BYTE_INT(aKey);
68191     case 2:
68192       testcase( aKey[0]&0x80 );
68193       return TWO_BYTE_INT(aKey);
68194     case 3:
68195       testcase( aKey[0]&0x80 );
68196       return THREE_BYTE_INT(aKey);
68197     case 4: {
68198       testcase( aKey[0]&0x80 );
68199       y = FOUR_BYTE_UINT(aKey);
68200       return (i64)*(int*)&y;
68201     }
68202     case 5: {
68203       testcase( aKey[0]&0x80 );
68204       return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
68205     }
68206     case 6: {
68207       u64 x = FOUR_BYTE_UINT(aKey);
68208       testcase( aKey[0]&0x80 );
68209       x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
68210       return (i64)*(i64*)&x;
68211     }
68212   }
68213
68214   return (serial_type - 8);
68215 }
68216
68217 /*
68218 ** This function compares the two table rows or index records
68219 ** specified by {nKey1, pKey1} and pPKey2.  It returns a negative, zero
68220 ** or positive integer if key1 is less than, equal to or 
68221 ** greater than key2.  The {nKey1, pKey1} key must be a blob
68222 ** created by the OP_MakeRecord opcode of the VDBE.  The pPKey2
68223 ** key must be a parsed key such as obtained from
68224 ** sqlite3VdbeParseRecord.
68225 **
68226 ** If argument bSkip is non-zero, it is assumed that the caller has already
68227 ** determined that the first fields of the keys are equal.
68228 **
68229 ** Key1 and Key2 do not have to contain the same number of fields. If all 
68230 ** fields that appear in both keys are equal, then pPKey2->default_rc is 
68231 ** returned.
68232 **
68233 ** If database corruption is discovered, set pPKey2->errCode to 
68234 ** SQLITE_CORRUPT and return 0. If an OOM error is encountered, 
68235 ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
68236 ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
68237 */
68238 static int vdbeRecordCompareWithSkip(
68239   int nKey1, const void *pKey1,   /* Left key */
68240   UnpackedRecord *pPKey2,         /* Right key */
68241   int bSkip                       /* If true, skip the first field */
68242 ){
68243   u32 d1;                         /* Offset into aKey[] of next data element */
68244   int i;                          /* Index of next field to compare */
68245   u32 szHdr1;                     /* Size of record header in bytes */
68246   u32 idx1;                       /* Offset of first type in header */
68247   int rc = 0;                     /* Return value */
68248   Mem *pRhs = pPKey2->aMem;       /* Next field of pPKey2 to compare */
68249   KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
68250   const unsigned char *aKey1 = (const unsigned char *)pKey1;
68251   Mem mem1;
68252
68253   /* If bSkip is true, then the caller has already determined that the first
68254   ** two elements in the keys are equal. Fix the various stack variables so
68255   ** that this routine begins comparing at the second field. */
68256   if( bSkip ){
68257     u32 s1;
68258     idx1 = 1 + getVarint32(&aKey1[1], s1);
68259     szHdr1 = aKey1[0];
68260     d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
68261     i = 1;
68262     pRhs++;
68263   }else{
68264     idx1 = getVarint32(aKey1, szHdr1);
68265     d1 = szHdr1;
68266     if( d1>(unsigned)nKey1 ){ 
68267       pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
68268       return 0;  /* Corruption */
68269     }
68270     i = 0;
68271   }
68272
68273   VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
68274   assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField 
68275        || CORRUPT_DB );
68276   assert( pPKey2->pKeyInfo->aSortOrder!=0 );
68277   assert( pPKey2->pKeyInfo->nField>0 );
68278   assert( idx1<=szHdr1 || CORRUPT_DB );
68279   do{
68280     u32 serial_type;
68281
68282     /* RHS is an integer */
68283     if( pRhs->flags & MEM_Int ){
68284       serial_type = aKey1[idx1];
68285       testcase( serial_type==12 );
68286       if( serial_type>=12 ){
68287         rc = +1;
68288       }else if( serial_type==0 ){
68289         rc = -1;
68290       }else if( serial_type==7 ){
68291         double rhs = (double)pRhs->u.i;
68292         sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
68293         if( mem1.u.r<rhs ){
68294           rc = -1;
68295         }else if( mem1.u.r>rhs ){
68296           rc = +1;
68297         }
68298       }else{
68299         i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
68300         i64 rhs = pRhs->u.i;
68301         if( lhs<rhs ){
68302           rc = -1;
68303         }else if( lhs>rhs ){
68304           rc = +1;
68305         }
68306       }
68307     }
68308
68309     /* RHS is real */
68310     else if( pRhs->flags & MEM_Real ){
68311       serial_type = aKey1[idx1];
68312       if( serial_type>=12 ){
68313         rc = +1;
68314       }else if( serial_type==0 ){
68315         rc = -1;
68316       }else{
68317         double rhs = pRhs->u.r;
68318         double lhs;
68319         sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
68320         if( serial_type==7 ){
68321           lhs = mem1.u.r;
68322         }else{
68323           lhs = (double)mem1.u.i;
68324         }
68325         if( lhs<rhs ){
68326           rc = -1;
68327         }else if( lhs>rhs ){
68328           rc = +1;
68329         }
68330       }
68331     }
68332
68333     /* RHS is a string */
68334     else if( pRhs->flags & MEM_Str ){
68335       getVarint32(&aKey1[idx1], serial_type);
68336       testcase( serial_type==12 );
68337       if( serial_type<12 ){
68338         rc = -1;
68339       }else if( !(serial_type & 0x01) ){
68340         rc = +1;
68341       }else{
68342         mem1.n = (serial_type - 12) / 2;
68343         testcase( (d1+mem1.n)==(unsigned)nKey1 );
68344         testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
68345         if( (d1+mem1.n) > (unsigned)nKey1 ){
68346           pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
68347           return 0;                /* Corruption */
68348         }else if( pKeyInfo->aColl[i] ){
68349           mem1.enc = pKeyInfo->enc;
68350           mem1.db = pKeyInfo->db;
68351           mem1.flags = MEM_Str;
68352           mem1.z = (char*)&aKey1[d1];
68353           rc = vdbeCompareMemString(
68354               &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
68355           );
68356         }else{
68357           int nCmp = MIN(mem1.n, pRhs->n);
68358           rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
68359           if( rc==0 ) rc = mem1.n - pRhs->n; 
68360         }
68361       }
68362     }
68363
68364     /* RHS is a blob */
68365     else if( pRhs->flags & MEM_Blob ){
68366       getVarint32(&aKey1[idx1], serial_type);
68367       testcase( serial_type==12 );
68368       if( serial_type<12 || (serial_type & 0x01) ){
68369         rc = -1;
68370       }else{
68371         int nStr = (serial_type - 12) / 2;
68372         testcase( (d1+nStr)==(unsigned)nKey1 );
68373         testcase( (d1+nStr+1)==(unsigned)nKey1 );
68374         if( (d1+nStr) > (unsigned)nKey1 ){
68375           pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
68376           return 0;                /* Corruption */
68377         }else{
68378           int nCmp = MIN(nStr, pRhs->n);
68379           rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
68380           if( rc==0 ) rc = nStr - pRhs->n;
68381         }
68382       }
68383     }
68384
68385     /* RHS is null */
68386     else{
68387       serial_type = aKey1[idx1];
68388       rc = (serial_type!=0);
68389     }
68390
68391     if( rc!=0 ){
68392       if( pKeyInfo->aSortOrder[i] ){
68393         rc = -rc;
68394       }
68395       assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
68396       assert( mem1.szMalloc==0 );  /* See comment below */
68397       return rc;
68398     }
68399
68400     i++;
68401     pRhs++;
68402     d1 += sqlite3VdbeSerialTypeLen(serial_type);
68403     idx1 += sqlite3VarintLen(serial_type);
68404   }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
68405
68406   /* No memory allocation is ever used on mem1.  Prove this using
68407   ** the following assert().  If the assert() fails, it indicates a
68408   ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).  */
68409   assert( mem1.szMalloc==0 );
68410
68411   /* rc==0 here means that one or both of the keys ran out of fields and
68412   ** all the fields up to that point were equal. Return the default_rc
68413   ** value.  */
68414   assert( CORRUPT_DB 
68415        || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc) 
68416        || pKeyInfo->db->mallocFailed
68417   );
68418   return pPKey2->default_rc;
68419 }
68420 SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
68421   int nKey1, const void *pKey1,   /* Left key */
68422   UnpackedRecord *pPKey2          /* Right key */
68423 ){
68424   return vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
68425 }
68426
68427
68428 /*
68429 ** This function is an optimized version of sqlite3VdbeRecordCompare() 
68430 ** that (a) the first field of pPKey2 is an integer, and (b) the 
68431 ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
68432 ** byte (i.e. is less than 128).
68433 **
68434 ** To avoid concerns about buffer overreads, this routine is only used
68435 ** on schemas where the maximum valid header size is 63 bytes or less.
68436 */
68437 static int vdbeRecordCompareInt(
68438   int nKey1, const void *pKey1, /* Left key */
68439   UnpackedRecord *pPKey2        /* Right key */
68440 ){
68441   const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
68442   int serial_type = ((const u8*)pKey1)[1];
68443   int res;
68444   u32 y;
68445   u64 x;
68446   i64 v = pPKey2->aMem[0].u.i;
68447   i64 lhs;
68448
68449   vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
68450   assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
68451   switch( serial_type ){
68452     case 1: { /* 1-byte signed integer */
68453       lhs = ONE_BYTE_INT(aKey);
68454       testcase( lhs<0 );
68455       break;
68456     }
68457     case 2: { /* 2-byte signed integer */
68458       lhs = TWO_BYTE_INT(aKey);
68459       testcase( lhs<0 );
68460       break;
68461     }
68462     case 3: { /* 3-byte signed integer */
68463       lhs = THREE_BYTE_INT(aKey);
68464       testcase( lhs<0 );
68465       break;
68466     }
68467     case 4: { /* 4-byte signed integer */
68468       y = FOUR_BYTE_UINT(aKey);
68469       lhs = (i64)*(int*)&y;
68470       testcase( lhs<0 );
68471       break;
68472     }
68473     case 5: { /* 6-byte signed integer */
68474       lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
68475       testcase( lhs<0 );
68476       break;
68477     }
68478     case 6: { /* 8-byte signed integer */
68479       x = FOUR_BYTE_UINT(aKey);
68480       x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
68481       lhs = *(i64*)&x;
68482       testcase( lhs<0 );
68483       break;
68484     }
68485     case 8: 
68486       lhs = 0;
68487       break;
68488     case 9:
68489       lhs = 1;
68490       break;
68491
68492     /* This case could be removed without changing the results of running
68493     ** this code. Including it causes gcc to generate a faster switch 
68494     ** statement (since the range of switch targets now starts at zero and
68495     ** is contiguous) but does not cause any duplicate code to be generated
68496     ** (as gcc is clever enough to combine the two like cases). Other 
68497     ** compilers might be similar.  */ 
68498     case 0: case 7:
68499       return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
68500
68501     default:
68502       return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
68503   }
68504
68505   if( v>lhs ){
68506     res = pPKey2->r1;
68507   }else if( v<lhs ){
68508     res = pPKey2->r2;
68509   }else if( pPKey2->nField>1 ){
68510     /* The first fields of the two keys are equal. Compare the trailing 
68511     ** fields.  */
68512     res = vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
68513   }else{
68514     /* The first fields of the two keys are equal and there are no trailing
68515     ** fields. Return pPKey2->default_rc in this case. */
68516     res = pPKey2->default_rc;
68517   }
68518
68519   assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
68520   return res;
68521 }
68522
68523 /*
68524 ** This function is an optimized version of sqlite3VdbeRecordCompare() 
68525 ** that (a) the first field of pPKey2 is a string, that (b) the first field
68526 ** uses the collation sequence BINARY and (c) that the size-of-header varint 
68527 ** at the start of (pKey1/nKey1) fits in a single byte.
68528 */
68529 static int vdbeRecordCompareString(
68530   int nKey1, const void *pKey1, /* Left key */
68531   UnpackedRecord *pPKey2        /* Right key */
68532 ){
68533   const u8 *aKey1 = (const u8*)pKey1;
68534   int serial_type;
68535   int res;
68536
68537   vdbeAssertFieldCountWithinLimits(nKey1, pKey1, pPKey2->pKeyInfo);
68538   getVarint32(&aKey1[1], serial_type);
68539   if( serial_type<12 ){
68540     res = pPKey2->r1;      /* (pKey1/nKey1) is a number or a null */
68541   }else if( !(serial_type & 0x01) ){ 
68542     res = pPKey2->r2;      /* (pKey1/nKey1) is a blob */
68543   }else{
68544     int nCmp;
68545     int nStr;
68546     int szHdr = aKey1[0];
68547
68548     nStr = (serial_type-12) / 2;
68549     if( (szHdr + nStr) > nKey1 ){
68550       pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
68551       return 0;    /* Corruption */
68552     }
68553     nCmp = MIN( pPKey2->aMem[0].n, nStr );
68554     res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
68555
68556     if( res==0 ){
68557       res = nStr - pPKey2->aMem[0].n;
68558       if( res==0 ){
68559         if( pPKey2->nField>1 ){
68560           res = vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
68561         }else{
68562           res = pPKey2->default_rc;
68563         }
68564       }else if( res>0 ){
68565         res = pPKey2->r2;
68566       }else{
68567         res = pPKey2->r1;
68568       }
68569     }else if( res>0 ){
68570       res = pPKey2->r2;
68571     }else{
68572       res = pPKey2->r1;
68573     }
68574   }
68575
68576   assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
68577        || CORRUPT_DB
68578        || pPKey2->pKeyInfo->db->mallocFailed
68579   );
68580   return res;
68581 }
68582
68583 /*
68584 ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
68585 ** suitable for comparing serialized records to the unpacked record passed
68586 ** as the only argument.
68587 */
68588 SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
68589   /* varintRecordCompareInt() and varintRecordCompareString() both assume
68590   ** that the size-of-header varint that occurs at the start of each record
68591   ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
68592   ** also assumes that it is safe to overread a buffer by at least the 
68593   ** maximum possible legal header size plus 8 bytes. Because there is
68594   ** guaranteed to be at least 74 (but not 136) bytes of padding following each
68595   ** buffer passed to varintRecordCompareInt() this makes it convenient to
68596   ** limit the size of the header to 64 bytes in cases where the first field
68597   ** is an integer.
68598   **
68599   ** The easiest way to enforce this limit is to consider only records with
68600   ** 13 fields or less. If the first field is an integer, the maximum legal
68601   ** header size is (12*5 + 1 + 1) bytes.  */
68602   if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
68603     int flags = p->aMem[0].flags;
68604     if( p->pKeyInfo->aSortOrder[0] ){
68605       p->r1 = 1;
68606       p->r2 = -1;
68607     }else{
68608       p->r1 = -1;
68609       p->r2 = 1;
68610     }
68611     if( (flags & MEM_Int) ){
68612       return vdbeRecordCompareInt;
68613     }
68614     testcase( flags & MEM_Real );
68615     testcase( flags & MEM_Null );
68616     testcase( flags & MEM_Blob );
68617     if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
68618       assert( flags & MEM_Str );
68619       return vdbeRecordCompareString;
68620     }
68621   }
68622
68623   return sqlite3VdbeRecordCompare;
68624 }
68625
68626 /*
68627 ** pCur points at an index entry created using the OP_MakeRecord opcode.
68628 ** Read the rowid (the last field in the record) and store it in *rowid.
68629 ** Return SQLITE_OK if everything works, or an error code otherwise.
68630 **
68631 ** pCur might be pointing to text obtained from a corrupt database file.
68632 ** So the content cannot be trusted.  Do appropriate checks on the content.
68633 */
68634 SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
68635   i64 nCellKey = 0;
68636   int rc;
68637   u32 szHdr;        /* Size of the header */
68638   u32 typeRowid;    /* Serial type of the rowid */
68639   u32 lenRowid;     /* Size of the rowid */
68640   Mem m, v;
68641
68642   /* Get the size of the index entry.  Only indices entries of less
68643   ** than 2GiB are support - anything large must be database corruption.
68644   ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
68645   ** this code can safely assume that nCellKey is 32-bits  
68646   */
68647   assert( sqlite3BtreeCursorIsValid(pCur) );
68648   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
68649   assert( rc==SQLITE_OK );     /* pCur is always valid so KeySize cannot fail */
68650   assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
68651
68652   /* Read in the complete content of the index entry */
68653   sqlite3VdbeMemInit(&m, db, 0);
68654   rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
68655   if( rc ){
68656     return rc;
68657   }
68658
68659   /* The index entry must begin with a header size */
68660   (void)getVarint32((u8*)m.z, szHdr);
68661   testcase( szHdr==3 );
68662   testcase( szHdr==m.n );
68663   if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
68664     goto idx_rowid_corruption;
68665   }
68666
68667   /* The last field of the index should be an integer - the ROWID.
68668   ** Verify that the last entry really is an integer. */
68669   (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
68670   testcase( typeRowid==1 );
68671   testcase( typeRowid==2 );
68672   testcase( typeRowid==3 );
68673   testcase( typeRowid==4 );
68674   testcase( typeRowid==5 );
68675   testcase( typeRowid==6 );
68676   testcase( typeRowid==8 );
68677   testcase( typeRowid==9 );
68678   if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
68679     goto idx_rowid_corruption;
68680   }
68681   lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
68682   testcase( (u32)m.n==szHdr+lenRowid );
68683   if( unlikely((u32)m.n<szHdr+lenRowid) ){
68684     goto idx_rowid_corruption;
68685   }
68686
68687   /* Fetch the integer off the end of the index record */
68688   sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
68689   *rowid = v.u.i;
68690   sqlite3VdbeMemRelease(&m);
68691   return SQLITE_OK;
68692
68693   /* Jump here if database corruption is detected after m has been
68694   ** allocated.  Free the m object and return SQLITE_CORRUPT. */
68695 idx_rowid_corruption:
68696   testcase( m.szMalloc!=0 );
68697   sqlite3VdbeMemRelease(&m);
68698   return SQLITE_CORRUPT_BKPT;
68699 }
68700
68701 /*
68702 ** Compare the key of the index entry that cursor pC is pointing to against
68703 ** the key string in pUnpacked.  Write into *pRes a number
68704 ** that is negative, zero, or positive if pC is less than, equal to,
68705 ** or greater than pUnpacked.  Return SQLITE_OK on success.
68706 **
68707 ** pUnpacked is either created without a rowid or is truncated so that it
68708 ** omits the rowid at the end.  The rowid at the end of the index entry
68709 ** is ignored as well.  Hence, this routine only compares the prefixes 
68710 ** of the keys prior to the final rowid, not the entire key.
68711 */
68712 SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
68713   sqlite3 *db,                     /* Database connection */
68714   VdbeCursor *pC,                  /* The cursor to compare against */
68715   UnpackedRecord *pUnpacked,       /* Unpacked version of key */
68716   int *res                         /* Write the comparison result here */
68717 ){
68718   i64 nCellKey = 0;
68719   int rc;
68720   BtCursor *pCur = pC->pCursor;
68721   Mem m;
68722
68723   assert( sqlite3BtreeCursorIsValid(pCur) );
68724   VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
68725   assert( rc==SQLITE_OK );    /* pCur is always valid so KeySize cannot fail */
68726   /* nCellKey will always be between 0 and 0xffffffff because of the way
68727   ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
68728   if( nCellKey<=0 || nCellKey>0x7fffffff ){
68729     *res = 0;
68730     return SQLITE_CORRUPT_BKPT;
68731   }
68732   sqlite3VdbeMemInit(&m, db, 0);
68733   rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (u32)nCellKey, 1, &m);
68734   if( rc ){
68735     return rc;
68736   }
68737   *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
68738   sqlite3VdbeMemRelease(&m);
68739   return SQLITE_OK;
68740 }
68741
68742 /*
68743 ** This routine sets the value to be returned by subsequent calls to
68744 ** sqlite3_changes() on the database handle 'db'. 
68745 */
68746 SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
68747   assert( sqlite3_mutex_held(db->mutex) );
68748   db->nChange = nChange;
68749   db->nTotalChange += nChange;
68750 }
68751
68752 /*
68753 ** Set a flag in the vdbe to update the change counter when it is finalised
68754 ** or reset.
68755 */
68756 SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
68757   v->changeCntOn = 1;
68758 }
68759
68760 /*
68761 ** Mark every prepared statement associated with a database connection
68762 ** as expired.
68763 **
68764 ** An expired statement means that recompilation of the statement is
68765 ** recommend.  Statements expire when things happen that make their
68766 ** programs obsolete.  Removing user-defined functions or collating
68767 ** sequences, or changing an authorization function are the types of
68768 ** things that make prepared statements obsolete.
68769 */
68770 SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
68771   Vdbe *p;
68772   for(p = db->pVdbe; p; p=p->pNext){
68773     p->expired = 1;
68774   }
68775 }
68776
68777 /*
68778 ** Return the database associated with the Vdbe.
68779 */
68780 SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
68781   return v->db;
68782 }
68783
68784 /*
68785 ** Return a pointer to an sqlite3_value structure containing the value bound
68786 ** parameter iVar of VM v. Except, if the value is an SQL NULL, return 
68787 ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
68788 ** constants) to the value before returning it.
68789 **
68790 ** The returned value must be freed by the caller using sqlite3ValueFree().
68791 */
68792 SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
68793   assert( iVar>0 );
68794   if( v ){
68795     Mem *pMem = &v->aVar[iVar-1];
68796     if( 0==(pMem->flags & MEM_Null) ){
68797       sqlite3_value *pRet = sqlite3ValueNew(v->db);
68798       if( pRet ){
68799         sqlite3VdbeMemCopy((Mem *)pRet, pMem);
68800         sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
68801       }
68802       return pRet;
68803     }
68804   }
68805   return 0;
68806 }
68807
68808 /*
68809 ** Configure SQL variable iVar so that binding a new value to it signals
68810 ** to sqlite3_reoptimize() that re-preparing the statement may result
68811 ** in a better query plan.
68812 */
68813 SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
68814   assert( iVar>0 );
68815   if( iVar>32 ){
68816     v->expmask = 0xffffffff;
68817   }else{
68818     v->expmask |= ((u32)1 << (iVar-1));
68819   }
68820 }
68821
68822 #ifndef SQLITE_OMIT_VIRTUALTABLE
68823 /*
68824 ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
68825 ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
68826 ** in memory obtained from sqlite3DbMalloc).
68827 */
68828 SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
68829   sqlite3 *db = p->db;
68830   sqlite3DbFree(db, p->zErrMsg);
68831   p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
68832   sqlite3_free(pVtab->zErrMsg);
68833   pVtab->zErrMsg = 0;
68834 }
68835 #endif /* SQLITE_OMIT_VIRTUALTABLE */
68836
68837 /************** End of vdbeaux.c *********************************************/
68838 /************** Begin file vdbeapi.c *****************************************/
68839 /*
68840 ** 2004 May 26
68841 **
68842 ** The author disclaims copyright to this source code.  In place of
68843 ** a legal notice, here is a blessing:
68844 **
68845 **    May you do good and not evil.
68846 **    May you find forgiveness for yourself and forgive others.
68847 **    May you share freely, never taking more than you give.
68848 **
68849 *************************************************************************
68850 **
68851 ** This file contains code use to implement APIs that are part of the
68852 ** VDBE.
68853 */
68854
68855 #ifndef SQLITE_OMIT_DEPRECATED
68856 /*
68857 ** Return TRUE (non-zero) of the statement supplied as an argument needs
68858 ** to be recompiled.  A statement needs to be recompiled whenever the
68859 ** execution environment changes in a way that would alter the program
68860 ** that sqlite3_prepare() generates.  For example, if new functions or
68861 ** collating sequences are registered or if an authorizer function is
68862 ** added or changed.
68863 */
68864 SQLITE_API int SQLITE_STDCALL sqlite3_expired(sqlite3_stmt *pStmt){
68865   Vdbe *p = (Vdbe*)pStmt;
68866   return p==0 || p->expired;
68867 }
68868 #endif
68869
68870 /*
68871 ** Check on a Vdbe to make sure it has not been finalized.  Log
68872 ** an error and return true if it has been finalized (or is otherwise
68873 ** invalid).  Return false if it is ok.
68874 */
68875 static int vdbeSafety(Vdbe *p){
68876   if( p->db==0 ){
68877     sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
68878     return 1;
68879   }else{
68880     return 0;
68881   }
68882 }
68883 static int vdbeSafetyNotNull(Vdbe *p){
68884   if( p==0 ){
68885     sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
68886     return 1;
68887   }else{
68888     return vdbeSafety(p);
68889   }
68890 }
68891
68892 /*
68893 ** The following routine destroys a virtual machine that is created by
68894 ** the sqlite3_compile() routine. The integer returned is an SQLITE_
68895 ** success/failure code that describes the result of executing the virtual
68896 ** machine.
68897 **
68898 ** This routine sets the error code and string returned by
68899 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
68900 */
68901 SQLITE_API int SQLITE_STDCALL sqlite3_finalize(sqlite3_stmt *pStmt){
68902   int rc;
68903   if( pStmt==0 ){
68904     /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
68905     ** pointer is a harmless no-op. */
68906     rc = SQLITE_OK;
68907   }else{
68908     Vdbe *v = (Vdbe*)pStmt;
68909     sqlite3 *db = v->db;
68910     if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
68911     sqlite3_mutex_enter(db->mutex);
68912     rc = sqlite3VdbeFinalize(v);
68913     rc = sqlite3ApiExit(db, rc);
68914     sqlite3LeaveMutexAndCloseZombie(db);
68915   }
68916   return rc;
68917 }
68918
68919 /*
68920 ** Terminate the current execution of an SQL statement and reset it
68921 ** back to its starting state so that it can be reused. A success code from
68922 ** the prior execution is returned.
68923 **
68924 ** This routine sets the error code and string returned by
68925 ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
68926 */
68927 SQLITE_API int SQLITE_STDCALL sqlite3_reset(sqlite3_stmt *pStmt){
68928   int rc;
68929   if( pStmt==0 ){
68930     rc = SQLITE_OK;
68931   }else{
68932     Vdbe *v = (Vdbe*)pStmt;
68933     sqlite3_mutex_enter(v->db->mutex);
68934     rc = sqlite3VdbeReset(v);
68935     sqlite3VdbeRewind(v);
68936     assert( (rc & (v->db->errMask))==rc );
68937     rc = sqlite3ApiExit(v->db, rc);
68938     sqlite3_mutex_leave(v->db->mutex);
68939   }
68940   return rc;
68941 }
68942
68943 /*
68944 ** Set all the parameters in the compiled SQL statement to NULL.
68945 */
68946 SQLITE_API int SQLITE_STDCALL sqlite3_clear_bindings(sqlite3_stmt *pStmt){
68947   int i;
68948   int rc = SQLITE_OK;
68949   Vdbe *p = (Vdbe*)pStmt;
68950 #if SQLITE_THREADSAFE
68951   sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
68952 #endif
68953   sqlite3_mutex_enter(mutex);
68954   for(i=0; i<p->nVar; i++){
68955     sqlite3VdbeMemRelease(&p->aVar[i]);
68956     p->aVar[i].flags = MEM_Null;
68957   }
68958   if( p->isPrepareV2 && p->expmask ){
68959     p->expired = 1;
68960   }
68961   sqlite3_mutex_leave(mutex);
68962   return rc;
68963 }
68964
68965
68966 /**************************** sqlite3_value_  *******************************
68967 ** The following routines extract information from a Mem or sqlite3_value
68968 ** structure.
68969 */
68970 SQLITE_API const void *SQLITE_STDCALL sqlite3_value_blob(sqlite3_value *pVal){
68971   Mem *p = (Mem*)pVal;
68972   if( p->flags & (MEM_Blob|MEM_Str) ){
68973     sqlite3VdbeMemExpandBlob(p);
68974     p->flags |= MEM_Blob;
68975     return p->n ? p->z : 0;
68976   }else{
68977     return sqlite3_value_text(pVal);
68978   }
68979 }
68980 SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes(sqlite3_value *pVal){
68981   return sqlite3ValueBytes(pVal, SQLITE_UTF8);
68982 }
68983 SQLITE_API int SQLITE_STDCALL sqlite3_value_bytes16(sqlite3_value *pVal){
68984   return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
68985 }
68986 SQLITE_API double SQLITE_STDCALL sqlite3_value_double(sqlite3_value *pVal){
68987   return sqlite3VdbeRealValue((Mem*)pVal);
68988 }
68989 SQLITE_API int SQLITE_STDCALL sqlite3_value_int(sqlite3_value *pVal){
68990   return (int)sqlite3VdbeIntValue((Mem*)pVal);
68991 }
68992 SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_value_int64(sqlite3_value *pVal){
68993   return sqlite3VdbeIntValue((Mem*)pVal);
68994 }
68995 SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_value_text(sqlite3_value *pVal){
68996   return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
68997 }
68998 #ifndef SQLITE_OMIT_UTF16
68999 SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16(sqlite3_value* pVal){
69000   return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
69001 }
69002 SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16be(sqlite3_value *pVal){
69003   return sqlite3ValueText(pVal, SQLITE_UTF16BE);
69004 }
69005 SQLITE_API const void *SQLITE_STDCALL sqlite3_value_text16le(sqlite3_value *pVal){
69006   return sqlite3ValueText(pVal, SQLITE_UTF16LE);
69007 }
69008 #endif /* SQLITE_OMIT_UTF16 */
69009 /* EVIDENCE-OF: R-12793-43283 Every value in SQLite has one of five
69010 ** fundamental datatypes: 64-bit signed integer 64-bit IEEE floating
69011 ** point number string BLOB NULL
69012 */
69013 SQLITE_API int SQLITE_STDCALL sqlite3_value_type(sqlite3_value* pVal){
69014   static const u8 aType[] = {
69015      SQLITE_BLOB,     /* 0x00 */
69016      SQLITE_NULL,     /* 0x01 */
69017      SQLITE_TEXT,     /* 0x02 */
69018      SQLITE_NULL,     /* 0x03 */
69019      SQLITE_INTEGER,  /* 0x04 */
69020      SQLITE_NULL,     /* 0x05 */
69021      SQLITE_INTEGER,  /* 0x06 */
69022      SQLITE_NULL,     /* 0x07 */
69023      SQLITE_FLOAT,    /* 0x08 */
69024      SQLITE_NULL,     /* 0x09 */
69025      SQLITE_FLOAT,    /* 0x0a */
69026      SQLITE_NULL,     /* 0x0b */
69027      SQLITE_INTEGER,  /* 0x0c */
69028      SQLITE_NULL,     /* 0x0d */
69029      SQLITE_INTEGER,  /* 0x0e */
69030      SQLITE_NULL,     /* 0x0f */
69031      SQLITE_BLOB,     /* 0x10 */
69032      SQLITE_NULL,     /* 0x11 */
69033      SQLITE_TEXT,     /* 0x12 */
69034      SQLITE_NULL,     /* 0x13 */
69035      SQLITE_INTEGER,  /* 0x14 */
69036      SQLITE_NULL,     /* 0x15 */
69037      SQLITE_INTEGER,  /* 0x16 */
69038      SQLITE_NULL,     /* 0x17 */
69039      SQLITE_FLOAT,    /* 0x18 */
69040      SQLITE_NULL,     /* 0x19 */
69041      SQLITE_FLOAT,    /* 0x1a */
69042      SQLITE_NULL,     /* 0x1b */
69043      SQLITE_INTEGER,  /* 0x1c */
69044      SQLITE_NULL,     /* 0x1d */
69045      SQLITE_INTEGER,  /* 0x1e */
69046      SQLITE_NULL,     /* 0x1f */
69047   };
69048   return aType[pVal->flags&MEM_AffMask];
69049 }
69050
69051 /**************************** sqlite3_result_  *******************************
69052 ** The following routines are used by user-defined functions to specify
69053 ** the function result.
69054 **
69055 ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
69056 ** result as a string or blob but if the string or blob is too large, it
69057 ** then sets the error code to SQLITE_TOOBIG
69058 **
69059 ** The invokeValueDestructor(P,X) routine invokes destructor function X()
69060 ** on value P is not going to be used and need to be destroyed.
69061 */
69062 static void setResultStrOrError(
69063   sqlite3_context *pCtx,  /* Function context */
69064   const char *z,          /* String pointer */
69065   int n,                  /* Bytes in string, or negative */
69066   u8 enc,                 /* Encoding of z.  0 for BLOBs */
69067   void (*xDel)(void*)     /* Destructor function */
69068 ){
69069   if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
69070     sqlite3_result_error_toobig(pCtx);
69071   }
69072 }
69073 static int invokeValueDestructor(
69074   const void *p,             /* Value to destroy */
69075   void (*xDel)(void*),       /* The destructor */
69076   sqlite3_context *pCtx      /* Set a SQLITE_TOOBIG error if no NULL */
69077 ){
69078   assert( xDel!=SQLITE_DYNAMIC );
69079   if( xDel==0 ){
69080     /* noop */
69081   }else if( xDel==SQLITE_TRANSIENT ){
69082     /* noop */
69083   }else{
69084     xDel((void*)p);
69085   }
69086   if( pCtx ) sqlite3_result_error_toobig(pCtx);
69087   return SQLITE_TOOBIG;
69088 }
69089 SQLITE_API void SQLITE_STDCALL sqlite3_result_blob(
69090   sqlite3_context *pCtx, 
69091   const void *z, 
69092   int n, 
69093   void (*xDel)(void *)
69094 ){
69095   assert( n>=0 );
69096   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69097   setResultStrOrError(pCtx, z, n, 0, xDel);
69098 }
69099 SQLITE_API void SQLITE_STDCALL sqlite3_result_blob64(
69100   sqlite3_context *pCtx, 
69101   const void *z, 
69102   sqlite3_uint64 n,
69103   void (*xDel)(void *)
69104 ){
69105   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69106   assert( xDel!=SQLITE_DYNAMIC );
69107   if( n>0x7fffffff ){
69108     (void)invokeValueDestructor(z, xDel, pCtx);
69109   }else{
69110     setResultStrOrError(pCtx, z, (int)n, 0, xDel);
69111   }
69112 }
69113 SQLITE_API void SQLITE_STDCALL sqlite3_result_double(sqlite3_context *pCtx, double rVal){
69114   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69115   sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
69116 }
69117 SQLITE_API void SQLITE_STDCALL sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
69118   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69119   pCtx->isError = SQLITE_ERROR;
69120   pCtx->fErrorOrAux = 1;
69121   sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
69122 }
69123 #ifndef SQLITE_OMIT_UTF16
69124 SQLITE_API void SQLITE_STDCALL sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
69125   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69126   pCtx->isError = SQLITE_ERROR;
69127   pCtx->fErrorOrAux = 1;
69128   sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
69129 }
69130 #endif
69131 SQLITE_API void SQLITE_STDCALL sqlite3_result_int(sqlite3_context *pCtx, int iVal){
69132   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69133   sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
69134 }
69135 SQLITE_API void SQLITE_STDCALL sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
69136   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69137   sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
69138 }
69139 SQLITE_API void SQLITE_STDCALL sqlite3_result_null(sqlite3_context *pCtx){
69140   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69141   sqlite3VdbeMemSetNull(pCtx->pOut);
69142 }
69143 SQLITE_API void SQLITE_STDCALL sqlite3_result_text(
69144   sqlite3_context *pCtx, 
69145   const char *z, 
69146   int n,
69147   void (*xDel)(void *)
69148 ){
69149   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69150   setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
69151 }
69152 SQLITE_API void SQLITE_STDCALL sqlite3_result_text64(
69153   sqlite3_context *pCtx, 
69154   const char *z, 
69155   sqlite3_uint64 n,
69156   void (*xDel)(void *),
69157   unsigned char enc
69158 ){
69159   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69160   assert( xDel!=SQLITE_DYNAMIC );
69161   if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
69162   if( n>0x7fffffff ){
69163     (void)invokeValueDestructor(z, xDel, pCtx);
69164   }else{
69165     setResultStrOrError(pCtx, z, (int)n, enc, xDel);
69166   }
69167 }
69168 #ifndef SQLITE_OMIT_UTF16
69169 SQLITE_API void SQLITE_STDCALL sqlite3_result_text16(
69170   sqlite3_context *pCtx, 
69171   const void *z, 
69172   int n, 
69173   void (*xDel)(void *)
69174 ){
69175   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69176   setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
69177 }
69178 SQLITE_API void SQLITE_STDCALL sqlite3_result_text16be(
69179   sqlite3_context *pCtx, 
69180   const void *z, 
69181   int n, 
69182   void (*xDel)(void *)
69183 ){
69184   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69185   setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
69186 }
69187 SQLITE_API void SQLITE_STDCALL sqlite3_result_text16le(
69188   sqlite3_context *pCtx, 
69189   const void *z, 
69190   int n, 
69191   void (*xDel)(void *)
69192 ){
69193   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69194   setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
69195 }
69196 #endif /* SQLITE_OMIT_UTF16 */
69197 SQLITE_API void SQLITE_STDCALL sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
69198   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69199   sqlite3VdbeMemCopy(pCtx->pOut, pValue);
69200 }
69201 SQLITE_API void SQLITE_STDCALL sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
69202   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69203   sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
69204 }
69205 SQLITE_API void SQLITE_STDCALL sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
69206   pCtx->isError = errCode;
69207   pCtx->fErrorOrAux = 1;
69208 #ifdef SQLITE_DEBUG
69209   if( pCtx->pVdbe ) pCtx->pVdbe->rcApp = errCode;
69210 #endif
69211   if( pCtx->pOut->flags & MEM_Null ){
69212     sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1, 
69213                          SQLITE_UTF8, SQLITE_STATIC);
69214   }
69215 }
69216
69217 /* Force an SQLITE_TOOBIG error. */
69218 SQLITE_API void SQLITE_STDCALL sqlite3_result_error_toobig(sqlite3_context *pCtx){
69219   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69220   pCtx->isError = SQLITE_TOOBIG;
69221   pCtx->fErrorOrAux = 1;
69222   sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1, 
69223                        SQLITE_UTF8, SQLITE_STATIC);
69224 }
69225
69226 /* An SQLITE_NOMEM error. */
69227 SQLITE_API void SQLITE_STDCALL sqlite3_result_error_nomem(sqlite3_context *pCtx){
69228   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69229   sqlite3VdbeMemSetNull(pCtx->pOut);
69230   pCtx->isError = SQLITE_NOMEM;
69231   pCtx->fErrorOrAux = 1;
69232   pCtx->pOut->db->mallocFailed = 1;
69233 }
69234
69235 /*
69236 ** This function is called after a transaction has been committed. It 
69237 ** invokes callbacks registered with sqlite3_wal_hook() as required.
69238 */
69239 static int doWalCallbacks(sqlite3 *db){
69240   int rc = SQLITE_OK;
69241 #ifndef SQLITE_OMIT_WAL
69242   int i;
69243   for(i=0; i<db->nDb; i++){
69244     Btree *pBt = db->aDb[i].pBt;
69245     if( pBt ){
69246       int nEntry;
69247       sqlite3BtreeEnter(pBt);
69248       nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
69249       sqlite3BtreeLeave(pBt);
69250       if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
69251         rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
69252       }
69253     }
69254   }
69255 #endif
69256   return rc;
69257 }
69258
69259 /*
69260 ** Execute the statement pStmt, either until a row of data is ready, the
69261 ** statement is completely executed or an error occurs.
69262 **
69263 ** This routine implements the bulk of the logic behind the sqlite_step()
69264 ** API.  The only thing omitted is the automatic recompile if a 
69265 ** schema change has occurred.  That detail is handled by the
69266 ** outer sqlite3_step() wrapper procedure.
69267 */
69268 static int sqlite3Step(Vdbe *p){
69269   sqlite3 *db;
69270   int rc;
69271
69272   assert(p);
69273   if( p->magic!=VDBE_MAGIC_RUN ){
69274     /* We used to require that sqlite3_reset() be called before retrying
69275     ** sqlite3_step() after any error or after SQLITE_DONE.  But beginning
69276     ** with version 3.7.0, we changed this so that sqlite3_reset() would
69277     ** be called automatically instead of throwing the SQLITE_MISUSE error.
69278     ** This "automatic-reset" change is not technically an incompatibility, 
69279     ** since any application that receives an SQLITE_MISUSE is broken by
69280     ** definition.
69281     **
69282     ** Nevertheless, some published applications that were originally written
69283     ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE 
69284     ** returns, and those were broken by the automatic-reset change.  As a
69285     ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
69286     ** legacy behavior of returning SQLITE_MISUSE for cases where the 
69287     ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
69288     ** or SQLITE_BUSY error.
69289     */
69290 #ifdef SQLITE_OMIT_AUTORESET
69291     if( (rc = p->rc&0xff)==SQLITE_BUSY || rc==SQLITE_LOCKED ){
69292       sqlite3_reset((sqlite3_stmt*)p);
69293     }else{
69294       return SQLITE_MISUSE_BKPT;
69295     }
69296 #else
69297     sqlite3_reset((sqlite3_stmt*)p);
69298 #endif
69299   }
69300
69301   /* Check that malloc() has not failed. If it has, return early. */
69302   db = p->db;
69303   if( db->mallocFailed ){
69304     p->rc = SQLITE_NOMEM;
69305     return SQLITE_NOMEM;
69306   }
69307
69308   if( p->pc<=0 && p->expired ){
69309     p->rc = SQLITE_SCHEMA;
69310     rc = SQLITE_ERROR;
69311     goto end_of_step;
69312   }
69313   if( p->pc<0 ){
69314     /* If there are no other statements currently running, then
69315     ** reset the interrupt flag.  This prevents a call to sqlite3_interrupt
69316     ** from interrupting a statement that has not yet started.
69317     */
69318     if( db->nVdbeActive==0 ){
69319       db->u1.isInterrupted = 0;
69320     }
69321
69322     assert( db->nVdbeWrite>0 || db->autoCommit==0 
69323         || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
69324     );
69325
69326 #ifndef SQLITE_OMIT_TRACE
69327     if( db->xProfile && !db->init.busy ){
69328       sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
69329     }
69330 #endif
69331
69332     db->nVdbeActive++;
69333     if( p->readOnly==0 ) db->nVdbeWrite++;
69334     if( p->bIsReader ) db->nVdbeRead++;
69335     p->pc = 0;
69336   }
69337 #ifdef SQLITE_DEBUG
69338   p->rcApp = SQLITE_OK;
69339 #endif
69340 #ifndef SQLITE_OMIT_EXPLAIN
69341   if( p->explain ){
69342     rc = sqlite3VdbeList(p);
69343   }else
69344 #endif /* SQLITE_OMIT_EXPLAIN */
69345   {
69346     db->nVdbeExec++;
69347     rc = sqlite3VdbeExec(p);
69348     db->nVdbeExec--;
69349   }
69350
69351 #ifndef SQLITE_OMIT_TRACE
69352   /* Invoke the profile callback if there is one
69353   */
69354   if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
69355     sqlite3_int64 iNow;
69356     sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
69357     db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
69358   }
69359 #endif
69360
69361   if( rc==SQLITE_DONE ){
69362     assert( p->rc==SQLITE_OK );
69363     p->rc = doWalCallbacks(db);
69364     if( p->rc!=SQLITE_OK ){
69365       rc = SQLITE_ERROR;
69366     }
69367   }
69368
69369   db->errCode = rc;
69370   if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
69371     p->rc = SQLITE_NOMEM;
69372   }
69373 end_of_step:
69374   /* At this point local variable rc holds the value that should be 
69375   ** returned if this statement was compiled using the legacy 
69376   ** sqlite3_prepare() interface. According to the docs, this can only
69377   ** be one of the values in the first assert() below. Variable p->rc 
69378   ** contains the value that would be returned if sqlite3_finalize() 
69379   ** were called on statement p.
69380   */
69381   assert( rc==SQLITE_ROW  || rc==SQLITE_DONE   || rc==SQLITE_ERROR 
69382        || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
69383   );
69384   assert( (p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE) || p->rc==p->rcApp );
69385   if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
69386     /* If this statement was prepared using sqlite3_prepare_v2(), and an
69387     ** error has occurred, then return the error code in p->rc to the
69388     ** caller. Set the error code in the database handle to the same value.
69389     */ 
69390     rc = sqlite3VdbeTransferError(p);
69391   }
69392   return (rc&db->errMask);
69393 }
69394
69395 /*
69396 ** This is the top-level implementation of sqlite3_step().  Call
69397 ** sqlite3Step() to do most of the work.  If a schema error occurs,
69398 ** call sqlite3Reprepare() and try again.
69399 */
69400 SQLITE_API int SQLITE_STDCALL sqlite3_step(sqlite3_stmt *pStmt){
69401   int rc = SQLITE_OK;      /* Result from sqlite3Step() */
69402   int rc2 = SQLITE_OK;     /* Result from sqlite3Reprepare() */
69403   Vdbe *v = (Vdbe*)pStmt;  /* the prepared statement */
69404   int cnt = 0;             /* Counter to prevent infinite loop of reprepares */
69405   sqlite3 *db;             /* The database connection */
69406
69407   if( vdbeSafetyNotNull(v) ){
69408     return SQLITE_MISUSE_BKPT;
69409   }
69410   db = v->db;
69411   sqlite3_mutex_enter(db->mutex);
69412   v->doingRerun = 0;
69413   while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
69414          && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
69415     int savedPc = v->pc;
69416     rc2 = rc = sqlite3Reprepare(v);
69417     if( rc!=SQLITE_OK) break;
69418     sqlite3_reset(pStmt);
69419     if( savedPc>=0 ) v->doingRerun = 1;
69420     assert( v->expired==0 );
69421   }
69422   if( rc2!=SQLITE_OK ){
69423     /* This case occurs after failing to recompile an sql statement. 
69424     ** The error message from the SQL compiler has already been loaded 
69425     ** into the database handle. This block copies the error message 
69426     ** from the database handle into the statement and sets the statement
69427     ** program counter to 0 to ensure that when the statement is 
69428     ** finalized or reset the parser error message is available via
69429     ** sqlite3_errmsg() and sqlite3_errcode().
69430     */
69431     const char *zErr = (const char *)sqlite3_value_text(db->pErr); 
69432     sqlite3DbFree(db, v->zErrMsg);
69433     if( !db->mallocFailed ){
69434       v->zErrMsg = sqlite3DbStrDup(db, zErr);
69435       v->rc = rc2;
69436     } else {
69437       v->zErrMsg = 0;
69438       v->rc = rc = SQLITE_NOMEM;
69439     }
69440   }
69441   rc = sqlite3ApiExit(db, rc);
69442   sqlite3_mutex_leave(db->mutex);
69443   return rc;
69444 }
69445
69446
69447 /*
69448 ** Extract the user data from a sqlite3_context structure and return a
69449 ** pointer to it.
69450 */
69451 SQLITE_API void *SQLITE_STDCALL sqlite3_user_data(sqlite3_context *p){
69452   assert( p && p->pFunc );
69453   return p->pFunc->pUserData;
69454 }
69455
69456 /*
69457 ** Extract the user data from a sqlite3_context structure and return a
69458 ** pointer to it.
69459 **
69460 ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
69461 ** returns a copy of the pointer to the database connection (the 1st
69462 ** parameter) of the sqlite3_create_function() and
69463 ** sqlite3_create_function16() routines that originally registered the
69464 ** application defined function.
69465 */
69466 SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_context_db_handle(sqlite3_context *p){
69467   assert( p && p->pFunc );
69468   return p->pOut->db;
69469 }
69470
69471 /*
69472 ** Return the current time for a statement.  If the current time
69473 ** is requested more than once within the same run of a single prepared
69474 ** statement, the exact same time is returned for each invocation regardless
69475 ** of the amount of time that elapses between invocations.  In other words,
69476 ** the time returned is always the time of the first call.
69477 */
69478 SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
69479   int rc;
69480 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
69481   sqlite3_int64 *piTime = &p->pVdbe->iCurrentTime;
69482   assert( p->pVdbe!=0 );
69483 #else
69484   sqlite3_int64 iTime = 0;
69485   sqlite3_int64 *piTime = p->pVdbe!=0 ? &p->pVdbe->iCurrentTime : &iTime;
69486 #endif
69487   if( *piTime==0 ){
69488     rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, piTime);
69489     if( rc ) *piTime = 0;
69490   }
69491   return *piTime;
69492 }
69493
69494 /*
69495 ** The following is the implementation of an SQL function that always
69496 ** fails with an error message stating that the function is used in the
69497 ** wrong context.  The sqlite3_overload_function() API might construct
69498 ** SQL function that use this routine so that the functions will exist
69499 ** for name resolution but are actually overloaded by the xFindFunction
69500 ** method of virtual tables.
69501 */
69502 SQLITE_PRIVATE void sqlite3InvalidFunction(
69503   sqlite3_context *context,  /* The function calling context */
69504   int NotUsed,               /* Number of arguments to the function */
69505   sqlite3_value **NotUsed2   /* Value of each argument */
69506 ){
69507   const char *zName = context->pFunc->zName;
69508   char *zErr;
69509   UNUSED_PARAMETER2(NotUsed, NotUsed2);
69510   zErr = sqlite3_mprintf(
69511       "unable to use function %s in the requested context", zName);
69512   sqlite3_result_error(context, zErr, -1);
69513   sqlite3_free(zErr);
69514 }
69515
69516 /*
69517 ** Create a new aggregate context for p and return a pointer to
69518 ** its pMem->z element.
69519 */
69520 static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
69521   Mem *pMem = p->pMem;
69522   assert( (pMem->flags & MEM_Agg)==0 );
69523   if( nByte<=0 ){
69524     sqlite3VdbeMemSetNull(pMem);
69525     pMem->z = 0;
69526   }else{
69527     sqlite3VdbeMemClearAndResize(pMem, nByte);
69528     pMem->flags = MEM_Agg;
69529     pMem->u.pDef = p->pFunc;
69530     if( pMem->z ){
69531       memset(pMem->z, 0, nByte);
69532     }
69533   }
69534   return (void*)pMem->z;
69535 }
69536
69537 /*
69538 ** Allocate or return the aggregate context for a user function.  A new
69539 ** context is allocated on the first call.  Subsequent calls return the
69540 ** same context that was returned on prior calls.
69541 */
69542 SQLITE_API void *SQLITE_STDCALL sqlite3_aggregate_context(sqlite3_context *p, int nByte){
69543   assert( p && p->pFunc && p->pFunc->xStep );
69544   assert( sqlite3_mutex_held(p->pOut->db->mutex) );
69545   testcase( nByte<0 );
69546   if( (p->pMem->flags & MEM_Agg)==0 ){
69547     return createAggContext(p, nByte);
69548   }else{
69549     return (void*)p->pMem->z;
69550   }
69551 }
69552
69553 /*
69554 ** Return the auxiliary data pointer, if any, for the iArg'th argument to
69555 ** the user-function defined by pCtx.
69556 */
69557 SQLITE_API void *SQLITE_STDCALL sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
69558   AuxData *pAuxData;
69559
69560   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69561 #if SQLITE_ENABLE_STAT3_OR_STAT4
69562   if( pCtx->pVdbe==0 ) return 0;
69563 #else
69564   assert( pCtx->pVdbe!=0 );
69565 #endif
69566   for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
69567     if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
69568   }
69569
69570   return (pAuxData ? pAuxData->pAux : 0);
69571 }
69572
69573 /*
69574 ** Set the auxiliary data pointer and delete function, for the iArg'th
69575 ** argument to the user-function defined by pCtx. Any previous value is
69576 ** deleted by calling the delete function specified when it was set.
69577 */
69578 SQLITE_API void SQLITE_STDCALL sqlite3_set_auxdata(
69579   sqlite3_context *pCtx, 
69580   int iArg, 
69581   void *pAux, 
69582   void (*xDelete)(void*)
69583 ){
69584   AuxData *pAuxData;
69585   Vdbe *pVdbe = pCtx->pVdbe;
69586
69587   assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
69588   if( iArg<0 ) goto failed;
69589 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
69590   if( pVdbe==0 ) goto failed;
69591 #else
69592   assert( pVdbe!=0 );
69593 #endif
69594
69595   for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
69596     if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
69597   }
69598   if( pAuxData==0 ){
69599     pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
69600     if( !pAuxData ) goto failed;
69601     pAuxData->iOp = pCtx->iOp;
69602     pAuxData->iArg = iArg;
69603     pAuxData->pNext = pVdbe->pAuxData;
69604     pVdbe->pAuxData = pAuxData;
69605     if( pCtx->fErrorOrAux==0 ){
69606       pCtx->isError = 0;
69607       pCtx->fErrorOrAux = 1;
69608     }
69609   }else if( pAuxData->xDelete ){
69610     pAuxData->xDelete(pAuxData->pAux);
69611   }
69612
69613   pAuxData->pAux = pAux;
69614   pAuxData->xDelete = xDelete;
69615   return;
69616
69617 failed:
69618   if( xDelete ){
69619     xDelete(pAux);
69620   }
69621 }
69622
69623 #ifndef SQLITE_OMIT_DEPRECATED
69624 /*
69625 ** Return the number of times the Step function of an aggregate has been 
69626 ** called.
69627 **
69628 ** This function is deprecated.  Do not use it for new code.  It is
69629 ** provide only to avoid breaking legacy code.  New aggregate function
69630 ** implementations should keep their own counts within their aggregate
69631 ** context.
69632 */
69633 SQLITE_API int SQLITE_STDCALL sqlite3_aggregate_count(sqlite3_context *p){
69634   assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
69635   return p->pMem->n;
69636 }
69637 #endif
69638
69639 /*
69640 ** Return the number of columns in the result set for the statement pStmt.
69641 */
69642 SQLITE_API int SQLITE_STDCALL sqlite3_column_count(sqlite3_stmt *pStmt){
69643   Vdbe *pVm = (Vdbe *)pStmt;
69644   return pVm ? pVm->nResColumn : 0;
69645 }
69646
69647 /*
69648 ** Return the number of values available from the current row of the
69649 ** currently executing statement pStmt.
69650 */
69651 SQLITE_API int SQLITE_STDCALL sqlite3_data_count(sqlite3_stmt *pStmt){
69652   Vdbe *pVm = (Vdbe *)pStmt;
69653   if( pVm==0 || pVm->pResultSet==0 ) return 0;
69654   return pVm->nResColumn;
69655 }
69656
69657 /*
69658 ** Return a pointer to static memory containing an SQL NULL value.
69659 */
69660 static const Mem *columnNullValue(void){
69661   /* Even though the Mem structure contains an element
69662   ** of type i64, on certain architectures (x86) with certain compiler
69663   ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
69664   ** instead of an 8-byte one. This all works fine, except that when
69665   ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
69666   ** that a Mem structure is located on an 8-byte boundary. To prevent
69667   ** these assert()s from failing, when building with SQLITE_DEBUG defined
69668   ** using gcc, we force nullMem to be 8-byte aligned using the magical
69669   ** __attribute__((aligned(8))) macro.  */
69670   static const Mem nullMem 
69671 #if defined(SQLITE_DEBUG) && defined(__GNUC__)
69672     __attribute__((aligned(8))) 
69673 #endif
69674     = {
69675         /* .u          = */ {0},
69676         /* .flags      = */ MEM_Null,
69677         /* .enc        = */ 0,
69678         /* .n          = */ 0,
69679         /* .z          = */ 0,
69680         /* .zMalloc    = */ 0,
69681         /* .szMalloc   = */ 0,
69682         /* .iPadding1  = */ 0,
69683         /* .db         = */ 0,
69684         /* .xDel       = */ 0,
69685 #ifdef SQLITE_DEBUG
69686         /* .pScopyFrom = */ 0,
69687         /* .pFiller    = */ 0,
69688 #endif
69689       };
69690   return &nullMem;
69691 }
69692
69693 /*
69694 ** Check to see if column iCol of the given statement is valid.  If
69695 ** it is, return a pointer to the Mem for the value of that column.
69696 ** If iCol is not valid, return a pointer to a Mem which has a value
69697 ** of NULL.
69698 */
69699 static Mem *columnMem(sqlite3_stmt *pStmt, int i){
69700   Vdbe *pVm;
69701   Mem *pOut;
69702
69703   pVm = (Vdbe *)pStmt;
69704   if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
69705     sqlite3_mutex_enter(pVm->db->mutex);
69706     pOut = &pVm->pResultSet[i];
69707   }else{
69708     if( pVm && ALWAYS(pVm->db) ){
69709       sqlite3_mutex_enter(pVm->db->mutex);
69710       sqlite3Error(pVm->db, SQLITE_RANGE);
69711     }
69712     pOut = (Mem*)columnNullValue();
69713   }
69714   return pOut;
69715 }
69716
69717 /*
69718 ** This function is called after invoking an sqlite3_value_XXX function on a 
69719 ** column value (i.e. a value returned by evaluating an SQL expression in the
69720 ** select list of a SELECT statement) that may cause a malloc() failure. If 
69721 ** malloc() has failed, the threads mallocFailed flag is cleared and the result
69722 ** code of statement pStmt set to SQLITE_NOMEM.
69723 **
69724 ** Specifically, this is called from within:
69725 **
69726 **     sqlite3_column_int()
69727 **     sqlite3_column_int64()
69728 **     sqlite3_column_text()
69729 **     sqlite3_column_text16()
69730 **     sqlite3_column_real()
69731 **     sqlite3_column_bytes()
69732 **     sqlite3_column_bytes16()
69733 **     sqiite3_column_blob()
69734 */
69735 static void columnMallocFailure(sqlite3_stmt *pStmt)
69736 {
69737   /* If malloc() failed during an encoding conversion within an
69738   ** sqlite3_column_XXX API, then set the return code of the statement to
69739   ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
69740   ** and _finalize() will return NOMEM.
69741   */
69742   Vdbe *p = (Vdbe *)pStmt;
69743   if( p ){
69744     p->rc = sqlite3ApiExit(p->db, p->rc);
69745     sqlite3_mutex_leave(p->db->mutex);
69746   }
69747 }
69748
69749 /**************************** sqlite3_column_  *******************************
69750 ** The following routines are used to access elements of the current row
69751 ** in the result set.
69752 */
69753 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
69754   const void *val;
69755   val = sqlite3_value_blob( columnMem(pStmt,i) );
69756   /* Even though there is no encoding conversion, value_blob() might
69757   ** need to call malloc() to expand the result of a zeroblob() 
69758   ** expression. 
69759   */
69760   columnMallocFailure(pStmt);
69761   return val;
69762 }
69763 SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
69764   int val = sqlite3_value_bytes( columnMem(pStmt,i) );
69765   columnMallocFailure(pStmt);
69766   return val;
69767 }
69768 SQLITE_API int SQLITE_STDCALL sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
69769   int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
69770   columnMallocFailure(pStmt);
69771   return val;
69772 }
69773 SQLITE_API double SQLITE_STDCALL sqlite3_column_double(sqlite3_stmt *pStmt, int i){
69774   double val = sqlite3_value_double( columnMem(pStmt,i) );
69775   columnMallocFailure(pStmt);
69776   return val;
69777 }
69778 SQLITE_API int SQLITE_STDCALL sqlite3_column_int(sqlite3_stmt *pStmt, int i){
69779   int val = sqlite3_value_int( columnMem(pStmt,i) );
69780   columnMallocFailure(pStmt);
69781   return val;
69782 }
69783 SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
69784   sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
69785   columnMallocFailure(pStmt);
69786   return val;
69787 }
69788 SQLITE_API const unsigned char *SQLITE_STDCALL sqlite3_column_text(sqlite3_stmt *pStmt, int i){
69789   const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
69790   columnMallocFailure(pStmt);
69791   return val;
69792 }
69793 SQLITE_API sqlite3_value *SQLITE_STDCALL sqlite3_column_value(sqlite3_stmt *pStmt, int i){
69794   Mem *pOut = columnMem(pStmt, i);
69795   if( pOut->flags&MEM_Static ){
69796     pOut->flags &= ~MEM_Static;
69797     pOut->flags |= MEM_Ephem;
69798   }
69799   columnMallocFailure(pStmt);
69800   return (sqlite3_value *)pOut;
69801 }
69802 #ifndef SQLITE_OMIT_UTF16
69803 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
69804   const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
69805   columnMallocFailure(pStmt);
69806   return val;
69807 }
69808 #endif /* SQLITE_OMIT_UTF16 */
69809 SQLITE_API int SQLITE_STDCALL sqlite3_column_type(sqlite3_stmt *pStmt, int i){
69810   int iType = sqlite3_value_type( columnMem(pStmt,i) );
69811   columnMallocFailure(pStmt);
69812   return iType;
69813 }
69814
69815 /*
69816 ** Convert the N-th element of pStmt->pColName[] into a string using
69817 ** xFunc() then return that string.  If N is out of range, return 0.
69818 **
69819 ** There are up to 5 names for each column.  useType determines which
69820 ** name is returned.  Here are the names:
69821 **
69822 **    0      The column name as it should be displayed for output
69823 **    1      The datatype name for the column
69824 **    2      The name of the database that the column derives from
69825 **    3      The name of the table that the column derives from
69826 **    4      The name of the table column that the result column derives from
69827 **
69828 ** If the result is not a simple column reference (if it is an expression
69829 ** or a constant) then useTypes 2, 3, and 4 return NULL.
69830 */
69831 static const void *columnName(
69832   sqlite3_stmt *pStmt,
69833   int N,
69834   const void *(*xFunc)(Mem*),
69835   int useType
69836 ){
69837   const void *ret;
69838   Vdbe *p;
69839   int n;
69840   sqlite3 *db;
69841 #ifdef SQLITE_ENABLE_API_ARMOR
69842   if( pStmt==0 ){
69843     (void)SQLITE_MISUSE_BKPT;
69844     return 0;
69845   }
69846 #endif
69847   ret = 0;
69848   p = (Vdbe *)pStmt;
69849   db = p->db;
69850   assert( db!=0 );
69851   n = sqlite3_column_count(pStmt);
69852   if( N<n && N>=0 ){
69853     N += useType*n;
69854     sqlite3_mutex_enter(db->mutex);
69855     assert( db->mallocFailed==0 );
69856     ret = xFunc(&p->aColName[N]);
69857      /* A malloc may have failed inside of the xFunc() call. If this
69858     ** is the case, clear the mallocFailed flag and return NULL.
69859     */
69860     if( db->mallocFailed ){
69861       db->mallocFailed = 0;
69862       ret = 0;
69863     }
69864     sqlite3_mutex_leave(db->mutex);
69865   }
69866   return ret;
69867 }
69868
69869 /*
69870 ** Return the name of the Nth column of the result set returned by SQL
69871 ** statement pStmt.
69872 */
69873 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_name(sqlite3_stmt *pStmt, int N){
69874   return columnName(
69875       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
69876 }
69877 #ifndef SQLITE_OMIT_UTF16
69878 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
69879   return columnName(
69880       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
69881 }
69882 #endif
69883
69884 /*
69885 ** Constraint:  If you have ENABLE_COLUMN_METADATA then you must
69886 ** not define OMIT_DECLTYPE.
69887 */
69888 #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
69889 # error "Must not define both SQLITE_OMIT_DECLTYPE \
69890          and SQLITE_ENABLE_COLUMN_METADATA"
69891 #endif
69892
69893 #ifndef SQLITE_OMIT_DECLTYPE
69894 /*
69895 ** Return the column declaration type (if applicable) of the 'i'th column
69896 ** of the result set of SQL statement pStmt.
69897 */
69898 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
69899   return columnName(
69900       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
69901 }
69902 #ifndef SQLITE_OMIT_UTF16
69903 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
69904   return columnName(
69905       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
69906 }
69907 #endif /* SQLITE_OMIT_UTF16 */
69908 #endif /* SQLITE_OMIT_DECLTYPE */
69909
69910 #ifdef SQLITE_ENABLE_COLUMN_METADATA
69911 /*
69912 ** Return the name of the database from which a result column derives.
69913 ** NULL is returned if the result column is an expression or constant or
69914 ** anything else which is not an unambiguous reference to a database column.
69915 */
69916 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
69917   return columnName(
69918       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
69919 }
69920 #ifndef SQLITE_OMIT_UTF16
69921 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
69922   return columnName(
69923       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
69924 }
69925 #endif /* SQLITE_OMIT_UTF16 */
69926
69927 /*
69928 ** Return the name of the table from which a result column derives.
69929 ** NULL is returned if the result column is an expression or constant or
69930 ** anything else which is not an unambiguous reference to a database column.
69931 */
69932 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
69933   return columnName(
69934       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
69935 }
69936 #ifndef SQLITE_OMIT_UTF16
69937 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
69938   return columnName(
69939       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
69940 }
69941 #endif /* SQLITE_OMIT_UTF16 */
69942
69943 /*
69944 ** Return the name of the table column from which a result column derives.
69945 ** NULL is returned if the result column is an expression or constant or
69946 ** anything else which is not an unambiguous reference to a database column.
69947 */
69948 SQLITE_API const char *SQLITE_STDCALL sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
69949   return columnName(
69950       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
69951 }
69952 #ifndef SQLITE_OMIT_UTF16
69953 SQLITE_API const void *SQLITE_STDCALL sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
69954   return columnName(
69955       pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
69956 }
69957 #endif /* SQLITE_OMIT_UTF16 */
69958 #endif /* SQLITE_ENABLE_COLUMN_METADATA */
69959
69960
69961 /******************************* sqlite3_bind_  ***************************
69962 ** 
69963 ** Routines used to attach values to wildcards in a compiled SQL statement.
69964 */
69965 /*
69966 ** Unbind the value bound to variable i in virtual machine p. This is the 
69967 ** the same as binding a NULL value to the column. If the "i" parameter is
69968 ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
69969 **
69970 ** A successful evaluation of this routine acquires the mutex on p.
69971 ** the mutex is released if any kind of error occurs.
69972 **
69973 ** The error code stored in database p->db is overwritten with the return
69974 ** value in any case.
69975 */
69976 static int vdbeUnbind(Vdbe *p, int i){
69977   Mem *pVar;
69978   if( vdbeSafetyNotNull(p) ){
69979     return SQLITE_MISUSE_BKPT;
69980   }
69981   sqlite3_mutex_enter(p->db->mutex);
69982   if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
69983     sqlite3Error(p->db, SQLITE_MISUSE);
69984     sqlite3_mutex_leave(p->db->mutex);
69985     sqlite3_log(SQLITE_MISUSE, 
69986         "bind on a busy prepared statement: [%s]", p->zSql);
69987     return SQLITE_MISUSE_BKPT;
69988   }
69989   if( i<1 || i>p->nVar ){
69990     sqlite3Error(p->db, SQLITE_RANGE);
69991     sqlite3_mutex_leave(p->db->mutex);
69992     return SQLITE_RANGE;
69993   }
69994   i--;
69995   pVar = &p->aVar[i];
69996   sqlite3VdbeMemRelease(pVar);
69997   pVar->flags = MEM_Null;
69998   sqlite3Error(p->db, SQLITE_OK);
69999
70000   /* If the bit corresponding to this variable in Vdbe.expmask is set, then 
70001   ** binding a new value to this variable invalidates the current query plan.
70002   **
70003   ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
70004   ** parameter in the WHERE clause might influence the choice of query plan
70005   ** for a statement, then the statement will be automatically recompiled,
70006   ** as if there had been a schema change, on the first sqlite3_step() call
70007   ** following any change to the bindings of that parameter.
70008   */
70009   if( p->isPrepareV2 &&
70010      ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
70011   ){
70012     p->expired = 1;
70013   }
70014   return SQLITE_OK;
70015 }
70016
70017 /*
70018 ** Bind a text or BLOB value.
70019 */
70020 static int bindText(
70021   sqlite3_stmt *pStmt,   /* The statement to bind against */
70022   int i,                 /* Index of the parameter to bind */
70023   const void *zData,     /* Pointer to the data to be bound */
70024   int nData,             /* Number of bytes of data to be bound */
70025   void (*xDel)(void*),   /* Destructor for the data */
70026   u8 encoding            /* Encoding for the data */
70027 ){
70028   Vdbe *p = (Vdbe *)pStmt;
70029   Mem *pVar;
70030   int rc;
70031
70032   rc = vdbeUnbind(p, i);
70033   if( rc==SQLITE_OK ){
70034     if( zData!=0 ){
70035       pVar = &p->aVar[i-1];
70036       rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
70037       if( rc==SQLITE_OK && encoding!=0 ){
70038         rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
70039       }
70040       sqlite3Error(p->db, rc);
70041       rc = sqlite3ApiExit(p->db, rc);
70042     }
70043     sqlite3_mutex_leave(p->db->mutex);
70044   }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
70045     xDel((void*)zData);
70046   }
70047   return rc;
70048 }
70049
70050
70051 /*
70052 ** Bind a blob value to an SQL statement variable.
70053 */
70054 SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob(
70055   sqlite3_stmt *pStmt, 
70056   int i, 
70057   const void *zData, 
70058   int nData, 
70059   void (*xDel)(void*)
70060 ){
70061   return bindText(pStmt, i, zData, nData, xDel, 0);
70062 }
70063 SQLITE_API int SQLITE_STDCALL sqlite3_bind_blob64(
70064   sqlite3_stmt *pStmt, 
70065   int i, 
70066   const void *zData, 
70067   sqlite3_uint64 nData, 
70068   void (*xDel)(void*)
70069 ){
70070   assert( xDel!=SQLITE_DYNAMIC );
70071   if( nData>0x7fffffff ){
70072     return invokeValueDestructor(zData, xDel, 0);
70073   }else{
70074     return bindText(pStmt, i, zData, (int)nData, xDel, 0);
70075   }
70076 }
70077 SQLITE_API int SQLITE_STDCALL sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
70078   int rc;
70079   Vdbe *p = (Vdbe *)pStmt;
70080   rc = vdbeUnbind(p, i);
70081   if( rc==SQLITE_OK ){
70082     sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
70083     sqlite3_mutex_leave(p->db->mutex);
70084   }
70085   return rc;
70086 }
70087 SQLITE_API int SQLITE_STDCALL sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
70088   return sqlite3_bind_int64(p, i, (i64)iValue);
70089 }
70090 SQLITE_API int SQLITE_STDCALL sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
70091   int rc;
70092   Vdbe *p = (Vdbe *)pStmt;
70093   rc = vdbeUnbind(p, i);
70094   if( rc==SQLITE_OK ){
70095     sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
70096     sqlite3_mutex_leave(p->db->mutex);
70097   }
70098   return rc;
70099 }
70100 SQLITE_API int SQLITE_STDCALL sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
70101   int rc;
70102   Vdbe *p = (Vdbe*)pStmt;
70103   rc = vdbeUnbind(p, i);
70104   if( rc==SQLITE_OK ){
70105     sqlite3_mutex_leave(p->db->mutex);
70106   }
70107   return rc;
70108 }
70109 SQLITE_API int SQLITE_STDCALL sqlite3_bind_text( 
70110   sqlite3_stmt *pStmt, 
70111   int i, 
70112   const char *zData, 
70113   int nData, 
70114   void (*xDel)(void*)
70115 ){
70116   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
70117 }
70118 SQLITE_API int SQLITE_STDCALL sqlite3_bind_text64( 
70119   sqlite3_stmt *pStmt, 
70120   int i, 
70121   const char *zData, 
70122   sqlite3_uint64 nData, 
70123   void (*xDel)(void*),
70124   unsigned char enc
70125 ){
70126   assert( xDel!=SQLITE_DYNAMIC );
70127   if( nData>0x7fffffff ){
70128     return invokeValueDestructor(zData, xDel, 0);
70129   }else{
70130     if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
70131     return bindText(pStmt, i, zData, (int)nData, xDel, enc);
70132   }
70133 }
70134 #ifndef SQLITE_OMIT_UTF16
70135 SQLITE_API int SQLITE_STDCALL sqlite3_bind_text16(
70136   sqlite3_stmt *pStmt, 
70137   int i, 
70138   const void *zData, 
70139   int nData, 
70140   void (*xDel)(void*)
70141 ){
70142   return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
70143 }
70144 #endif /* SQLITE_OMIT_UTF16 */
70145 SQLITE_API int SQLITE_STDCALL sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
70146   int rc;
70147   switch( sqlite3_value_type((sqlite3_value*)pValue) ){
70148     case SQLITE_INTEGER: {
70149       rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
70150       break;
70151     }
70152     case SQLITE_FLOAT: {
70153       rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
70154       break;
70155     }
70156     case SQLITE_BLOB: {
70157       if( pValue->flags & MEM_Zero ){
70158         rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
70159       }else{
70160         rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
70161       }
70162       break;
70163     }
70164     case SQLITE_TEXT: {
70165       rc = bindText(pStmt,i,  pValue->z, pValue->n, SQLITE_TRANSIENT,
70166                               pValue->enc);
70167       break;
70168     }
70169     default: {
70170       rc = sqlite3_bind_null(pStmt, i);
70171       break;
70172     }
70173   }
70174   return rc;
70175 }
70176 SQLITE_API int SQLITE_STDCALL sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
70177   int rc;
70178   Vdbe *p = (Vdbe *)pStmt;
70179   rc = vdbeUnbind(p, i);
70180   if( rc==SQLITE_OK ){
70181     sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
70182     sqlite3_mutex_leave(p->db->mutex);
70183   }
70184   return rc;
70185 }
70186
70187 /*
70188 ** Return the number of wildcards that can be potentially bound to.
70189 ** This routine is added to support DBD::SQLite.  
70190 */
70191 SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
70192   Vdbe *p = (Vdbe*)pStmt;
70193   return p ? p->nVar : 0;
70194 }
70195
70196 /*
70197 ** Return the name of a wildcard parameter.  Return NULL if the index
70198 ** is out of range or if the wildcard is unnamed.
70199 **
70200 ** The result is always UTF-8.
70201 */
70202 SQLITE_API const char *SQLITE_STDCALL sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
70203   Vdbe *p = (Vdbe*)pStmt;
70204   if( p==0 || i<1 || i>p->nzVar ){
70205     return 0;
70206   }
70207   return p->azVar[i-1];
70208 }
70209
70210 /*
70211 ** Given a wildcard parameter name, return the index of the variable
70212 ** with that name.  If there is no variable with the given name,
70213 ** return 0.
70214 */
70215 SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
70216   int i;
70217   if( p==0 ){
70218     return 0;
70219   }
70220   if( zName ){
70221     for(i=0; i<p->nzVar; i++){
70222       const char *z = p->azVar[i];
70223       if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
70224         return i+1;
70225       }
70226     }
70227   }
70228   return 0;
70229 }
70230 SQLITE_API int SQLITE_STDCALL sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
70231   return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
70232 }
70233
70234 /*
70235 ** Transfer all bindings from the first statement over to the second.
70236 */
70237 SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
70238   Vdbe *pFrom = (Vdbe*)pFromStmt;
70239   Vdbe *pTo = (Vdbe*)pToStmt;
70240   int i;
70241   assert( pTo->db==pFrom->db );
70242   assert( pTo->nVar==pFrom->nVar );
70243   sqlite3_mutex_enter(pTo->db->mutex);
70244   for(i=0; i<pFrom->nVar; i++){
70245     sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
70246   }
70247   sqlite3_mutex_leave(pTo->db->mutex);
70248   return SQLITE_OK;
70249 }
70250
70251 #ifndef SQLITE_OMIT_DEPRECATED
70252 /*
70253 ** Deprecated external interface.  Internal/core SQLite code
70254 ** should call sqlite3TransferBindings.
70255 **
70256 ** It is misuse to call this routine with statements from different
70257 ** database connections.  But as this is a deprecated interface, we
70258 ** will not bother to check for that condition.
70259 **
70260 ** If the two statements contain a different number of bindings, then
70261 ** an SQLITE_ERROR is returned.  Nothing else can go wrong, so otherwise
70262 ** SQLITE_OK is returned.
70263 */
70264 SQLITE_API int SQLITE_STDCALL sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
70265   Vdbe *pFrom = (Vdbe*)pFromStmt;
70266   Vdbe *pTo = (Vdbe*)pToStmt;
70267   if( pFrom->nVar!=pTo->nVar ){
70268     return SQLITE_ERROR;
70269   }
70270   if( pTo->isPrepareV2 && pTo->expmask ){
70271     pTo->expired = 1;
70272   }
70273   if( pFrom->isPrepareV2 && pFrom->expmask ){
70274     pFrom->expired = 1;
70275   }
70276   return sqlite3TransferBindings(pFromStmt, pToStmt);
70277 }
70278 #endif
70279
70280 /*
70281 ** Return the sqlite3* database handle to which the prepared statement given
70282 ** in the argument belongs.  This is the same database handle that was
70283 ** the first argument to the sqlite3_prepare() that was used to create
70284 ** the statement in the first place.
70285 */
70286 SQLITE_API sqlite3 *SQLITE_STDCALL sqlite3_db_handle(sqlite3_stmt *pStmt){
70287   return pStmt ? ((Vdbe*)pStmt)->db : 0;
70288 }
70289
70290 /*
70291 ** Return true if the prepared statement is guaranteed to not modify the
70292 ** database.
70293 */
70294 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
70295   return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
70296 }
70297
70298 /*
70299 ** Return true if the prepared statement is in need of being reset.
70300 */
70301 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_busy(sqlite3_stmt *pStmt){
70302   Vdbe *v = (Vdbe*)pStmt;
70303   return v!=0 && v->pc>=0 && v->magic==VDBE_MAGIC_RUN;
70304 }
70305
70306 /*
70307 ** Return a pointer to the next prepared statement after pStmt associated
70308 ** with database connection pDb.  If pStmt is NULL, return the first
70309 ** prepared statement for the database connection.  Return NULL if there
70310 ** are no more.
70311 */
70312 SQLITE_API sqlite3_stmt *SQLITE_STDCALL sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
70313   sqlite3_stmt *pNext;
70314 #ifdef SQLITE_ENABLE_API_ARMOR
70315   if( !sqlite3SafetyCheckOk(pDb) ){
70316     (void)SQLITE_MISUSE_BKPT;
70317     return 0;
70318   }
70319 #endif
70320   sqlite3_mutex_enter(pDb->mutex);
70321   if( pStmt==0 ){
70322     pNext = (sqlite3_stmt*)pDb->pVdbe;
70323   }else{
70324     pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
70325   }
70326   sqlite3_mutex_leave(pDb->mutex);
70327   return pNext;
70328 }
70329
70330 /*
70331 ** Return the value of a status counter for a prepared statement
70332 */
70333 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
70334   Vdbe *pVdbe = (Vdbe*)pStmt;
70335   u32 v;
70336 #ifdef SQLITE_ENABLE_API_ARMOR
70337   if( !pStmt ){
70338     (void)SQLITE_MISUSE_BKPT;
70339     return 0;
70340   }
70341 #endif
70342   v = pVdbe->aCounter[op];
70343   if( resetFlag ) pVdbe->aCounter[op] = 0;
70344   return (int)v;
70345 }
70346
70347 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
70348 /*
70349 ** Return status data for a single loop within query pStmt.
70350 */
70351 SQLITE_API int SQLITE_STDCALL sqlite3_stmt_scanstatus(
70352   sqlite3_stmt *pStmt,            /* Prepared statement being queried */
70353   int idx,                        /* Index of loop to report on */
70354   int iScanStatusOp,              /* Which metric to return */
70355   void *pOut                      /* OUT: Write the answer here */
70356 ){
70357   Vdbe *p = (Vdbe*)pStmt;
70358   ScanStatus *pScan;
70359   if( idx<0 || idx>=p->nScan ) return 1;
70360   pScan = &p->aScan[idx];
70361   switch( iScanStatusOp ){
70362     case SQLITE_SCANSTAT_NLOOP: {
70363       *(sqlite3_int64*)pOut = p->anExec[pScan->addrLoop];
70364       break;
70365     }
70366     case SQLITE_SCANSTAT_NVISIT: {
70367       *(sqlite3_int64*)pOut = p->anExec[pScan->addrVisit];
70368       break;
70369     }
70370     case SQLITE_SCANSTAT_EST: {
70371       double r = 1.0;
70372       LogEst x = pScan->nEst;
70373       while( x<100 ){
70374         x += 10;
70375         r *= 0.5;
70376       }
70377       *(double*)pOut = r*sqlite3LogEstToInt(x);
70378       break;
70379     }
70380     case SQLITE_SCANSTAT_NAME: {
70381       *(const char**)pOut = pScan->zName;
70382       break;
70383     }
70384     case SQLITE_SCANSTAT_EXPLAIN: {
70385       if( pScan->addrExplain ){
70386         *(const char**)pOut = p->aOp[ pScan->addrExplain ].p4.z;
70387       }else{
70388         *(const char**)pOut = 0;
70389       }
70390       break;
70391     }
70392     case SQLITE_SCANSTAT_SELECTID: {
70393       if( pScan->addrExplain ){
70394         *(int*)pOut = p->aOp[ pScan->addrExplain ].p1;
70395       }else{
70396         *(int*)pOut = -1;
70397       }
70398       break;
70399     }
70400     default: {
70401       return 1;
70402     }
70403   }
70404   return 0;
70405 }
70406
70407 /*
70408 ** Zero all counters associated with the sqlite3_stmt_scanstatus() data.
70409 */
70410 SQLITE_API void SQLITE_STDCALL sqlite3_stmt_scanstatus_reset(sqlite3_stmt *pStmt){
70411   Vdbe *p = (Vdbe*)pStmt;
70412   memset(p->anExec, 0, p->nOp * sizeof(i64));
70413 }
70414 #endif /* SQLITE_ENABLE_STMT_SCANSTATUS */
70415
70416 /************** End of vdbeapi.c *********************************************/
70417 /************** Begin file vdbetrace.c ***************************************/
70418 /*
70419 ** 2009 November 25
70420 **
70421 ** The author disclaims copyright to this source code.  In place of
70422 ** a legal notice, here is a blessing:
70423 **
70424 **    May you do good and not evil.
70425 **    May you find forgiveness for yourself and forgive others.
70426 **    May you share freely, never taking more than you give.
70427 **
70428 *************************************************************************
70429 **
70430 ** This file contains code used to insert the values of host parameters
70431 ** (aka "wildcards") into the SQL text output by sqlite3_trace().
70432 **
70433 ** The Vdbe parse-tree explainer is also found here.
70434 */
70435
70436 #ifndef SQLITE_OMIT_TRACE
70437
70438 /*
70439 ** zSql is a zero-terminated string of UTF-8 SQL text.  Return the number of
70440 ** bytes in this text up to but excluding the first character in
70441 ** a host parameter.  If the text contains no host parameters, return
70442 ** the total number of bytes in the text.
70443 */
70444 static int findNextHostParameter(const char *zSql, int *pnToken){
70445   int tokenType;
70446   int nTotal = 0;
70447   int n;
70448
70449   *pnToken = 0;
70450   while( zSql[0] ){
70451     n = sqlite3GetToken((u8*)zSql, &tokenType);
70452     assert( n>0 && tokenType!=TK_ILLEGAL );
70453     if( tokenType==TK_VARIABLE ){
70454       *pnToken = n;
70455       break;
70456     }
70457     nTotal += n;
70458     zSql += n;
70459   }
70460   return nTotal;
70461 }
70462
70463 /*
70464 ** This function returns a pointer to a nul-terminated string in memory
70465 ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
70466 ** string contains a copy of zRawSql but with host parameters expanded to 
70467 ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1, 
70468 ** then the returned string holds a copy of zRawSql with "-- " prepended
70469 ** to each line of text.
70470 **
70471 ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
70472 ** then long strings and blobs are truncated to that many bytes.  This
70473 ** can be used to prevent unreasonably large trace strings when dealing
70474 ** with large (multi-megabyte) strings and blobs.
70475 **
70476 ** The calling function is responsible for making sure the memory returned
70477 ** is eventually freed.
70478 **
70479 ** ALGORITHM:  Scan the input string looking for host parameters in any of
70480 ** these forms:  ?, ?N, $A, @A, :A.  Take care to avoid text within
70481 ** string literals, quoted identifier names, and comments.  For text forms,
70482 ** the host parameter index is found by scanning the prepared
70483 ** statement for the corresponding OP_Variable opcode.  Once the host
70484 ** parameter index is known, locate the value in p->aVar[].  Then render
70485 ** the value as a literal in place of the host parameter name.
70486 */
70487 SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
70488   Vdbe *p,                 /* The prepared statement being evaluated */
70489   const char *zRawSql      /* Raw text of the SQL statement */
70490 ){
70491   sqlite3 *db;             /* The database connection */
70492   int idx = 0;             /* Index of a host parameter */
70493   int nextIndex = 1;       /* Index of next ? host parameter */
70494   int n;                   /* Length of a token prefix */
70495   int nToken;              /* Length of the parameter token */
70496   int i;                   /* Loop counter */
70497   Mem *pVar;               /* Value of a host parameter */
70498   StrAccum out;            /* Accumulate the output here */
70499   char zBase[100];         /* Initial working space */
70500
70501   db = p->db;
70502   sqlite3StrAccumInit(&out, zBase, sizeof(zBase), 
70503                       db->aLimit[SQLITE_LIMIT_LENGTH]);
70504   out.db = db;
70505   if( db->nVdbeExec>1 ){
70506     while( *zRawSql ){
70507       const char *zStart = zRawSql;
70508       while( *(zRawSql++)!='\n' && *zRawSql );
70509       sqlite3StrAccumAppend(&out, "-- ", 3);
70510       assert( (zRawSql - zStart) > 0 );
70511       sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
70512     }
70513   }else{
70514     while( zRawSql[0] ){
70515       n = findNextHostParameter(zRawSql, &nToken);
70516       assert( n>0 );
70517       sqlite3StrAccumAppend(&out, zRawSql, n);
70518       zRawSql += n;
70519       assert( zRawSql[0] || nToken==0 );
70520       if( nToken==0 ) break;
70521       if( zRawSql[0]=='?' ){
70522         if( nToken>1 ){
70523           assert( sqlite3Isdigit(zRawSql[1]) );
70524           sqlite3GetInt32(&zRawSql[1], &idx);
70525         }else{
70526           idx = nextIndex;
70527         }
70528       }else{
70529         assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
70530         testcase( zRawSql[0]==':' );
70531         testcase( zRawSql[0]=='$' );
70532         testcase( zRawSql[0]=='@' );
70533         idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
70534         assert( idx>0 );
70535       }
70536       zRawSql += nToken;
70537       nextIndex = idx + 1;
70538       assert( idx>0 && idx<=p->nVar );
70539       pVar = &p->aVar[idx-1];
70540       if( pVar->flags & MEM_Null ){
70541         sqlite3StrAccumAppend(&out, "NULL", 4);
70542       }else if( pVar->flags & MEM_Int ){
70543         sqlite3XPrintf(&out, 0, "%lld", pVar->u.i);
70544       }else if( pVar->flags & MEM_Real ){
70545         sqlite3XPrintf(&out, 0, "%!.15g", pVar->u.r);
70546       }else if( pVar->flags & MEM_Str ){
70547         int nOut;  /* Number of bytes of the string text to include in output */
70548 #ifndef SQLITE_OMIT_UTF16
70549         u8 enc = ENC(db);
70550         Mem utf8;
70551         if( enc!=SQLITE_UTF8 ){
70552           memset(&utf8, 0, sizeof(utf8));
70553           utf8.db = db;
70554           sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
70555           sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
70556           pVar = &utf8;
70557         }
70558 #endif
70559         nOut = pVar->n;
70560 #ifdef SQLITE_TRACE_SIZE_LIMIT
70561         if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
70562           nOut = SQLITE_TRACE_SIZE_LIMIT;
70563           while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
70564         }
70565 #endif    
70566         sqlite3XPrintf(&out, 0, "'%.*q'", nOut, pVar->z);
70567 #ifdef SQLITE_TRACE_SIZE_LIMIT
70568         if( nOut<pVar->n ){
70569           sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
70570         }
70571 #endif
70572 #ifndef SQLITE_OMIT_UTF16
70573         if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
70574 #endif
70575       }else if( pVar->flags & MEM_Zero ){
70576         sqlite3XPrintf(&out, 0, "zeroblob(%d)", pVar->u.nZero);
70577       }else{
70578         int nOut;  /* Number of bytes of the blob to include in output */
70579         assert( pVar->flags & MEM_Blob );
70580         sqlite3StrAccumAppend(&out, "x'", 2);
70581         nOut = pVar->n;
70582 #ifdef SQLITE_TRACE_SIZE_LIMIT
70583         if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
70584 #endif
70585         for(i=0; i<nOut; i++){
70586           sqlite3XPrintf(&out, 0, "%02x", pVar->z[i]&0xff);
70587         }
70588         sqlite3StrAccumAppend(&out, "'", 1);
70589 #ifdef SQLITE_TRACE_SIZE_LIMIT
70590         if( nOut<pVar->n ){
70591           sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
70592         }
70593 #endif
70594       }
70595     }
70596   }
70597   return sqlite3StrAccumFinish(&out);
70598 }
70599
70600 #endif /* #ifndef SQLITE_OMIT_TRACE */
70601
70602 /************** End of vdbetrace.c *******************************************/
70603 /************** Begin file vdbe.c ********************************************/
70604 /*
70605 ** 2001 September 15
70606 **
70607 ** The author disclaims copyright to this source code.  In place of
70608 ** a legal notice, here is a blessing:
70609 **
70610 **    May you do good and not evil.
70611 **    May you find forgiveness for yourself and forgive others.
70612 **    May you share freely, never taking more than you give.
70613 **
70614 *************************************************************************
70615 ** The code in this file implements the function that runs the
70616 ** bytecode of a prepared statement.
70617 **
70618 ** Various scripts scan this source file in order to generate HTML
70619 ** documentation, headers files, or other derived files.  The formatting
70620 ** of the code in this file is, therefore, important.  See other comments
70621 ** in this file for details.  If in doubt, do not deviate from existing
70622 ** commenting and indentation practices when changing or adding code.
70623 */
70624
70625 /*
70626 ** Invoke this macro on memory cells just prior to changing the
70627 ** value of the cell.  This macro verifies that shallow copies are
70628 ** not misused.  A shallow copy of a string or blob just copies a
70629 ** pointer to the string or blob, not the content.  If the original
70630 ** is changed while the copy is still in use, the string or blob might
70631 ** be changed out from under the copy.  This macro verifies that nothing
70632 ** like that ever happens.
70633 */
70634 #ifdef SQLITE_DEBUG
70635 # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
70636 #else
70637 # define memAboutToChange(P,M)
70638 #endif
70639
70640 /*
70641 ** The following global variable is incremented every time a cursor
70642 ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes.  The test
70643 ** procedures use this information to make sure that indices are
70644 ** working correctly.  This variable has no function other than to
70645 ** help verify the correct operation of the library.
70646 */
70647 #ifdef SQLITE_TEST
70648 SQLITE_API int sqlite3_search_count = 0;
70649 #endif
70650
70651 /*
70652 ** When this global variable is positive, it gets decremented once before
70653 ** each instruction in the VDBE.  When it reaches zero, the u1.isInterrupted
70654 ** field of the sqlite3 structure is set in order to simulate an interrupt.
70655 **
70656 ** This facility is used for testing purposes only.  It does not function
70657 ** in an ordinary build.
70658 */
70659 #ifdef SQLITE_TEST
70660 SQLITE_API int sqlite3_interrupt_count = 0;
70661 #endif
70662
70663 /*
70664 ** The next global variable is incremented each type the OP_Sort opcode
70665 ** is executed.  The test procedures use this information to make sure that
70666 ** sorting is occurring or not occurring at appropriate times.   This variable
70667 ** has no function other than to help verify the correct operation of the
70668 ** library.
70669 */
70670 #ifdef SQLITE_TEST
70671 SQLITE_API int sqlite3_sort_count = 0;
70672 #endif
70673
70674 /*
70675 ** The next global variable records the size of the largest MEM_Blob
70676 ** or MEM_Str that has been used by a VDBE opcode.  The test procedures
70677 ** use this information to make sure that the zero-blob functionality
70678 ** is working correctly.   This variable has no function other than to
70679 ** help verify the correct operation of the library.
70680 */
70681 #ifdef SQLITE_TEST
70682 SQLITE_API int sqlite3_max_blobsize = 0;
70683 static void updateMaxBlobsize(Mem *p){
70684   if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
70685     sqlite3_max_blobsize = p->n;
70686   }
70687 }
70688 #endif
70689
70690 /*
70691 ** The next global variable is incremented each time the OP_Found opcode
70692 ** is executed. This is used to test whether or not the foreign key
70693 ** operation implemented using OP_FkIsZero is working. This variable
70694 ** has no function other than to help verify the correct operation of the
70695 ** library.
70696 */
70697 #ifdef SQLITE_TEST
70698 SQLITE_API int sqlite3_found_count = 0;
70699 #endif
70700
70701 /*
70702 ** Test a register to see if it exceeds the current maximum blob size.
70703 ** If it does, record the new maximum blob size.
70704 */
70705 #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
70706 # define UPDATE_MAX_BLOBSIZE(P)  updateMaxBlobsize(P)
70707 #else
70708 # define UPDATE_MAX_BLOBSIZE(P)
70709 #endif
70710
70711 /*
70712 ** Invoke the VDBE coverage callback, if that callback is defined.  This
70713 ** feature is used for test suite validation only and does not appear an
70714 ** production builds.
70715 **
70716 ** M is an integer, 2 or 3, that indices how many different ways the
70717 ** branch can go.  It is usually 2.  "I" is the direction the branch
70718 ** goes.  0 means falls through.  1 means branch is taken.  2 means the
70719 ** second alternative branch is taken.
70720 **
70721 ** iSrcLine is the source code line (from the __LINE__ macro) that
70722 ** generated the VDBE instruction.  This instrumentation assumes that all
70723 ** source code is in a single file (the amalgamation).  Special values 1
70724 ** and 2 for the iSrcLine parameter mean that this particular branch is
70725 ** always taken or never taken, respectively.
70726 */
70727 #if !defined(SQLITE_VDBE_COVERAGE)
70728 # define VdbeBranchTaken(I,M)
70729 #else
70730 # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
70731   static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
70732     if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
70733       M = iSrcLine;
70734       /* Assert the truth of VdbeCoverageAlwaysTaken() and 
70735       ** VdbeCoverageNeverTaken() */
70736       assert( (M & I)==I );
70737     }else{
70738       if( sqlite3GlobalConfig.xVdbeBranch==0 ) return;  /*NO_TEST*/
70739       sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
70740                                       iSrcLine,I,M);
70741     }
70742   }
70743 #endif
70744
70745 /*
70746 ** Convert the given register into a string if it isn't one
70747 ** already. Return non-zero if a malloc() fails.
70748 */
70749 #define Stringify(P, enc) \
70750    if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
70751      { goto no_mem; }
70752
70753 /*
70754 ** An ephemeral string value (signified by the MEM_Ephem flag) contains
70755 ** a pointer to a dynamically allocated string where some other entity
70756 ** is responsible for deallocating that string.  Because the register
70757 ** does not control the string, it might be deleted without the register
70758 ** knowing it.
70759 **
70760 ** This routine converts an ephemeral string into a dynamically allocated
70761 ** string that the register itself controls.  In other words, it
70762 ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
70763 */
70764 #define Deephemeralize(P) \
70765    if( ((P)->flags&MEM_Ephem)!=0 \
70766        && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
70767
70768 /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
70769 #define isSorter(x) ((x)->pSorter!=0)
70770
70771 /*
70772 ** Allocate VdbeCursor number iCur.  Return a pointer to it.  Return NULL
70773 ** if we run out of memory.
70774 */
70775 static VdbeCursor *allocateCursor(
70776   Vdbe *p,              /* The virtual machine */
70777   int iCur,             /* Index of the new VdbeCursor */
70778   int nField,           /* Number of fields in the table or index */
70779   int iDb,              /* Database the cursor belongs to, or -1 */
70780   int isBtreeCursor     /* True for B-Tree.  False for pseudo-table or vtab */
70781 ){
70782   /* Find the memory cell that will be used to store the blob of memory
70783   ** required for this VdbeCursor structure. It is convenient to use a 
70784   ** vdbe memory cell to manage the memory allocation required for a
70785   ** VdbeCursor structure for the following reasons:
70786   **
70787   **   * Sometimes cursor numbers are used for a couple of different
70788   **     purposes in a vdbe program. The different uses might require
70789   **     different sized allocations. Memory cells provide growable
70790   **     allocations.
70791   **
70792   **   * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
70793   **     be freed lazily via the sqlite3_release_memory() API. This
70794   **     minimizes the number of malloc calls made by the system.
70795   **
70796   ** Memory cells for cursors are allocated at the top of the address
70797   ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
70798   ** cursor 1 is managed by memory cell (p->nMem-1), etc.
70799   */
70800   Mem *pMem = &p->aMem[p->nMem-iCur];
70801
70802   int nByte;
70803   VdbeCursor *pCx = 0;
70804   nByte = 
70805       ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField + 
70806       (isBtreeCursor?sqlite3BtreeCursorSize():0);
70807
70808   assert( iCur<p->nCursor );
70809   if( p->apCsr[iCur] ){
70810     sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
70811     p->apCsr[iCur] = 0;
70812   }
70813   if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
70814     p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
70815     memset(pCx, 0, sizeof(VdbeCursor));
70816     pCx->iDb = iDb;
70817     pCx->nField = nField;
70818     pCx->aOffset = &pCx->aType[nField];
70819     if( isBtreeCursor ){
70820       pCx->pCursor = (BtCursor*)
70821           &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
70822       sqlite3BtreeCursorZero(pCx->pCursor);
70823     }
70824   }
70825   return pCx;
70826 }
70827
70828 /*
70829 ** Try to convert a value into a numeric representation if we can
70830 ** do so without loss of information.  In other words, if the string
70831 ** looks like a number, convert it into a number.  If it does not
70832 ** look like a number, leave it alone.
70833 **
70834 ** If the bTryForInt flag is true, then extra effort is made to give
70835 ** an integer representation.  Strings that look like floating point
70836 ** values but which have no fractional component (example: '48.00')
70837 ** will have a MEM_Int representation when bTryForInt is true.
70838 **
70839 ** If bTryForInt is false, then if the input string contains a decimal
70840 ** point or exponential notation, the result is only MEM_Real, even
70841 ** if there is an exact integer representation of the quantity.
70842 */
70843 static void applyNumericAffinity(Mem *pRec, int bTryForInt){
70844   double rValue;
70845   i64 iValue;
70846   u8 enc = pRec->enc;
70847   assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
70848   if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
70849   if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
70850     pRec->u.i = iValue;
70851     pRec->flags |= MEM_Int;
70852   }else{
70853     pRec->u.r = rValue;
70854     pRec->flags |= MEM_Real;
70855     if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
70856   }
70857 }
70858
70859 /*
70860 ** Processing is determine by the affinity parameter:
70861 **
70862 ** SQLITE_AFF_INTEGER:
70863 ** SQLITE_AFF_REAL:
70864 ** SQLITE_AFF_NUMERIC:
70865 **    Try to convert pRec to an integer representation or a 
70866 **    floating-point representation if an integer representation
70867 **    is not possible.  Note that the integer representation is
70868 **    always preferred, even if the affinity is REAL, because
70869 **    an integer representation is more space efficient on disk.
70870 **
70871 ** SQLITE_AFF_TEXT:
70872 **    Convert pRec to a text representation.
70873 **
70874 ** SQLITE_AFF_NONE:
70875 **    No-op.  pRec is unchanged.
70876 */
70877 static void applyAffinity(
70878   Mem *pRec,          /* The value to apply affinity to */
70879   char affinity,      /* The affinity to be applied */
70880   u8 enc              /* Use this text encoding */
70881 ){
70882   if( affinity>=SQLITE_AFF_NUMERIC ){
70883     assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
70884              || affinity==SQLITE_AFF_NUMERIC );
70885     if( (pRec->flags & MEM_Int)==0 ){
70886       if( (pRec->flags & MEM_Real)==0 ){
70887         if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
70888       }else{
70889         sqlite3VdbeIntegerAffinity(pRec);
70890       }
70891     }
70892   }else if( affinity==SQLITE_AFF_TEXT ){
70893     /* Only attempt the conversion to TEXT if there is an integer or real
70894     ** representation (blob and NULL do not get converted) but no string
70895     ** representation.
70896     */
70897     if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
70898       sqlite3VdbeMemStringify(pRec, enc, 1);
70899     }
70900   }
70901 }
70902
70903 /*
70904 ** Try to convert the type of a function argument or a result column
70905 ** into a numeric representation.  Use either INTEGER or REAL whichever
70906 ** is appropriate.  But only do the conversion if it is possible without
70907 ** loss of information and return the revised type of the argument.
70908 */
70909 SQLITE_API int SQLITE_STDCALL sqlite3_value_numeric_type(sqlite3_value *pVal){
70910   int eType = sqlite3_value_type(pVal);
70911   if( eType==SQLITE_TEXT ){
70912     Mem *pMem = (Mem*)pVal;
70913     applyNumericAffinity(pMem, 0);
70914     eType = sqlite3_value_type(pVal);
70915   }
70916   return eType;
70917 }
70918
70919 /*
70920 ** Exported version of applyAffinity(). This one works on sqlite3_value*, 
70921 ** not the internal Mem* type.
70922 */
70923 SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
70924   sqlite3_value *pVal, 
70925   u8 affinity, 
70926   u8 enc
70927 ){
70928   applyAffinity((Mem *)pVal, affinity, enc);
70929 }
70930
70931 /*
70932 ** pMem currently only holds a string type (or maybe a BLOB that we can
70933 ** interpret as a string if we want to).  Compute its corresponding
70934 ** numeric type, if has one.  Set the pMem->u.r and pMem->u.i fields
70935 ** accordingly.
70936 */
70937 static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
70938   assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
70939   assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
70940   if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
70941     return 0;
70942   }
70943   if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
70944     return MEM_Int;
70945   }
70946   return MEM_Real;
70947 }
70948
70949 /*
70950 ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
70951 ** none.  
70952 **
70953 ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
70954 ** But it does set pMem->u.r and pMem->u.i appropriately.
70955 */
70956 static u16 numericType(Mem *pMem){
70957   if( pMem->flags & (MEM_Int|MEM_Real) ){
70958     return pMem->flags & (MEM_Int|MEM_Real);
70959   }
70960   if( pMem->flags & (MEM_Str|MEM_Blob) ){
70961     return computeNumericType(pMem);
70962   }
70963   return 0;
70964 }
70965
70966 #ifdef SQLITE_DEBUG
70967 /*
70968 ** Write a nice string representation of the contents of cell pMem
70969 ** into buffer zBuf, length nBuf.
70970 */
70971 SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
70972   char *zCsr = zBuf;
70973   int f = pMem->flags;
70974
70975   static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
70976
70977   if( f&MEM_Blob ){
70978     int i;
70979     char c;
70980     if( f & MEM_Dyn ){
70981       c = 'z';
70982       assert( (f & (MEM_Static|MEM_Ephem))==0 );
70983     }else if( f & MEM_Static ){
70984       c = 't';
70985       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
70986     }else if( f & MEM_Ephem ){
70987       c = 'e';
70988       assert( (f & (MEM_Static|MEM_Dyn))==0 );
70989     }else{
70990       c = 's';
70991     }
70992
70993     sqlite3_snprintf(100, zCsr, "%c", c);
70994     zCsr += sqlite3Strlen30(zCsr);
70995     sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
70996     zCsr += sqlite3Strlen30(zCsr);
70997     for(i=0; i<16 && i<pMem->n; i++){
70998       sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
70999       zCsr += sqlite3Strlen30(zCsr);
71000     }
71001     for(i=0; i<16 && i<pMem->n; i++){
71002       char z = pMem->z[i];
71003       if( z<32 || z>126 ) *zCsr++ = '.';
71004       else *zCsr++ = z;
71005     }
71006
71007     sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
71008     zCsr += sqlite3Strlen30(zCsr);
71009     if( f & MEM_Zero ){
71010       sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
71011       zCsr += sqlite3Strlen30(zCsr);
71012     }
71013     *zCsr = '\0';
71014   }else if( f & MEM_Str ){
71015     int j, k;
71016     zBuf[0] = ' ';
71017     if( f & MEM_Dyn ){
71018       zBuf[1] = 'z';
71019       assert( (f & (MEM_Static|MEM_Ephem))==0 );
71020     }else if( f & MEM_Static ){
71021       zBuf[1] = 't';
71022       assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
71023     }else if( f & MEM_Ephem ){
71024       zBuf[1] = 'e';
71025       assert( (f & (MEM_Static|MEM_Dyn))==0 );
71026     }else{
71027       zBuf[1] = 's';
71028     }
71029     k = 2;
71030     sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
71031     k += sqlite3Strlen30(&zBuf[k]);
71032     zBuf[k++] = '[';
71033     for(j=0; j<15 && j<pMem->n; j++){
71034       u8 c = pMem->z[j];
71035       if( c>=0x20 && c<0x7f ){
71036         zBuf[k++] = c;
71037       }else{
71038         zBuf[k++] = '.';
71039       }
71040     }
71041     zBuf[k++] = ']';
71042     sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
71043     k += sqlite3Strlen30(&zBuf[k]);
71044     zBuf[k++] = 0;
71045   }
71046 }
71047 #endif
71048
71049 #ifdef SQLITE_DEBUG
71050 /*
71051 ** Print the value of a register for tracing purposes:
71052 */
71053 static void memTracePrint(Mem *p){
71054   if( p->flags & MEM_Undefined ){
71055     printf(" undefined");
71056   }else if( p->flags & MEM_Null ){
71057     printf(" NULL");
71058   }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
71059     printf(" si:%lld", p->u.i);
71060   }else if( p->flags & MEM_Int ){
71061     printf(" i:%lld", p->u.i);
71062 #ifndef SQLITE_OMIT_FLOATING_POINT
71063   }else if( p->flags & MEM_Real ){
71064     printf(" r:%g", p->u.r);
71065 #endif
71066   }else if( p->flags & MEM_RowSet ){
71067     printf(" (rowset)");
71068   }else{
71069     char zBuf[200];
71070     sqlite3VdbeMemPrettyPrint(p, zBuf);
71071     printf(" %s", zBuf);
71072   }
71073 }
71074 static void registerTrace(int iReg, Mem *p){
71075   printf("REG[%d] = ", iReg);
71076   memTracePrint(p);
71077   printf("\n");
71078 }
71079 #endif
71080
71081 #ifdef SQLITE_DEBUG
71082 #  define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
71083 #else
71084 #  define REGISTER_TRACE(R,M)
71085 #endif
71086
71087
71088 #ifdef VDBE_PROFILE
71089
71090 /* 
71091 ** hwtime.h contains inline assembler code for implementing 
71092 ** high-performance timing routines.
71093 */
71094 /************** Include hwtime.h in the middle of vdbe.c *********************/
71095 /************** Begin file hwtime.h ******************************************/
71096 /*
71097 ** 2008 May 27
71098 **
71099 ** The author disclaims copyright to this source code.  In place of
71100 ** a legal notice, here is a blessing:
71101 **
71102 **    May you do good and not evil.
71103 **    May you find forgiveness for yourself and forgive others.
71104 **    May you share freely, never taking more than you give.
71105 **
71106 ******************************************************************************
71107 **
71108 ** This file contains inline asm code for retrieving "high-performance"
71109 ** counters for x86 class CPUs.
71110 */
71111 #ifndef _HWTIME_H_
71112 #define _HWTIME_H_
71113
71114 /*
71115 ** The following routine only works on pentium-class (or newer) processors.
71116 ** It uses the RDTSC opcode to read the cycle count value out of the
71117 ** processor and returns that value.  This can be used for high-res
71118 ** profiling.
71119 */
71120 #if (defined(__GNUC__) || defined(_MSC_VER)) && \
71121       (defined(i386) || defined(__i386__) || defined(_M_IX86))
71122
71123   #if defined(__GNUC__)
71124
71125   __inline__ sqlite_uint64 sqlite3Hwtime(void){
71126      unsigned int lo, hi;
71127      __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
71128      return (sqlite_uint64)hi << 32 | lo;
71129   }
71130
71131   #elif defined(_MSC_VER)
71132
71133   __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
71134      __asm {
71135         rdtsc
71136         ret       ; return value at EDX:EAX
71137      }
71138   }
71139
71140   #endif
71141
71142 #elif (defined(__GNUC__) && defined(__x86_64__))
71143
71144   __inline__ sqlite_uint64 sqlite3Hwtime(void){
71145       unsigned long val;
71146       __asm__ __volatile__ ("rdtsc" : "=A" (val));
71147       return val;
71148   }
71149  
71150 #elif (defined(__GNUC__) && defined(__ppc__))
71151
71152   __inline__ sqlite_uint64 sqlite3Hwtime(void){
71153       unsigned long long retval;
71154       unsigned long junk;
71155       __asm__ __volatile__ ("\n\
71156           1:      mftbu   %1\n\
71157                   mftb    %L0\n\
71158                   mftbu   %0\n\
71159                   cmpw    %0,%1\n\
71160                   bne     1b"
71161                   : "=r" (retval), "=r" (junk));
71162       return retval;
71163   }
71164
71165 #else
71166
71167   #error Need implementation of sqlite3Hwtime() for your platform.
71168
71169   /*
71170   ** To compile without implementing sqlite3Hwtime() for your platform,
71171   ** you can remove the above #error and use the following
71172   ** stub function.  You will lose timing support for many
71173   ** of the debugging and testing utilities, but it should at
71174   ** least compile and run.
71175   */
71176 SQLITE_PRIVATE   sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
71177
71178 #endif
71179
71180 #endif /* !defined(_HWTIME_H_) */
71181
71182 /************** End of hwtime.h **********************************************/
71183 /************** Continuing where we left off in vdbe.c ***********************/
71184
71185 #endif
71186
71187 #ifndef NDEBUG
71188 /*
71189 ** This function is only called from within an assert() expression. It
71190 ** checks that the sqlite3.nTransaction variable is correctly set to
71191 ** the number of non-transaction savepoints currently in the 
71192 ** linked list starting at sqlite3.pSavepoint.
71193 ** 
71194 ** Usage:
71195 **
71196 **     assert( checkSavepointCount(db) );
71197 */
71198 static int checkSavepointCount(sqlite3 *db){
71199   int n = 0;
71200   Savepoint *p;
71201   for(p=db->pSavepoint; p; p=p->pNext) n++;
71202   assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
71203   return 1;
71204 }
71205 #endif
71206
71207
71208 /*
71209 ** Execute as much of a VDBE program as we can.
71210 ** This is the core of sqlite3_step().  
71211 */
71212 SQLITE_PRIVATE int sqlite3VdbeExec(
71213   Vdbe *p                    /* The VDBE */
71214 ){
71215   int pc=0;                  /* The program counter */
71216   Op *aOp = p->aOp;          /* Copy of p->aOp */
71217   Op *pOp;                   /* Current operation */
71218   int rc = SQLITE_OK;        /* Value to return */
71219   sqlite3 *db = p->db;       /* The database */
71220   u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
71221   u8 encoding = ENC(db);     /* The database encoding */
71222   int iCompare = 0;          /* Result of last OP_Compare operation */
71223   unsigned nVmStep = 0;      /* Number of virtual machine steps */
71224 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
71225   unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
71226 #endif
71227   Mem *aMem = p->aMem;       /* Copy of p->aMem */
71228   Mem *pIn1 = 0;             /* 1st input operand */
71229   Mem *pIn2 = 0;             /* 2nd input operand */
71230   Mem *pIn3 = 0;             /* 3rd input operand */
71231   Mem *pOut = 0;             /* Output operand */
71232   int *aPermute = 0;         /* Permutation of columns for OP_Compare */
71233   i64 lastRowid = db->lastRowid;  /* Saved value of the last insert ROWID */
71234 #ifdef VDBE_PROFILE
71235   u64 start;                 /* CPU clock count at start of opcode */
71236 #endif
71237   /*** INSERT STACK UNION HERE ***/
71238
71239   assert( p->magic==VDBE_MAGIC_RUN );  /* sqlite3_step() verifies this */
71240   sqlite3VdbeEnter(p);
71241   if( p->rc==SQLITE_NOMEM ){
71242     /* This happens if a malloc() inside a call to sqlite3_column_text() or
71243     ** sqlite3_column_text16() failed.  */
71244     goto no_mem;
71245   }
71246   assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
71247   assert( p->bIsReader || p->readOnly!=0 );
71248   p->rc = SQLITE_OK;
71249   p->iCurrentTime = 0;
71250   assert( p->explain==0 );
71251   p->pResultSet = 0;
71252   db->busyHandler.nBusy = 0;
71253   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
71254   sqlite3VdbeIOTraceSql(p);
71255 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
71256   if( db->xProgress ){
71257     assert( 0 < db->nProgressOps );
71258     nProgressLimit = (unsigned)p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
71259     if( nProgressLimit==0 ){
71260       nProgressLimit = db->nProgressOps;
71261     }else{
71262       nProgressLimit %= (unsigned)db->nProgressOps;
71263     }
71264   }
71265 #endif
71266 #ifdef SQLITE_DEBUG
71267   sqlite3BeginBenignMalloc();
71268   if( p->pc==0
71269    && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
71270   ){
71271     int i;
71272     int once = 1;
71273     sqlite3VdbePrintSql(p);
71274     if( p->db->flags & SQLITE_VdbeListing ){
71275       printf("VDBE Program Listing:\n");
71276       for(i=0; i<p->nOp; i++){
71277         sqlite3VdbePrintOp(stdout, i, &aOp[i]);
71278       }
71279     }
71280     if( p->db->flags & SQLITE_VdbeEQP ){
71281       for(i=0; i<p->nOp; i++){
71282         if( aOp[i].opcode==OP_Explain ){
71283           if( once ) printf("VDBE Query Plan:\n");
71284           printf("%s\n", aOp[i].p4.z);
71285           once = 0;
71286         }
71287       }
71288     }
71289     if( p->db->flags & SQLITE_VdbeTrace )  printf("VDBE Trace:\n");
71290   }
71291   sqlite3EndBenignMalloc();
71292 #endif
71293   for(pc=p->pc; rc==SQLITE_OK; pc++){
71294     assert( pc>=0 && pc<p->nOp );
71295     if( db->mallocFailed ) goto no_mem;
71296 #ifdef VDBE_PROFILE
71297     start = sqlite3Hwtime();
71298 #endif
71299     nVmStep++;
71300     pOp = &aOp[pc];
71301 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
71302     if( p->anExec ) p->anExec[pc]++;
71303 #endif
71304
71305     /* Only allow tracing if SQLITE_DEBUG is defined.
71306     */
71307 #ifdef SQLITE_DEBUG
71308     if( db->flags & SQLITE_VdbeTrace ){
71309       sqlite3VdbePrintOp(stdout, pc, pOp);
71310     }
71311 #endif
71312       
71313
71314     /* Check to see if we need to simulate an interrupt.  This only happens
71315     ** if we have a special test build.
71316     */
71317 #ifdef SQLITE_TEST
71318     if( sqlite3_interrupt_count>0 ){
71319       sqlite3_interrupt_count--;
71320       if( sqlite3_interrupt_count==0 ){
71321         sqlite3_interrupt(db);
71322       }
71323     }
71324 #endif
71325
71326     /* On any opcode with the "out2-prerelease" tag, free any
71327     ** external allocations out of mem[p2] and set mem[p2] to be
71328     ** an undefined integer.  Opcodes will either fill in the integer
71329     ** value or convert mem[p2] to a different type.
71330     */
71331     assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
71332     if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
71333       assert( pOp->p2>0 );
71334       assert( pOp->p2<=(p->nMem-p->nCursor) );
71335       pOut = &aMem[pOp->p2];
71336       memAboutToChange(p, pOut);
71337       if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut);
71338       pOut->flags = MEM_Int;
71339     }
71340
71341     /* Sanity checking on other operands */
71342 #ifdef SQLITE_DEBUG
71343     if( (pOp->opflags & OPFLG_IN1)!=0 ){
71344       assert( pOp->p1>0 );
71345       assert( pOp->p1<=(p->nMem-p->nCursor) );
71346       assert( memIsValid(&aMem[pOp->p1]) );
71347       assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
71348       REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
71349     }
71350     if( (pOp->opflags & OPFLG_IN2)!=0 ){
71351       assert( pOp->p2>0 );
71352       assert( pOp->p2<=(p->nMem-p->nCursor) );
71353       assert( memIsValid(&aMem[pOp->p2]) );
71354       assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
71355       REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
71356     }
71357     if( (pOp->opflags & OPFLG_IN3)!=0 ){
71358       assert( pOp->p3>0 );
71359       assert( pOp->p3<=(p->nMem-p->nCursor) );
71360       assert( memIsValid(&aMem[pOp->p3]) );
71361       assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
71362       REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
71363     }
71364     if( (pOp->opflags & OPFLG_OUT2)!=0 ){
71365       assert( pOp->p2>0 );
71366       assert( pOp->p2<=(p->nMem-p->nCursor) );
71367       memAboutToChange(p, &aMem[pOp->p2]);
71368     }
71369     if( (pOp->opflags & OPFLG_OUT3)!=0 ){
71370       assert( pOp->p3>0 );
71371       assert( pOp->p3<=(p->nMem-p->nCursor) );
71372       memAboutToChange(p, &aMem[pOp->p3]);
71373     }
71374 #endif
71375   
71376     switch( pOp->opcode ){
71377
71378 /*****************************************************************************
71379 ** What follows is a massive switch statement where each case implements a
71380 ** separate instruction in the virtual machine.  If we follow the usual
71381 ** indentation conventions, each case should be indented by 6 spaces.  But
71382 ** that is a lot of wasted space on the left margin.  So the code within
71383 ** the switch statement will break with convention and be flush-left. Another
71384 ** big comment (similar to this one) will mark the point in the code where
71385 ** we transition back to normal indentation.
71386 **
71387 ** The formatting of each case is important.  The makefile for SQLite
71388 ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
71389 ** file looking for lines that begin with "case OP_".  The opcodes.h files
71390 ** will be filled with #defines that give unique integer values to each
71391 ** opcode and the opcodes.c file is filled with an array of strings where
71392 ** each string is the symbolic name for the corresponding opcode.  If the
71393 ** case statement is followed by a comment of the form "/# same as ... #/"
71394 ** that comment is used to determine the particular value of the opcode.
71395 **
71396 ** Other keywords in the comment that follows each case are used to
71397 ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
71398 ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3.  See
71399 ** the mkopcodeh.awk script for additional information.
71400 **
71401 ** Documentation about VDBE opcodes is generated by scanning this file
71402 ** for lines of that contain "Opcode:".  That line and all subsequent
71403 ** comment lines are used in the generation of the opcode.html documentation
71404 ** file.
71405 **
71406 ** SUMMARY:
71407 **
71408 **     Formatting is important to scripts that scan this file.
71409 **     Do not deviate from the formatting style currently in use.
71410 **
71411 *****************************************************************************/
71412
71413 /* Opcode:  Goto * P2 * * *
71414 **
71415 ** An unconditional jump to address P2.
71416 ** The next instruction executed will be 
71417 ** the one at index P2 from the beginning of
71418 ** the program.
71419 **
71420 ** The P1 parameter is not actually used by this opcode.  However, it
71421 ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
71422 ** that this Goto is the bottom of a loop and that the lines from P2 down
71423 ** to the current line should be indented for EXPLAIN output.
71424 */
71425 case OP_Goto: {             /* jump */
71426   pc = pOp->p2 - 1;
71427
71428   /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
71429   ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
71430   ** completion.  Check to see if sqlite3_interrupt() has been called
71431   ** or if the progress callback needs to be invoked. 
71432   **
71433   ** This code uses unstructured "goto" statements and does not look clean.
71434   ** But that is not due to sloppy coding habits. The code is written this
71435   ** way for performance, to avoid having to run the interrupt and progress
71436   ** checks on every opcode.  This helps sqlite3_step() to run about 1.5%
71437   ** faster according to "valgrind --tool=cachegrind" */
71438 check_for_interrupt:
71439   if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
71440 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
71441   /* Call the progress callback if it is configured and the required number
71442   ** of VDBE ops have been executed (either since this invocation of
71443   ** sqlite3VdbeExec() or since last time the progress callback was called).
71444   ** If the progress callback returns non-zero, exit the virtual machine with
71445   ** a return code SQLITE_ABORT.
71446   */
71447   if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
71448     assert( db->nProgressOps!=0 );
71449     nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
71450     if( db->xProgress(db->pProgressArg) ){
71451       rc = SQLITE_INTERRUPT;
71452       goto vdbe_error_halt;
71453     }
71454   }
71455 #endif
71456   
71457   break;
71458 }
71459
71460 /* Opcode:  Gosub P1 P2 * * *
71461 **
71462 ** Write the current address onto register P1
71463 ** and then jump to address P2.
71464 */
71465 case OP_Gosub: {            /* jump */
71466   assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
71467   pIn1 = &aMem[pOp->p1];
71468   assert( VdbeMemDynamic(pIn1)==0 );
71469   memAboutToChange(p, pIn1);
71470   pIn1->flags = MEM_Int;
71471   pIn1->u.i = pc;
71472   REGISTER_TRACE(pOp->p1, pIn1);
71473   pc = pOp->p2 - 1;
71474   break;
71475 }
71476
71477 /* Opcode:  Return P1 * * * *
71478 **
71479 ** Jump to the next instruction after the address in register P1.  After
71480 ** the jump, register P1 becomes undefined.
71481 */
71482 case OP_Return: {           /* in1 */
71483   pIn1 = &aMem[pOp->p1];
71484   assert( pIn1->flags==MEM_Int );
71485   pc = (int)pIn1->u.i;
71486   pIn1->flags = MEM_Undefined;
71487   break;
71488 }
71489
71490 /* Opcode: InitCoroutine P1 P2 P3 * *
71491 **
71492 ** Set up register P1 so that it will Yield to the coroutine
71493 ** located at address P3.
71494 **
71495 ** If P2!=0 then the coroutine implementation immediately follows
71496 ** this opcode.  So jump over the coroutine implementation to
71497 ** address P2.
71498 **
71499 ** See also: EndCoroutine
71500 */
71501 case OP_InitCoroutine: {     /* jump */
71502   assert( pOp->p1>0 &&  pOp->p1<=(p->nMem-p->nCursor) );
71503   assert( pOp->p2>=0 && pOp->p2<p->nOp );
71504   assert( pOp->p3>=0 && pOp->p3<p->nOp );
71505   pOut = &aMem[pOp->p1];
71506   assert( !VdbeMemDynamic(pOut) );
71507   pOut->u.i = pOp->p3 - 1;
71508   pOut->flags = MEM_Int;
71509   if( pOp->p2 ) pc = pOp->p2 - 1;
71510   break;
71511 }
71512
71513 /* Opcode:  EndCoroutine P1 * * * *
71514 **
71515 ** The instruction at the address in register P1 is a Yield.
71516 ** Jump to the P2 parameter of that Yield.
71517 ** After the jump, register P1 becomes undefined.
71518 **
71519 ** See also: InitCoroutine
71520 */
71521 case OP_EndCoroutine: {           /* in1 */
71522   VdbeOp *pCaller;
71523   pIn1 = &aMem[pOp->p1];
71524   assert( pIn1->flags==MEM_Int );
71525   assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
71526   pCaller = &aOp[pIn1->u.i];
71527   assert( pCaller->opcode==OP_Yield );
71528   assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
71529   pc = pCaller->p2 - 1;
71530   pIn1->flags = MEM_Undefined;
71531   break;
71532 }
71533
71534 /* Opcode:  Yield P1 P2 * * *
71535 **
71536 ** Swap the program counter with the value in register P1.  This
71537 ** has the effect of yielding to a coroutine.
71538 **
71539 ** If the coroutine that is launched by this instruction ends with
71540 ** Yield or Return then continue to the next instruction.  But if
71541 ** the coroutine launched by this instruction ends with
71542 ** EndCoroutine, then jump to P2 rather than continuing with the
71543 ** next instruction.
71544 **
71545 ** See also: InitCoroutine
71546 */
71547 case OP_Yield: {            /* in1, jump */
71548   int pcDest;
71549   pIn1 = &aMem[pOp->p1];
71550   assert( VdbeMemDynamic(pIn1)==0 );
71551   pIn1->flags = MEM_Int;
71552   pcDest = (int)pIn1->u.i;
71553   pIn1->u.i = pc;
71554   REGISTER_TRACE(pOp->p1, pIn1);
71555   pc = pcDest;
71556   break;
71557 }
71558
71559 /* Opcode:  HaltIfNull  P1 P2 P3 P4 P5
71560 ** Synopsis:  if r[P3]=null halt
71561 **
71562 ** Check the value in register P3.  If it is NULL then Halt using
71563 ** parameter P1, P2, and P4 as if this were a Halt instruction.  If the
71564 ** value in register P3 is not NULL, then this routine is a no-op.
71565 ** The P5 parameter should be 1.
71566 */
71567 case OP_HaltIfNull: {      /* in3 */
71568   pIn3 = &aMem[pOp->p3];
71569   if( (pIn3->flags & MEM_Null)==0 ) break;
71570   /* Fall through into OP_Halt */
71571 }
71572
71573 /* Opcode:  Halt P1 P2 * P4 P5
71574 **
71575 ** Exit immediately.  All open cursors, etc are closed
71576 ** automatically.
71577 **
71578 ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
71579 ** or sqlite3_finalize().  For a normal halt, this should be SQLITE_OK (0).
71580 ** For errors, it can be some other value.  If P1!=0 then P2 will determine
71581 ** whether or not to rollback the current transaction.  Do not rollback
71582 ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback.  If P2==OE_Abort,
71583 ** then back out all changes that have occurred during this execution of the
71584 ** VDBE, but do not rollback the transaction. 
71585 **
71586 ** If P4 is not null then it is an error message string.
71587 **
71588 ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
71589 **
71590 **    0:  (no change)
71591 **    1:  NOT NULL contraint failed: P4
71592 **    2:  UNIQUE constraint failed: P4
71593 **    3:  CHECK constraint failed: P4
71594 **    4:  FOREIGN KEY constraint failed: P4
71595 **
71596 ** If P5 is not zero and P4 is NULL, then everything after the ":" is
71597 ** omitted.
71598 **
71599 ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
71600 ** every program.  So a jump past the last instruction of the program
71601 ** is the same as executing Halt.
71602 */
71603 case OP_Halt: {
71604   const char *zType;
71605   const char *zLogFmt;
71606
71607   if( pOp->p1==SQLITE_OK && p->pFrame ){
71608     /* Halt the sub-program. Return control to the parent frame. */
71609     VdbeFrame *pFrame = p->pFrame;
71610     p->pFrame = pFrame->pParent;
71611     p->nFrame--;
71612     sqlite3VdbeSetChanges(db, p->nChange);
71613     pc = sqlite3VdbeFrameRestore(pFrame);
71614     lastRowid = db->lastRowid;
71615     if( pOp->p2==OE_Ignore ){
71616       /* Instruction pc is the OP_Program that invoked the sub-program 
71617       ** currently being halted. If the p2 instruction of this OP_Halt
71618       ** instruction is set to OE_Ignore, then the sub-program is throwing
71619       ** an IGNORE exception. In this case jump to the address specified
71620       ** as the p2 of the calling OP_Program.  */
71621       pc = p->aOp[pc].p2-1;
71622     }
71623     aOp = p->aOp;
71624     aMem = p->aMem;
71625     break;
71626   }
71627   p->rc = pOp->p1;
71628   p->errorAction = (u8)pOp->p2;
71629   p->pc = pc;
71630   if( p->rc ){
71631     if( pOp->p5 ){
71632       static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
71633                                              "FOREIGN KEY" };
71634       assert( pOp->p5>=1 && pOp->p5<=4 );
71635       testcase( pOp->p5==1 );
71636       testcase( pOp->p5==2 );
71637       testcase( pOp->p5==3 );
71638       testcase( pOp->p5==4 );
71639       zType = azType[pOp->p5-1];
71640     }else{
71641       zType = 0;
71642     }
71643     assert( zType!=0 || pOp->p4.z!=0 );
71644     zLogFmt = "abort at %d in [%s]: %s";
71645     if( zType && pOp->p4.z ){
71646       sqlite3SetString(&p->zErrMsg, db, "%s constraint failed: %s", 
71647                        zType, pOp->p4.z);
71648     }else if( pOp->p4.z ){
71649       sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
71650     }else{
71651       sqlite3SetString(&p->zErrMsg, db, "%s constraint failed", zType);
71652     }
71653     sqlite3_log(pOp->p1, zLogFmt, pc, p->zSql, p->zErrMsg);
71654   }
71655   rc = sqlite3VdbeHalt(p);
71656   assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
71657   if( rc==SQLITE_BUSY ){
71658     p->rc = rc = SQLITE_BUSY;
71659   }else{
71660     assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
71661     assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
71662     rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
71663   }
71664   goto vdbe_return;
71665 }
71666
71667 /* Opcode: Integer P1 P2 * * *
71668 ** Synopsis: r[P2]=P1
71669 **
71670 ** The 32-bit integer value P1 is written into register P2.
71671 */
71672 case OP_Integer: {         /* out2-prerelease */
71673   pOut->u.i = pOp->p1;
71674   break;
71675 }
71676
71677 /* Opcode: Int64 * P2 * P4 *
71678 ** Synopsis: r[P2]=P4
71679 **
71680 ** P4 is a pointer to a 64-bit integer value.
71681 ** Write that value into register P2.
71682 */
71683 case OP_Int64: {           /* out2-prerelease */
71684   assert( pOp->p4.pI64!=0 );
71685   pOut->u.i = *pOp->p4.pI64;
71686   break;
71687 }
71688
71689 #ifndef SQLITE_OMIT_FLOATING_POINT
71690 /* Opcode: Real * P2 * P4 *
71691 ** Synopsis: r[P2]=P4
71692 **
71693 ** P4 is a pointer to a 64-bit floating point value.
71694 ** Write that value into register P2.
71695 */
71696 case OP_Real: {            /* same as TK_FLOAT, out2-prerelease */
71697   pOut->flags = MEM_Real;
71698   assert( !sqlite3IsNaN(*pOp->p4.pReal) );
71699   pOut->u.r = *pOp->p4.pReal;
71700   break;
71701 }
71702 #endif
71703
71704 /* Opcode: String8 * P2 * P4 *
71705 ** Synopsis: r[P2]='P4'
71706 **
71707 ** P4 points to a nul terminated UTF-8 string. This opcode is transformed 
71708 ** into a String opcode before it is executed for the first time.  During
71709 ** this transformation, the length of string P4 is computed and stored
71710 ** as the P1 parameter.
71711 */
71712 case OP_String8: {         /* same as TK_STRING, out2-prerelease */
71713   assert( pOp->p4.z!=0 );
71714   pOp->opcode = OP_String;
71715   pOp->p1 = sqlite3Strlen30(pOp->p4.z);
71716
71717 #ifndef SQLITE_OMIT_UTF16
71718   if( encoding!=SQLITE_UTF8 ){
71719     rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
71720     if( rc==SQLITE_TOOBIG ) goto too_big;
71721     if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
71722     assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
71723     assert( VdbeMemDynamic(pOut)==0 );
71724     pOut->szMalloc = 0;
71725     pOut->flags |= MEM_Static;
71726     if( pOp->p4type==P4_DYNAMIC ){
71727       sqlite3DbFree(db, pOp->p4.z);
71728     }
71729     pOp->p4type = P4_DYNAMIC;
71730     pOp->p4.z = pOut->z;
71731     pOp->p1 = pOut->n;
71732   }
71733 #endif
71734   if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
71735     goto too_big;
71736   }
71737   /* Fall through to the next case, OP_String */
71738 }
71739   
71740 /* Opcode: String P1 P2 P3 P4 P5
71741 ** Synopsis: r[P2]='P4' (len=P1)
71742 **
71743 ** The string value P4 of length P1 (bytes) is stored in register P2.
71744 **
71745 ** If P5!=0 and the content of register P3 is greater than zero, then
71746 ** the datatype of the register P2 is converted to BLOB.  The content is
71747 ** the same sequence of bytes, it is merely interpreted as a BLOB instead
71748 ** of a string, as if it had been CAST.
71749 */
71750 case OP_String: {          /* out2-prerelease */
71751   assert( pOp->p4.z!=0 );
71752   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
71753   pOut->z = pOp->p4.z;
71754   pOut->n = pOp->p1;
71755   pOut->enc = encoding;
71756   UPDATE_MAX_BLOBSIZE(pOut);
71757   if( pOp->p5 ){
71758     assert( pOp->p3>0 );
71759     assert( pOp->p3<=(p->nMem-p->nCursor) );
71760     pIn3 = &aMem[pOp->p3];
71761     assert( pIn3->flags & MEM_Int );
71762     if( pIn3->u.i ) pOut->flags = MEM_Blob|MEM_Static|MEM_Term;
71763   }
71764   break;
71765 }
71766
71767 /* Opcode: Null P1 P2 P3 * *
71768 ** Synopsis:  r[P2..P3]=NULL
71769 **
71770 ** Write a NULL into registers P2.  If P3 greater than P2, then also write
71771 ** NULL into register P3 and every register in between P2 and P3.  If P3
71772 ** is less than P2 (typically P3 is zero) then only register P2 is
71773 ** set to NULL.
71774 **
71775 ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
71776 ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
71777 ** OP_Ne or OP_Eq.
71778 */
71779 case OP_Null: {           /* out2-prerelease */
71780   int cnt;
71781   u16 nullFlag;
71782   cnt = pOp->p3-pOp->p2;
71783   assert( pOp->p3<=(p->nMem-p->nCursor) );
71784   pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
71785   while( cnt>0 ){
71786     pOut++;
71787     memAboutToChange(p, pOut);
71788     sqlite3VdbeMemSetNull(pOut);
71789     pOut->flags = nullFlag;
71790     cnt--;
71791   }
71792   break;
71793 }
71794
71795 /* Opcode: SoftNull P1 * * * *
71796 ** Synopsis:  r[P1]=NULL
71797 **
71798 ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
71799 ** instruction, but do not free any string or blob memory associated with
71800 ** the register, so that if the value was a string or blob that was
71801 ** previously copied using OP_SCopy, the copies will continue to be valid.
71802 */
71803 case OP_SoftNull: {
71804   assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
71805   pOut = &aMem[pOp->p1];
71806   pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
71807   break;
71808 }
71809
71810 /* Opcode: Blob P1 P2 * P4 *
71811 ** Synopsis: r[P2]=P4 (len=P1)
71812 **
71813 ** P4 points to a blob of data P1 bytes long.  Store this
71814 ** blob in register P2.
71815 */
71816 case OP_Blob: {                /* out2-prerelease */
71817   assert( pOp->p1 <= SQLITE_MAX_LENGTH );
71818   sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
71819   pOut->enc = encoding;
71820   UPDATE_MAX_BLOBSIZE(pOut);
71821   break;
71822 }
71823
71824 /* Opcode: Variable P1 P2 * P4 *
71825 ** Synopsis: r[P2]=parameter(P1,P4)
71826 **
71827 ** Transfer the values of bound parameter P1 into register P2
71828 **
71829 ** If the parameter is named, then its name appears in P4.
71830 ** The P4 value is used by sqlite3_bind_parameter_name().
71831 */
71832 case OP_Variable: {            /* out2-prerelease */
71833   Mem *pVar;       /* Value being transferred */
71834
71835   assert( pOp->p1>0 && pOp->p1<=p->nVar );
71836   assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
71837   pVar = &p->aVar[pOp->p1 - 1];
71838   if( sqlite3VdbeMemTooBig(pVar) ){
71839     goto too_big;
71840   }
71841   sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
71842   UPDATE_MAX_BLOBSIZE(pOut);
71843   break;
71844 }
71845
71846 /* Opcode: Move P1 P2 P3 * *
71847 ** Synopsis:  r[P2@P3]=r[P1@P3]
71848 **
71849 ** Move the P3 values in register P1..P1+P3-1 over into
71850 ** registers P2..P2+P3-1.  Registers P1..P1+P3-1 are
71851 ** left holding a NULL.  It is an error for register ranges
71852 ** P1..P1+P3-1 and P2..P2+P3-1 to overlap.  It is an error
71853 ** for P3 to be less than 1.
71854 */
71855 case OP_Move: {
71856   int n;           /* Number of registers left to copy */
71857   int p1;          /* Register to copy from */
71858   int p2;          /* Register to copy to */
71859
71860   n = pOp->p3;
71861   p1 = pOp->p1;
71862   p2 = pOp->p2;
71863   assert( n>0 && p1>0 && p2>0 );
71864   assert( p1+n<=p2 || p2+n<=p1 );
71865
71866   pIn1 = &aMem[p1];
71867   pOut = &aMem[p2];
71868   do{
71869     assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
71870     assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
71871     assert( memIsValid(pIn1) );
71872     memAboutToChange(p, pOut);
71873     sqlite3VdbeMemMove(pOut, pIn1);
71874 #ifdef SQLITE_DEBUG
71875     if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<&aMem[p1+pOp->p3] ){
71876       pOut->pScopyFrom += p1 - pOp->p2;
71877     }
71878 #endif
71879     REGISTER_TRACE(p2++, pOut);
71880     pIn1++;
71881     pOut++;
71882   }while( --n );
71883   break;
71884 }
71885
71886 /* Opcode: Copy P1 P2 P3 * *
71887 ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
71888 **
71889 ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
71890 **
71891 ** This instruction makes a deep copy of the value.  A duplicate
71892 ** is made of any string or blob constant.  See also OP_SCopy.
71893 */
71894 case OP_Copy: {
71895   int n;
71896
71897   n = pOp->p3;
71898   pIn1 = &aMem[pOp->p1];
71899   pOut = &aMem[pOp->p2];
71900   assert( pOut!=pIn1 );
71901   while( 1 ){
71902     sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
71903     Deephemeralize(pOut);
71904 #ifdef SQLITE_DEBUG
71905     pOut->pScopyFrom = 0;
71906 #endif
71907     REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
71908     if( (n--)==0 ) break;
71909     pOut++;
71910     pIn1++;
71911   }
71912   break;
71913 }
71914
71915 /* Opcode: SCopy P1 P2 * * *
71916 ** Synopsis: r[P2]=r[P1]
71917 **
71918 ** Make a shallow copy of register P1 into register P2.
71919 **
71920 ** This instruction makes a shallow copy of the value.  If the value
71921 ** is a string or blob, then the copy is only a pointer to the
71922 ** original and hence if the original changes so will the copy.
71923 ** Worse, if the original is deallocated, the copy becomes invalid.
71924 ** Thus the program must guarantee that the original will not change
71925 ** during the lifetime of the copy.  Use OP_Copy to make a complete
71926 ** copy.
71927 */
71928 case OP_SCopy: {            /* out2 */
71929   pIn1 = &aMem[pOp->p1];
71930   pOut = &aMem[pOp->p2];
71931   assert( pOut!=pIn1 );
71932   sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
71933 #ifdef SQLITE_DEBUG
71934   if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
71935 #endif
71936   break;
71937 }
71938
71939 /* Opcode: ResultRow P1 P2 * * *
71940 ** Synopsis:  output=r[P1@P2]
71941 **
71942 ** The registers P1 through P1+P2-1 contain a single row of
71943 ** results. This opcode causes the sqlite3_step() call to terminate
71944 ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
71945 ** structure to provide access to the r(P1)..r(P1+P2-1) values as
71946 ** the result row.
71947 */
71948 case OP_ResultRow: {
71949   Mem *pMem;
71950   int i;
71951   assert( p->nResColumn==pOp->p2 );
71952   assert( pOp->p1>0 );
71953   assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
71954
71955 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
71956   /* Run the progress counter just before returning.
71957   */
71958   if( db->xProgress!=0
71959    && nVmStep>=nProgressLimit
71960    && db->xProgress(db->pProgressArg)!=0
71961   ){
71962     rc = SQLITE_INTERRUPT;
71963     goto vdbe_error_halt;
71964   }
71965 #endif
71966
71967   /* If this statement has violated immediate foreign key constraints, do
71968   ** not return the number of rows modified. And do not RELEASE the statement
71969   ** transaction. It needs to be rolled back.  */
71970   if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
71971     assert( db->flags&SQLITE_CountRows );
71972     assert( p->usesStmtJournal );
71973     break;
71974   }
71975
71976   /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then 
71977   ** DML statements invoke this opcode to return the number of rows 
71978   ** modified to the user. This is the only way that a VM that
71979   ** opens a statement transaction may invoke this opcode.
71980   **
71981   ** In case this is such a statement, close any statement transaction
71982   ** opened by this VM before returning control to the user. This is to
71983   ** ensure that statement-transactions are always nested, not overlapping.
71984   ** If the open statement-transaction is not closed here, then the user
71985   ** may step another VM that opens its own statement transaction. This
71986   ** may lead to overlapping statement transactions.
71987   **
71988   ** The statement transaction is never a top-level transaction.  Hence
71989   ** the RELEASE call below can never fail.
71990   */
71991   assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
71992   rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
71993   if( NEVER(rc!=SQLITE_OK) ){
71994     break;
71995   }
71996
71997   /* Invalidate all ephemeral cursor row caches */
71998   p->cacheCtr = (p->cacheCtr + 2)|1;
71999
72000   /* Make sure the results of the current row are \000 terminated
72001   ** and have an assigned type.  The results are de-ephemeralized as
72002   ** a side effect.
72003   */
72004   pMem = p->pResultSet = &aMem[pOp->p1];
72005   for(i=0; i<pOp->p2; i++){
72006     assert( memIsValid(&pMem[i]) );
72007     Deephemeralize(&pMem[i]);
72008     assert( (pMem[i].flags & MEM_Ephem)==0
72009             || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
72010     sqlite3VdbeMemNulTerminate(&pMem[i]);
72011     REGISTER_TRACE(pOp->p1+i, &pMem[i]);
72012   }
72013   if( db->mallocFailed ) goto no_mem;
72014
72015   /* Return SQLITE_ROW
72016   */
72017   p->pc = pc + 1;
72018   rc = SQLITE_ROW;
72019   goto vdbe_return;
72020 }
72021
72022 /* Opcode: Concat P1 P2 P3 * *
72023 ** Synopsis: r[P3]=r[P2]+r[P1]
72024 **
72025 ** Add the text in register P1 onto the end of the text in
72026 ** register P2 and store the result in register P3.
72027 ** If either the P1 or P2 text are NULL then store NULL in P3.
72028 **
72029 **   P3 = P2 || P1
72030 **
72031 ** It is illegal for P1 and P3 to be the same register. Sometimes,
72032 ** if P3 is the same register as P2, the implementation is able
72033 ** to avoid a memcpy().
72034 */
72035 case OP_Concat: {           /* same as TK_CONCAT, in1, in2, out3 */
72036   i64 nByte;
72037
72038   pIn1 = &aMem[pOp->p1];
72039   pIn2 = &aMem[pOp->p2];
72040   pOut = &aMem[pOp->p3];
72041   assert( pIn1!=pOut );
72042   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
72043     sqlite3VdbeMemSetNull(pOut);
72044     break;
72045   }
72046   if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
72047   Stringify(pIn1, encoding);
72048   Stringify(pIn2, encoding);
72049   nByte = pIn1->n + pIn2->n;
72050   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
72051     goto too_big;
72052   }
72053   if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
72054     goto no_mem;
72055   }
72056   MemSetTypeFlag(pOut, MEM_Str);
72057   if( pOut!=pIn2 ){
72058     memcpy(pOut->z, pIn2->z, pIn2->n);
72059   }
72060   memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
72061   pOut->z[nByte]=0;
72062   pOut->z[nByte+1] = 0;
72063   pOut->flags |= MEM_Term;
72064   pOut->n = (int)nByte;
72065   pOut->enc = encoding;
72066   UPDATE_MAX_BLOBSIZE(pOut);
72067   break;
72068 }
72069
72070 /* Opcode: Add P1 P2 P3 * *
72071 ** Synopsis:  r[P3]=r[P1]+r[P2]
72072 **
72073 ** Add the value in register P1 to the value in register P2
72074 ** and store the result in register P3.
72075 ** If either input is NULL, the result is NULL.
72076 */
72077 /* Opcode: Multiply P1 P2 P3 * *
72078 ** Synopsis:  r[P3]=r[P1]*r[P2]
72079 **
72080 **
72081 ** Multiply the value in register P1 by the value in register P2
72082 ** and store the result in register P3.
72083 ** If either input is NULL, the result is NULL.
72084 */
72085 /* Opcode: Subtract P1 P2 P3 * *
72086 ** Synopsis:  r[P3]=r[P2]-r[P1]
72087 **
72088 ** Subtract the value in register P1 from the value in register P2
72089 ** and store the result in register P3.
72090 ** If either input is NULL, the result is NULL.
72091 */
72092 /* Opcode: Divide P1 P2 P3 * *
72093 ** Synopsis:  r[P3]=r[P2]/r[P1]
72094 **
72095 ** Divide the value in register P1 by the value in register P2
72096 ** and store the result in register P3 (P3=P2/P1). If the value in 
72097 ** register P1 is zero, then the result is NULL. If either input is 
72098 ** NULL, the result is NULL.
72099 */
72100 /* Opcode: Remainder P1 P2 P3 * *
72101 ** Synopsis:  r[P3]=r[P2]%r[P1]
72102 **
72103 ** Compute the remainder after integer register P2 is divided by 
72104 ** register P1 and store the result in register P3. 
72105 ** If the value in register P1 is zero the result is NULL.
72106 ** If either operand is NULL, the result is NULL.
72107 */
72108 case OP_Add:                   /* same as TK_PLUS, in1, in2, out3 */
72109 case OP_Subtract:              /* same as TK_MINUS, in1, in2, out3 */
72110 case OP_Multiply:              /* same as TK_STAR, in1, in2, out3 */
72111 case OP_Divide:                /* same as TK_SLASH, in1, in2, out3 */
72112 case OP_Remainder: {           /* same as TK_REM, in1, in2, out3 */
72113   char bIntint;   /* Started out as two integer operands */
72114   u16 flags;      /* Combined MEM_* flags from both inputs */
72115   u16 type1;      /* Numeric type of left operand */
72116   u16 type2;      /* Numeric type of right operand */
72117   i64 iA;         /* Integer value of left operand */
72118   i64 iB;         /* Integer value of right operand */
72119   double rA;      /* Real value of left operand */
72120   double rB;      /* Real value of right operand */
72121
72122   pIn1 = &aMem[pOp->p1];
72123   type1 = numericType(pIn1);
72124   pIn2 = &aMem[pOp->p2];
72125   type2 = numericType(pIn2);
72126   pOut = &aMem[pOp->p3];
72127   flags = pIn1->flags | pIn2->flags;
72128   if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
72129   if( (type1 & type2 & MEM_Int)!=0 ){
72130     iA = pIn1->u.i;
72131     iB = pIn2->u.i;
72132     bIntint = 1;
72133     switch( pOp->opcode ){
72134       case OP_Add:       if( sqlite3AddInt64(&iB,iA) ) goto fp_math;  break;
72135       case OP_Subtract:  if( sqlite3SubInt64(&iB,iA) ) goto fp_math;  break;
72136       case OP_Multiply:  if( sqlite3MulInt64(&iB,iA) ) goto fp_math;  break;
72137       case OP_Divide: {
72138         if( iA==0 ) goto arithmetic_result_is_null;
72139         if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
72140         iB /= iA;
72141         break;
72142       }
72143       default: {
72144         if( iA==0 ) goto arithmetic_result_is_null;
72145         if( iA==-1 ) iA = 1;
72146         iB %= iA;
72147         break;
72148       }
72149     }
72150     pOut->u.i = iB;
72151     MemSetTypeFlag(pOut, MEM_Int);
72152   }else{
72153     bIntint = 0;
72154 fp_math:
72155     rA = sqlite3VdbeRealValue(pIn1);
72156     rB = sqlite3VdbeRealValue(pIn2);
72157     switch( pOp->opcode ){
72158       case OP_Add:         rB += rA;       break;
72159       case OP_Subtract:    rB -= rA;       break;
72160       case OP_Multiply:    rB *= rA;       break;
72161       case OP_Divide: {
72162         /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
72163         if( rA==(double)0 ) goto arithmetic_result_is_null;
72164         rB /= rA;
72165         break;
72166       }
72167       default: {
72168         iA = (i64)rA;
72169         iB = (i64)rB;
72170         if( iA==0 ) goto arithmetic_result_is_null;
72171         if( iA==-1 ) iA = 1;
72172         rB = (double)(iB % iA);
72173         break;
72174       }
72175     }
72176 #ifdef SQLITE_OMIT_FLOATING_POINT
72177     pOut->u.i = rB;
72178     MemSetTypeFlag(pOut, MEM_Int);
72179 #else
72180     if( sqlite3IsNaN(rB) ){
72181       goto arithmetic_result_is_null;
72182     }
72183     pOut->u.r = rB;
72184     MemSetTypeFlag(pOut, MEM_Real);
72185     if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
72186       sqlite3VdbeIntegerAffinity(pOut);
72187     }
72188 #endif
72189   }
72190   break;
72191
72192 arithmetic_result_is_null:
72193   sqlite3VdbeMemSetNull(pOut);
72194   break;
72195 }
72196
72197 /* Opcode: CollSeq P1 * * P4
72198 **
72199 ** P4 is a pointer to a CollSeq struct. If the next call to a user function
72200 ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
72201 ** be returned. This is used by the built-in min(), max() and nullif()
72202 ** functions.
72203 **
72204 ** If P1 is not zero, then it is a register that a subsequent min() or
72205 ** max() aggregate will set to 1 if the current row is not the minimum or
72206 ** maximum.  The P1 register is initialized to 0 by this instruction.
72207 **
72208 ** The interface used by the implementation of the aforementioned functions
72209 ** to retrieve the collation sequence set by this opcode is not available
72210 ** publicly.  Only built-in functions have access to this feature.
72211 */
72212 case OP_CollSeq: {
72213   assert( pOp->p4type==P4_COLLSEQ );
72214   if( pOp->p1 ){
72215     sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
72216   }
72217   break;
72218 }
72219
72220 /* Opcode: Function P1 P2 P3 P4 P5
72221 ** Synopsis: r[P3]=func(r[P2@P5])
72222 **
72223 ** Invoke a user function (P4 is a pointer to a Function structure that
72224 ** defines the function) with P5 arguments taken from register P2 and
72225 ** successors.  The result of the function is stored in register P3.
72226 ** Register P3 must not be one of the function inputs.
72227 **
72228 ** P1 is a 32-bit bitmask indicating whether or not each argument to the 
72229 ** function was determined to be constant at compile time. If the first
72230 ** argument was constant then bit 0 of P1 is set. This is used to determine
72231 ** whether meta data associated with a user function argument using the
72232 ** sqlite3_set_auxdata() API may be safely retained until the next
72233 ** invocation of this opcode.
72234 **
72235 ** See also: AggStep and AggFinal
72236 */
72237 case OP_Function: {
72238   int i;
72239   Mem *pArg;
72240   sqlite3_context ctx;
72241   sqlite3_value **apVal;
72242   int n;
72243
72244   n = pOp->p5;
72245   apVal = p->apArg;
72246   assert( apVal || n==0 );
72247   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
72248   ctx.pOut = &aMem[pOp->p3];
72249   memAboutToChange(p, ctx.pOut);
72250
72251   assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
72252   assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
72253   pArg = &aMem[pOp->p2];
72254   for(i=0; i<n; i++, pArg++){
72255     assert( memIsValid(pArg) );
72256     apVal[i] = pArg;
72257     Deephemeralize(pArg);
72258     REGISTER_TRACE(pOp->p2+i, pArg);
72259   }
72260
72261   assert( pOp->p4type==P4_FUNCDEF );
72262   ctx.pFunc = pOp->p4.pFunc;
72263   ctx.iOp = pc;
72264   ctx.pVdbe = p;
72265   MemSetTypeFlag(ctx.pOut, MEM_Null);
72266   ctx.fErrorOrAux = 0;
72267   db->lastRowid = lastRowid;
72268   (*ctx.pFunc->xFunc)(&ctx, n, apVal); /* IMP: R-24505-23230 */
72269   lastRowid = db->lastRowid;  /* Remember rowid changes made by xFunc */
72270
72271   /* If the function returned an error, throw an exception */
72272   if( ctx.fErrorOrAux ){
72273     if( ctx.isError ){
72274       sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(ctx.pOut));
72275       rc = ctx.isError;
72276     }
72277     sqlite3VdbeDeleteAuxData(p, pc, pOp->p1);
72278   }
72279
72280   /* Copy the result of the function into register P3 */
72281   sqlite3VdbeChangeEncoding(ctx.pOut, encoding);
72282   if( sqlite3VdbeMemTooBig(ctx.pOut) ){
72283     goto too_big;
72284   }
72285
72286   REGISTER_TRACE(pOp->p3, ctx.pOut);
72287   UPDATE_MAX_BLOBSIZE(ctx.pOut);
72288   break;
72289 }
72290
72291 /* Opcode: BitAnd P1 P2 P3 * *
72292 ** Synopsis:  r[P3]=r[P1]&r[P2]
72293 **
72294 ** Take the bit-wise AND of the values in register P1 and P2 and
72295 ** store the result in register P3.
72296 ** If either input is NULL, the result is NULL.
72297 */
72298 /* Opcode: BitOr P1 P2 P3 * *
72299 ** Synopsis:  r[P3]=r[P1]|r[P2]
72300 **
72301 ** Take the bit-wise OR of the values in register P1 and P2 and
72302 ** store the result in register P3.
72303 ** If either input is NULL, the result is NULL.
72304 */
72305 /* Opcode: ShiftLeft P1 P2 P3 * *
72306 ** Synopsis:  r[P3]=r[P2]<<r[P1]
72307 **
72308 ** Shift the integer value in register P2 to the left by the
72309 ** number of bits specified by the integer in register P1.
72310 ** Store the result in register P3.
72311 ** If either input is NULL, the result is NULL.
72312 */
72313 /* Opcode: ShiftRight P1 P2 P3 * *
72314 ** Synopsis:  r[P3]=r[P2]>>r[P1]
72315 **
72316 ** Shift the integer value in register P2 to the right by the
72317 ** number of bits specified by the integer in register P1.
72318 ** Store the result in register P3.
72319 ** If either input is NULL, the result is NULL.
72320 */
72321 case OP_BitAnd:                 /* same as TK_BITAND, in1, in2, out3 */
72322 case OP_BitOr:                  /* same as TK_BITOR, in1, in2, out3 */
72323 case OP_ShiftLeft:              /* same as TK_LSHIFT, in1, in2, out3 */
72324 case OP_ShiftRight: {           /* same as TK_RSHIFT, in1, in2, out3 */
72325   i64 iA;
72326   u64 uA;
72327   i64 iB;
72328   u8 op;
72329
72330   pIn1 = &aMem[pOp->p1];
72331   pIn2 = &aMem[pOp->p2];
72332   pOut = &aMem[pOp->p3];
72333   if( (pIn1->flags | pIn2->flags) & MEM_Null ){
72334     sqlite3VdbeMemSetNull(pOut);
72335     break;
72336   }
72337   iA = sqlite3VdbeIntValue(pIn2);
72338   iB = sqlite3VdbeIntValue(pIn1);
72339   op = pOp->opcode;
72340   if( op==OP_BitAnd ){
72341     iA &= iB;
72342   }else if( op==OP_BitOr ){
72343     iA |= iB;
72344   }else if( iB!=0 ){
72345     assert( op==OP_ShiftRight || op==OP_ShiftLeft );
72346
72347     /* If shifting by a negative amount, shift in the other direction */
72348     if( iB<0 ){
72349       assert( OP_ShiftRight==OP_ShiftLeft+1 );
72350       op = 2*OP_ShiftLeft + 1 - op;
72351       iB = iB>(-64) ? -iB : 64;
72352     }
72353
72354     if( iB>=64 ){
72355       iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
72356     }else{
72357       memcpy(&uA, &iA, sizeof(uA));
72358       if( op==OP_ShiftLeft ){
72359         uA <<= iB;
72360       }else{
72361         uA >>= iB;
72362         /* Sign-extend on a right shift of a negative number */
72363         if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
72364       }
72365       memcpy(&iA, &uA, sizeof(iA));
72366     }
72367   }
72368   pOut->u.i = iA;
72369   MemSetTypeFlag(pOut, MEM_Int);
72370   break;
72371 }
72372
72373 /* Opcode: AddImm  P1 P2 * * *
72374 ** Synopsis:  r[P1]=r[P1]+P2
72375 ** 
72376 ** Add the constant P2 to the value in register P1.
72377 ** The result is always an integer.
72378 **
72379 ** To force any register to be an integer, just add 0.
72380 */
72381 case OP_AddImm: {            /* in1 */
72382   pIn1 = &aMem[pOp->p1];
72383   memAboutToChange(p, pIn1);
72384   sqlite3VdbeMemIntegerify(pIn1);
72385   pIn1->u.i += pOp->p2;
72386   break;
72387 }
72388
72389 /* Opcode: MustBeInt P1 P2 * * *
72390 ** 
72391 ** Force the value in register P1 to be an integer.  If the value
72392 ** in P1 is not an integer and cannot be converted into an integer
72393 ** without data loss, then jump immediately to P2, or if P2==0
72394 ** raise an SQLITE_MISMATCH exception.
72395 */
72396 case OP_MustBeInt: {            /* jump, in1 */
72397   pIn1 = &aMem[pOp->p1];
72398   if( (pIn1->flags & MEM_Int)==0 ){
72399     applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
72400     VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
72401     if( (pIn1->flags & MEM_Int)==0 ){
72402       if( pOp->p2==0 ){
72403         rc = SQLITE_MISMATCH;
72404         goto abort_due_to_error;
72405       }else{
72406         pc = pOp->p2 - 1;
72407         break;
72408       }
72409     }
72410   }
72411   MemSetTypeFlag(pIn1, MEM_Int);
72412   break;
72413 }
72414
72415 #ifndef SQLITE_OMIT_FLOATING_POINT
72416 /* Opcode: RealAffinity P1 * * * *
72417 **
72418 ** If register P1 holds an integer convert it to a real value.
72419 **
72420 ** This opcode is used when extracting information from a column that
72421 ** has REAL affinity.  Such column values may still be stored as
72422 ** integers, for space efficiency, but after extraction we want them
72423 ** to have only a real value.
72424 */
72425 case OP_RealAffinity: {                  /* in1 */
72426   pIn1 = &aMem[pOp->p1];
72427   if( pIn1->flags & MEM_Int ){
72428     sqlite3VdbeMemRealify(pIn1);
72429   }
72430   break;
72431 }
72432 #endif
72433
72434 #ifndef SQLITE_OMIT_CAST
72435 /* Opcode: Cast P1 P2 * * *
72436 ** Synopsis: affinity(r[P1])
72437 **
72438 ** Force the value in register P1 to be the type defined by P2.
72439 ** 
72440 ** <ul>
72441 ** <li value="97"> TEXT
72442 ** <li value="98"> BLOB
72443 ** <li value="99"> NUMERIC
72444 ** <li value="100"> INTEGER
72445 ** <li value="101"> REAL
72446 ** </ul>
72447 **
72448 ** A NULL value is not changed by this routine.  It remains NULL.
72449 */
72450 case OP_Cast: {                  /* in1 */
72451   assert( pOp->p2>=SQLITE_AFF_NONE && pOp->p2<=SQLITE_AFF_REAL );
72452   testcase( pOp->p2==SQLITE_AFF_TEXT );
72453   testcase( pOp->p2==SQLITE_AFF_NONE );
72454   testcase( pOp->p2==SQLITE_AFF_NUMERIC );
72455   testcase( pOp->p2==SQLITE_AFF_INTEGER );
72456   testcase( pOp->p2==SQLITE_AFF_REAL );
72457   pIn1 = &aMem[pOp->p1];
72458   memAboutToChange(p, pIn1);
72459   rc = ExpandBlob(pIn1);
72460   sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
72461   UPDATE_MAX_BLOBSIZE(pIn1);
72462   break;
72463 }
72464 #endif /* SQLITE_OMIT_CAST */
72465
72466 /* Opcode: Lt P1 P2 P3 P4 P5
72467 ** Synopsis: if r[P1]<r[P3] goto P2
72468 **
72469 ** Compare the values in register P1 and P3.  If reg(P3)<reg(P1) then
72470 ** jump to address P2.  
72471 **
72472 ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
72473 ** reg(P3) is NULL then take the jump.  If the SQLITE_JUMPIFNULL 
72474 ** bit is clear then fall through if either operand is NULL.
72475 **
72476 ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
72477 ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made 
72478 ** to coerce both inputs according to this affinity before the
72479 ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
72480 ** affinity is used. Note that the affinity conversions are stored
72481 ** back into the input registers P1 and P3.  So this opcode can cause
72482 ** persistent changes to registers P1 and P3.
72483 **
72484 ** Once any conversions have taken place, and neither value is NULL, 
72485 ** the values are compared. If both values are blobs then memcmp() is
72486 ** used to determine the results of the comparison.  If both values
72487 ** are text, then the appropriate collating function specified in
72488 ** P4 is  used to do the comparison.  If P4 is not specified then
72489 ** memcmp() is used to compare text string.  If both values are
72490 ** numeric, then a numeric comparison is used. If the two values
72491 ** are of different types, then numbers are considered less than
72492 ** strings and strings are considered less than blobs.
72493 **
72494 ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump.  Instead,
72495 ** store a boolean result (either 0, or 1, or NULL) in register P2.
72496 **
72497 ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
72498 ** equal to one another, provided that they do not have their MEM_Cleared
72499 ** bit set.
72500 */
72501 /* Opcode: Ne P1 P2 P3 P4 P5
72502 ** Synopsis: if r[P1]!=r[P3] goto P2
72503 **
72504 ** This works just like the Lt opcode except that the jump is taken if
72505 ** the operands in registers P1 and P3 are not equal.  See the Lt opcode for
72506 ** additional information.
72507 **
72508 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
72509 ** true or false and is never NULL.  If both operands are NULL then the result
72510 ** of comparison is false.  If either operand is NULL then the result is true.
72511 ** If neither operand is NULL the result is the same as it would be if
72512 ** the SQLITE_NULLEQ flag were omitted from P5.
72513 */
72514 /* Opcode: Eq P1 P2 P3 P4 P5
72515 ** Synopsis: if r[P1]==r[P3] goto P2
72516 **
72517 ** This works just like the Lt opcode except that the jump is taken if
72518 ** the operands in registers P1 and P3 are equal.
72519 ** See the Lt opcode for additional information.
72520 **
72521 ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
72522 ** true or false and is never NULL.  If both operands are NULL then the result
72523 ** of comparison is true.  If either operand is NULL then the result is false.
72524 ** If neither operand is NULL the result is the same as it would be if
72525 ** the SQLITE_NULLEQ flag were omitted from P5.
72526 */
72527 /* Opcode: Le P1 P2 P3 P4 P5
72528 ** Synopsis: if r[P1]<=r[P3] goto P2
72529 **
72530 ** This works just like the Lt opcode except that the jump is taken if
72531 ** the content of register P3 is less than or equal to the content of
72532 ** register P1.  See the Lt opcode for additional information.
72533 */
72534 /* Opcode: Gt P1 P2 P3 P4 P5
72535 ** Synopsis: if r[P1]>r[P3] goto P2
72536 **
72537 ** This works just like the Lt opcode except that the jump is taken if
72538 ** the content of register P3 is greater than the content of
72539 ** register P1.  See the Lt opcode for additional information.
72540 */
72541 /* Opcode: Ge P1 P2 P3 P4 P5
72542 ** Synopsis: if r[P1]>=r[P3] goto P2
72543 **
72544 ** This works just like the Lt opcode except that the jump is taken if
72545 ** the content of register P3 is greater than or equal to the content of
72546 ** register P1.  See the Lt opcode for additional information.
72547 */
72548 case OP_Eq:               /* same as TK_EQ, jump, in1, in3 */
72549 case OP_Ne:               /* same as TK_NE, jump, in1, in3 */
72550 case OP_Lt:               /* same as TK_LT, jump, in1, in3 */
72551 case OP_Le:               /* same as TK_LE, jump, in1, in3 */
72552 case OP_Gt:               /* same as TK_GT, jump, in1, in3 */
72553 case OP_Ge: {             /* same as TK_GE, jump, in1, in3 */
72554   int res;            /* Result of the comparison of pIn1 against pIn3 */
72555   char affinity;      /* Affinity to use for comparison */
72556   u16 flags1;         /* Copy of initial value of pIn1->flags */
72557   u16 flags3;         /* Copy of initial value of pIn3->flags */
72558
72559   pIn1 = &aMem[pOp->p1];
72560   pIn3 = &aMem[pOp->p3];
72561   flags1 = pIn1->flags;
72562   flags3 = pIn3->flags;
72563   if( (flags1 | flags3)&MEM_Null ){
72564     /* One or both operands are NULL */
72565     if( pOp->p5 & SQLITE_NULLEQ ){
72566       /* If SQLITE_NULLEQ is set (which will only happen if the operator is
72567       ** OP_Eq or OP_Ne) then take the jump or not depending on whether
72568       ** or not both operands are null.
72569       */
72570       assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
72571       assert( (flags1 & MEM_Cleared)==0 );
72572       assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
72573       if( (flags1&MEM_Null)!=0
72574        && (flags3&MEM_Null)!=0
72575        && (flags3&MEM_Cleared)==0
72576       ){
72577         res = 0;  /* Results are equal */
72578       }else{
72579         res = 1;  /* Results are not equal */
72580       }
72581     }else{
72582       /* SQLITE_NULLEQ is clear and at least one operand is NULL,
72583       ** then the result is always NULL.
72584       ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
72585       */
72586       if( pOp->p5 & SQLITE_STOREP2 ){
72587         pOut = &aMem[pOp->p2];
72588         MemSetTypeFlag(pOut, MEM_Null);
72589         REGISTER_TRACE(pOp->p2, pOut);
72590       }else{
72591         VdbeBranchTaken(2,3);
72592         if( pOp->p5 & SQLITE_JUMPIFNULL ){
72593           pc = pOp->p2-1;
72594         }
72595       }
72596       break;
72597     }
72598   }else{
72599     /* Neither operand is NULL.  Do a comparison. */
72600     affinity = pOp->p5 & SQLITE_AFF_MASK;
72601     if( affinity>=SQLITE_AFF_NUMERIC ){
72602       if( (pIn1->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
72603         applyNumericAffinity(pIn1,0);
72604       }
72605       if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
72606         applyNumericAffinity(pIn3,0);
72607       }
72608     }else if( affinity==SQLITE_AFF_TEXT ){
72609       if( (pIn1->flags & MEM_Str)==0 && (pIn1->flags & (MEM_Int|MEM_Real))!=0 ){
72610         testcase( pIn1->flags & MEM_Int );
72611         testcase( pIn1->flags & MEM_Real );
72612         sqlite3VdbeMemStringify(pIn1, encoding, 1);
72613         testcase( (flags1&MEM_Dyn) != (pIn1->flags&MEM_Dyn) );
72614         flags1 = (pIn1->flags & ~MEM_TypeMask) | (flags1 & MEM_TypeMask);
72615       }
72616       if( (pIn3->flags & MEM_Str)==0 && (pIn3->flags & (MEM_Int|MEM_Real))!=0 ){
72617         testcase( pIn3->flags & MEM_Int );
72618         testcase( pIn3->flags & MEM_Real );
72619         sqlite3VdbeMemStringify(pIn3, encoding, 1);
72620         testcase( (flags3&MEM_Dyn) != (pIn3->flags&MEM_Dyn) );
72621         flags3 = (pIn3->flags & ~MEM_TypeMask) | (flags3 & MEM_TypeMask);
72622       }
72623     }
72624     assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
72625     if( pIn1->flags & MEM_Zero ){
72626       sqlite3VdbeMemExpandBlob(pIn1);
72627       flags1 &= ~MEM_Zero;
72628     }
72629     if( pIn3->flags & MEM_Zero ){
72630       sqlite3VdbeMemExpandBlob(pIn3);
72631       flags3 &= ~MEM_Zero;
72632     }
72633     if( db->mallocFailed ) goto no_mem;
72634     res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
72635   }
72636   switch( pOp->opcode ){
72637     case OP_Eq:    res = res==0;     break;
72638     case OP_Ne:    res = res!=0;     break;
72639     case OP_Lt:    res = res<0;      break;
72640     case OP_Le:    res = res<=0;     break;
72641     case OP_Gt:    res = res>0;      break;
72642     default:       res = res>=0;     break;
72643   }
72644
72645   if( pOp->p5 & SQLITE_STOREP2 ){
72646     pOut = &aMem[pOp->p2];
72647     memAboutToChange(p, pOut);
72648     MemSetTypeFlag(pOut, MEM_Int);
72649     pOut->u.i = res;
72650     REGISTER_TRACE(pOp->p2, pOut);
72651   }else{
72652     VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
72653     if( res ){
72654       pc = pOp->p2-1;
72655     }
72656   }
72657   /* Undo any changes made by applyAffinity() to the input registers. */
72658   assert( (pIn1->flags & MEM_Dyn) == (flags1 & MEM_Dyn) );
72659   pIn1->flags = flags1;
72660   assert( (pIn3->flags & MEM_Dyn) == (flags3 & MEM_Dyn) );
72661   pIn3->flags = flags3;
72662   break;
72663 }
72664
72665 /* Opcode: Permutation * * * P4 *
72666 **
72667 ** Set the permutation used by the OP_Compare operator to be the array
72668 ** of integers in P4.
72669 **
72670 ** The permutation is only valid until the next OP_Compare that has
72671 ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should 
72672 ** occur immediately prior to the OP_Compare.
72673 */
72674 case OP_Permutation: {
72675   assert( pOp->p4type==P4_INTARRAY );
72676   assert( pOp->p4.ai );
72677   aPermute = pOp->p4.ai;
72678   break;
72679 }
72680
72681 /* Opcode: Compare P1 P2 P3 P4 P5
72682 ** Synopsis: r[P1@P3] <-> r[P2@P3]
72683 **
72684 ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
72685 ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B").  Save the result of
72686 ** the comparison for use by the next OP_Jump instruct.
72687 **
72688 ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
72689 ** determined by the most recent OP_Permutation operator.  If the
72690 ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
72691 ** order.
72692 **
72693 ** P4 is a KeyInfo structure that defines collating sequences and sort
72694 ** orders for the comparison.  The permutation applies to registers
72695 ** only.  The KeyInfo elements are used sequentially.
72696 **
72697 ** The comparison is a sort comparison, so NULLs compare equal,
72698 ** NULLs are less than numbers, numbers are less than strings,
72699 ** and strings are less than blobs.
72700 */
72701 case OP_Compare: {
72702   int n;
72703   int i;
72704   int p1;
72705   int p2;
72706   const KeyInfo *pKeyInfo;
72707   int idx;
72708   CollSeq *pColl;    /* Collating sequence to use on this term */
72709   int bRev;          /* True for DESCENDING sort order */
72710
72711   if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
72712   n = pOp->p3;
72713   pKeyInfo = pOp->p4.pKeyInfo;
72714   assert( n>0 );
72715   assert( pKeyInfo!=0 );
72716   p1 = pOp->p1;
72717   p2 = pOp->p2;
72718 #if SQLITE_DEBUG
72719   if( aPermute ){
72720     int k, mx = 0;
72721     for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
72722     assert( p1>0 && p1+mx<=(p->nMem-p->nCursor)+1 );
72723     assert( p2>0 && p2+mx<=(p->nMem-p->nCursor)+1 );
72724   }else{
72725     assert( p1>0 && p1+n<=(p->nMem-p->nCursor)+1 );
72726     assert( p2>0 && p2+n<=(p->nMem-p->nCursor)+1 );
72727   }
72728 #endif /* SQLITE_DEBUG */
72729   for(i=0; i<n; i++){
72730     idx = aPermute ? aPermute[i] : i;
72731     assert( memIsValid(&aMem[p1+idx]) );
72732     assert( memIsValid(&aMem[p2+idx]) );
72733     REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
72734     REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
72735     assert( i<pKeyInfo->nField );
72736     pColl = pKeyInfo->aColl[i];
72737     bRev = pKeyInfo->aSortOrder[i];
72738     iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
72739     if( iCompare ){
72740       if( bRev ) iCompare = -iCompare;
72741       break;
72742     }
72743   }
72744   aPermute = 0;
72745   break;
72746 }
72747
72748 /* Opcode: Jump P1 P2 P3 * *
72749 **
72750 ** Jump to the instruction at address P1, P2, or P3 depending on whether
72751 ** in the most recent OP_Compare instruction the P1 vector was less than
72752 ** equal to, or greater than the P2 vector, respectively.
72753 */
72754 case OP_Jump: {             /* jump */
72755   if( iCompare<0 ){
72756     pc = pOp->p1 - 1;  VdbeBranchTaken(0,3);
72757   }else if( iCompare==0 ){
72758     pc = pOp->p2 - 1;  VdbeBranchTaken(1,3);
72759   }else{
72760     pc = pOp->p3 - 1;  VdbeBranchTaken(2,3);
72761   }
72762   break;
72763 }
72764
72765 /* Opcode: And P1 P2 P3 * *
72766 ** Synopsis: r[P3]=(r[P1] && r[P2])
72767 **
72768 ** Take the logical AND of the values in registers P1 and P2 and
72769 ** write the result into register P3.
72770 **
72771 ** If either P1 or P2 is 0 (false) then the result is 0 even if
72772 ** the other input is NULL.  A NULL and true or two NULLs give
72773 ** a NULL output.
72774 */
72775 /* Opcode: Or P1 P2 P3 * *
72776 ** Synopsis: r[P3]=(r[P1] || r[P2])
72777 **
72778 ** Take the logical OR of the values in register P1 and P2 and
72779 ** store the answer in register P3.
72780 **
72781 ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
72782 ** even if the other input is NULL.  A NULL and false or two NULLs
72783 ** give a NULL output.
72784 */
72785 case OP_And:              /* same as TK_AND, in1, in2, out3 */
72786 case OP_Or: {             /* same as TK_OR, in1, in2, out3 */
72787   int v1;    /* Left operand:  0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
72788   int v2;    /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
72789
72790   pIn1 = &aMem[pOp->p1];
72791   if( pIn1->flags & MEM_Null ){
72792     v1 = 2;
72793   }else{
72794     v1 = sqlite3VdbeIntValue(pIn1)!=0;
72795   }
72796   pIn2 = &aMem[pOp->p2];
72797   if( pIn2->flags & MEM_Null ){
72798     v2 = 2;
72799   }else{
72800     v2 = sqlite3VdbeIntValue(pIn2)!=0;
72801   }
72802   if( pOp->opcode==OP_And ){
72803     static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
72804     v1 = and_logic[v1*3+v2];
72805   }else{
72806     static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
72807     v1 = or_logic[v1*3+v2];
72808   }
72809   pOut = &aMem[pOp->p3];
72810   if( v1==2 ){
72811     MemSetTypeFlag(pOut, MEM_Null);
72812   }else{
72813     pOut->u.i = v1;
72814     MemSetTypeFlag(pOut, MEM_Int);
72815   }
72816   break;
72817 }
72818
72819 /* Opcode: Not P1 P2 * * *
72820 ** Synopsis: r[P2]= !r[P1]
72821 **
72822 ** Interpret the value in register P1 as a boolean value.  Store the
72823 ** boolean complement in register P2.  If the value in register P1 is 
72824 ** NULL, then a NULL is stored in P2.
72825 */
72826 case OP_Not: {                /* same as TK_NOT, in1, out2 */
72827   pIn1 = &aMem[pOp->p1];
72828   pOut = &aMem[pOp->p2];
72829   sqlite3VdbeMemSetNull(pOut);
72830   if( (pIn1->flags & MEM_Null)==0 ){
72831     pOut->flags = MEM_Int;
72832     pOut->u.i = !sqlite3VdbeIntValue(pIn1);
72833   }
72834   break;
72835 }
72836
72837 /* Opcode: BitNot P1 P2 * * *
72838 ** Synopsis: r[P1]= ~r[P1]
72839 **
72840 ** Interpret the content of register P1 as an integer.  Store the
72841 ** ones-complement of the P1 value into register P2.  If P1 holds
72842 ** a NULL then store a NULL in P2.
72843 */
72844 case OP_BitNot: {             /* same as TK_BITNOT, in1, out2 */
72845   pIn1 = &aMem[pOp->p1];
72846   pOut = &aMem[pOp->p2];
72847   sqlite3VdbeMemSetNull(pOut);
72848   if( (pIn1->flags & MEM_Null)==0 ){
72849     pOut->flags = MEM_Int;
72850     pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
72851   }
72852   break;
72853 }
72854
72855 /* Opcode: Once P1 P2 * * *
72856 **
72857 ** Check the "once" flag number P1. If it is set, jump to instruction P2. 
72858 ** Otherwise, set the flag and fall through to the next instruction.
72859 ** In other words, this opcode causes all following opcodes up through P2
72860 ** (but not including P2) to run just once and to be skipped on subsequent
72861 ** times through the loop.
72862 **
72863 ** All "once" flags are initially cleared whenever a prepared statement
72864 ** first begins to run.
72865 */
72866 case OP_Once: {             /* jump */
72867   assert( pOp->p1<p->nOnceFlag );
72868   VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
72869   if( p->aOnceFlag[pOp->p1] ){
72870     pc = pOp->p2-1;
72871   }else{
72872     p->aOnceFlag[pOp->p1] = 1;
72873   }
72874   break;
72875 }
72876
72877 /* Opcode: If P1 P2 P3 * *
72878 **
72879 ** Jump to P2 if the value in register P1 is true.  The value
72880 ** is considered true if it is numeric and non-zero.  If the value
72881 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
72882 */
72883 /* Opcode: IfNot P1 P2 P3 * *
72884 **
72885 ** Jump to P2 if the value in register P1 is False.  The value
72886 ** is considered false if it has a numeric value of zero.  If the value
72887 ** in P1 is NULL then take the jump if and only if P3 is non-zero.
72888 */
72889 case OP_If:                 /* jump, in1 */
72890 case OP_IfNot: {            /* jump, in1 */
72891   int c;
72892   pIn1 = &aMem[pOp->p1];
72893   if( pIn1->flags & MEM_Null ){
72894     c = pOp->p3;
72895   }else{
72896 #ifdef SQLITE_OMIT_FLOATING_POINT
72897     c = sqlite3VdbeIntValue(pIn1)!=0;
72898 #else
72899     c = sqlite3VdbeRealValue(pIn1)!=0.0;
72900 #endif
72901     if( pOp->opcode==OP_IfNot ) c = !c;
72902   }
72903   VdbeBranchTaken(c!=0, 2);
72904   if( c ){
72905     pc = pOp->p2-1;
72906   }
72907   break;
72908 }
72909
72910 /* Opcode: IsNull P1 P2 * * *
72911 ** Synopsis:  if r[P1]==NULL goto P2
72912 **
72913 ** Jump to P2 if the value in register P1 is NULL.
72914 */
72915 case OP_IsNull: {            /* same as TK_ISNULL, jump, in1 */
72916   pIn1 = &aMem[pOp->p1];
72917   VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
72918   if( (pIn1->flags & MEM_Null)!=0 ){
72919     pc = pOp->p2 - 1;
72920   }
72921   break;
72922 }
72923
72924 /* Opcode: NotNull P1 P2 * * *
72925 ** Synopsis: if r[P1]!=NULL goto P2
72926 **
72927 ** Jump to P2 if the value in register P1 is not NULL.  
72928 */
72929 case OP_NotNull: {            /* same as TK_NOTNULL, jump, in1 */
72930   pIn1 = &aMem[pOp->p1];
72931   VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
72932   if( (pIn1->flags & MEM_Null)==0 ){
72933     pc = pOp->p2 - 1;
72934   }
72935   break;
72936 }
72937
72938 /* Opcode: Column P1 P2 P3 P4 P5
72939 ** Synopsis:  r[P3]=PX
72940 **
72941 ** Interpret the data that cursor P1 points to as a structure built using
72942 ** the MakeRecord instruction.  (See the MakeRecord opcode for additional
72943 ** information about the format of the data.)  Extract the P2-th column
72944 ** from this record.  If there are less that (P2+1) 
72945 ** values in the record, extract a NULL.
72946 **
72947 ** The value extracted is stored in register P3.
72948 **
72949 ** If the column contains fewer than P2 fields, then extract a NULL.  Or,
72950 ** if the P4 argument is a P4_MEM use the value of the P4 argument as
72951 ** the result.
72952 **
72953 ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
72954 ** then the cache of the cursor is reset prior to extracting the column.
72955 ** The first OP_Column against a pseudo-table after the value of the content
72956 ** register has changed should have this bit set.
72957 **
72958 ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
72959 ** the result is guaranteed to only be used as the argument of a length()
72960 ** or typeof() function, respectively.  The loading of large blobs can be
72961 ** skipped for length() and all content loading can be skipped for typeof().
72962 */
72963 case OP_Column: {
72964   i64 payloadSize64; /* Number of bytes in the record */
72965   int p2;            /* column number to retrieve */
72966   VdbeCursor *pC;    /* The VDBE cursor */
72967   BtCursor *pCrsr;   /* The BTree cursor */
72968   u32 *aOffset;      /* aOffset[i] is offset to start of data for i-th column */
72969   int len;           /* The length of the serialized data for the column */
72970   int i;             /* Loop counter */
72971   Mem *pDest;        /* Where to write the extracted value */
72972   Mem sMem;          /* For storing the record being decoded */
72973   const u8 *zData;   /* Part of the record being decoded */
72974   const u8 *zHdr;    /* Next unparsed byte of the header */
72975   const u8 *zEndHdr; /* Pointer to first byte after the header */
72976   u32 offset;        /* Offset into the data */
72977   u32 szField;       /* Number of bytes in the content of a field */
72978   u32 avail;         /* Number of bytes of available data */
72979   u32 t;             /* A type code from the record header */
72980   u16 fx;            /* pDest->flags value */
72981   Mem *pReg;         /* PseudoTable input register */
72982
72983   p2 = pOp->p2;
72984   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
72985   pDest = &aMem[pOp->p3];
72986   memAboutToChange(p, pDest);
72987   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
72988   pC = p->apCsr[pOp->p1];
72989   assert( pC!=0 );
72990   assert( p2<pC->nField );
72991   aOffset = pC->aOffset;
72992 #ifndef SQLITE_OMIT_VIRTUALTABLE
72993   assert( pC->pVtabCursor==0 ); /* OP_Column never called on virtual table */
72994 #endif
72995   pCrsr = pC->pCursor;
72996   assert( pCrsr!=0 || pC->pseudoTableReg>0 ); /* pCrsr NULL on PseudoTables */
72997   assert( pCrsr!=0 || pC->nullRow );          /* pC->nullRow on PseudoTables */
72998
72999   /* If the cursor cache is stale, bring it up-to-date */
73000   rc = sqlite3VdbeCursorMoveto(pC);
73001   if( rc ) goto abort_due_to_error;
73002   if( pC->cacheStatus!=p->cacheCtr ){
73003     if( pC->nullRow ){
73004       if( pCrsr==0 ){
73005         assert( pC->pseudoTableReg>0 );
73006         pReg = &aMem[pC->pseudoTableReg];
73007         assert( pReg->flags & MEM_Blob );
73008         assert( memIsValid(pReg) );
73009         pC->payloadSize = pC->szRow = avail = pReg->n;
73010         pC->aRow = (u8*)pReg->z;
73011       }else{
73012         sqlite3VdbeMemSetNull(pDest);
73013         goto op_column_out;
73014       }
73015     }else{
73016       assert( pCrsr );
73017       if( pC->isTable==0 ){
73018         assert( sqlite3BtreeCursorIsValid(pCrsr) );
73019         VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &payloadSize64);
73020         assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
73021         /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
73022         ** payload size, so it is impossible for payloadSize64 to be
73023         ** larger than 32 bits. */
73024         assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 );
73025         pC->aRow = sqlite3BtreeKeyFetch(pCrsr, &avail);
73026         pC->payloadSize = (u32)payloadSize64;
73027       }else{
73028         assert( sqlite3BtreeCursorIsValid(pCrsr) );
73029         VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &pC->payloadSize);
73030         assert( rc==SQLITE_OK );   /* DataSize() cannot fail */
73031         pC->aRow = sqlite3BtreeDataFetch(pCrsr, &avail);
73032       }
73033       assert( avail<=65536 );  /* Maximum page size is 64KiB */
73034       if( pC->payloadSize <= (u32)avail ){
73035         pC->szRow = pC->payloadSize;
73036       }else{
73037         pC->szRow = avail;
73038       }
73039       if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
73040         goto too_big;
73041       }
73042     }
73043     pC->cacheStatus = p->cacheCtr;
73044     pC->iHdrOffset = getVarint32(pC->aRow, offset);
73045     pC->nHdrParsed = 0;
73046     aOffset[0] = offset;
73047
73048     /* Make sure a corrupt database has not given us an oversize header.
73049     ** Do this now to avoid an oversize memory allocation.
73050     **
73051     ** Type entries can be between 1 and 5 bytes each.  But 4 and 5 byte
73052     ** types use so much data space that there can only be 4096 and 32 of
73053     ** them, respectively.  So the maximum header length results from a
73054     ** 3-byte type for each of the maximum of 32768 columns plus three
73055     ** extra bytes for the header length itself.  32768*3 + 3 = 98307.
73056     */
73057     if( offset > 98307 || offset > pC->payloadSize ){
73058       rc = SQLITE_CORRUPT_BKPT;
73059       goto op_column_error;
73060     }
73061
73062     if( avail<offset ){
73063       /* pC->aRow does not have to hold the entire row, but it does at least
73064       ** need to cover the header of the record.  If pC->aRow does not contain
73065       ** the complete header, then set it to zero, forcing the header to be
73066       ** dynamically allocated. */
73067       pC->aRow = 0;
73068       pC->szRow = 0;
73069     }
73070
73071     /* The following goto is an optimization.  It can be omitted and
73072     ** everything will still work.  But OP_Column is measurably faster
73073     ** by skipping the subsequent conditional, which is always true.
73074     */
73075     assert( pC->nHdrParsed<=p2 );         /* Conditional skipped */
73076     goto op_column_read_header;
73077   }
73078
73079   /* Make sure at least the first p2+1 entries of the header have been
73080   ** parsed and valid information is in aOffset[] and pC->aType[].
73081   */
73082   if( pC->nHdrParsed<=p2 ){
73083     /* If there is more header available for parsing in the record, try
73084     ** to extract additional fields up through the p2+1-th field 
73085     */
73086     op_column_read_header:
73087     if( pC->iHdrOffset<aOffset[0] ){
73088       /* Make sure zData points to enough of the record to cover the header. */
73089       if( pC->aRow==0 ){
73090         memset(&sMem, 0, sizeof(sMem));
73091         rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0], 
73092                                      !pC->isTable, &sMem);
73093         if( rc!=SQLITE_OK ){
73094           goto op_column_error;
73095         }
73096         zData = (u8*)sMem.z;
73097       }else{
73098         zData = pC->aRow;
73099       }
73100   
73101       /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
73102       i = pC->nHdrParsed;
73103       offset = aOffset[i];
73104       zHdr = zData + pC->iHdrOffset;
73105       zEndHdr = zData + aOffset[0];
73106       assert( i<=p2 && zHdr<zEndHdr );
73107       do{
73108         if( zHdr[0]<0x80 ){
73109           t = zHdr[0];
73110           zHdr++;
73111         }else{
73112           zHdr += sqlite3GetVarint32(zHdr, &t);
73113         }
73114         pC->aType[i] = t;
73115         szField = sqlite3VdbeSerialTypeLen(t);
73116         offset += szField;
73117         if( offset<szField ){  /* True if offset overflows */
73118           zHdr = &zEndHdr[1];  /* Forces SQLITE_CORRUPT return below */
73119           break;
73120         }
73121         i++;
73122         aOffset[i] = offset;
73123       }while( i<=p2 && zHdr<zEndHdr );
73124       pC->nHdrParsed = i;
73125       pC->iHdrOffset = (u32)(zHdr - zData);
73126       if( pC->aRow==0 ){
73127         sqlite3VdbeMemRelease(&sMem);
73128         sMem.flags = MEM_Null;
73129       }
73130   
73131       /* The record is corrupt if any of the following are true:
73132       ** (1) the bytes of the header extend past the declared header size
73133       **          (zHdr>zEndHdr)
73134       ** (2) the entire header was used but not all data was used
73135       **          (zHdr==zEndHdr && offset!=pC->payloadSize)
73136       ** (3) the end of the data extends beyond the end of the record.
73137       **          (offset > pC->payloadSize)
73138       */
73139       if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset!=pC->payloadSize))
73140        || (offset > pC->payloadSize)
73141       ){
73142         rc = SQLITE_CORRUPT_BKPT;
73143         goto op_column_error;
73144       }
73145     }
73146
73147     /* If after trying to extra new entries from the header, nHdrParsed is
73148     ** still not up to p2, that means that the record has fewer than p2
73149     ** columns.  So the result will be either the default value or a NULL.
73150     */
73151     if( pC->nHdrParsed<=p2 ){
73152       if( pOp->p4type==P4_MEM ){
73153         sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
73154       }else{
73155         sqlite3VdbeMemSetNull(pDest);
73156       }
73157       goto op_column_out;
73158     }
73159   }
73160
73161   /* Extract the content for the p2+1-th column.  Control can only
73162   ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
73163   ** all valid.
73164   */
73165   assert( p2<pC->nHdrParsed );
73166   assert( rc==SQLITE_OK );
73167   assert( sqlite3VdbeCheckMemInvariants(pDest) );
73168   if( VdbeMemDynamic(pDest) ) sqlite3VdbeMemSetNull(pDest);
73169   t = pC->aType[p2];
73170   if( pC->szRow>=aOffset[p2+1] ){
73171     /* This is the common case where the desired content fits on the original
73172     ** page - where the content is not on an overflow page */
73173     sqlite3VdbeSerialGet(pC->aRow+aOffset[p2], t, pDest);
73174   }else{
73175     /* This branch happens only when content is on overflow pages */
73176     if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
73177           && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
73178      || (len = sqlite3VdbeSerialTypeLen(t))==0
73179     ){
73180       /* Content is irrelevant for
73181       **    1. the typeof() function,
73182       **    2. the length(X) function if X is a blob, and
73183       **    3. if the content length is zero.
73184       ** So we might as well use bogus content rather than reading
73185       ** content from disk.  NULL will work for the value for strings
73186       ** and blobs and whatever is in the payloadSize64 variable
73187       ** will work for everything else. */
73188       sqlite3VdbeSerialGet(t<=13 ? (u8*)&payloadSize64 : 0, t, pDest);
73189     }else{
73190       rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
73191                                    pDest);
73192       if( rc!=SQLITE_OK ){
73193         goto op_column_error;
73194       }
73195       sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
73196       pDest->flags &= ~MEM_Ephem;
73197     }
73198   }
73199   pDest->enc = encoding;
73200
73201 op_column_out:
73202   /* If the column value is an ephemeral string, go ahead and persist
73203   ** that string in case the cursor moves before the column value is
73204   ** used.  The following code does the equivalent of Deephemeralize()
73205   ** but does it faster. */
73206   if( (pDest->flags & MEM_Ephem)!=0 && pDest->z ){
73207     fx = pDest->flags & (MEM_Str|MEM_Blob);
73208     assert( fx!=0 );
73209     zData = (const u8*)pDest->z;
73210     len = pDest->n;
73211     if( sqlite3VdbeMemClearAndResize(pDest, len+2) ) goto no_mem;
73212     memcpy(pDest->z, zData, len);
73213     pDest->z[len] = 0;
73214     pDest->z[len+1] = 0;
73215     pDest->flags = fx|MEM_Term;
73216   }
73217 op_column_error:
73218   UPDATE_MAX_BLOBSIZE(pDest);
73219   REGISTER_TRACE(pOp->p3, pDest);
73220   break;
73221 }
73222
73223 /* Opcode: Affinity P1 P2 * P4 *
73224 ** Synopsis: affinity(r[P1@P2])
73225 **
73226 ** Apply affinities to a range of P2 registers starting with P1.
73227 **
73228 ** P4 is a string that is P2 characters long. The nth character of the
73229 ** string indicates the column affinity that should be used for the nth
73230 ** memory cell in the range.
73231 */
73232 case OP_Affinity: {
73233   const char *zAffinity;   /* The affinity to be applied */
73234   char cAff;               /* A single character of affinity */
73235
73236   zAffinity = pOp->p4.z;
73237   assert( zAffinity!=0 );
73238   assert( zAffinity[pOp->p2]==0 );
73239   pIn1 = &aMem[pOp->p1];
73240   while( (cAff = *(zAffinity++))!=0 ){
73241     assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
73242     assert( memIsValid(pIn1) );
73243     applyAffinity(pIn1, cAff, encoding);
73244     pIn1++;
73245   }
73246   break;
73247 }
73248
73249 /* Opcode: MakeRecord P1 P2 P3 P4 *
73250 ** Synopsis: r[P3]=mkrec(r[P1@P2])
73251 **
73252 ** Convert P2 registers beginning with P1 into the [record format]
73253 ** use as a data record in a database table or as a key
73254 ** in an index.  The OP_Column opcode can decode the record later.
73255 **
73256 ** P4 may be a string that is P2 characters long.  The nth character of the
73257 ** string indicates the column affinity that should be used for the nth
73258 ** field of the index key.
73259 **
73260 ** The mapping from character to affinity is given by the SQLITE_AFF_
73261 ** macros defined in sqliteInt.h.
73262 **
73263 ** If P4 is NULL then all index fields have the affinity NONE.
73264 */
73265 case OP_MakeRecord: {
73266   u8 *zNewRecord;        /* A buffer to hold the data for the new record */
73267   Mem *pRec;             /* The new record */
73268   u64 nData;             /* Number of bytes of data space */
73269   int nHdr;              /* Number of bytes of header space */
73270   i64 nByte;             /* Data space required for this record */
73271   int nZero;             /* Number of zero bytes at the end of the record */
73272   int nVarint;           /* Number of bytes in a varint */
73273   u32 serial_type;       /* Type field */
73274   Mem *pData0;           /* First field to be combined into the record */
73275   Mem *pLast;            /* Last field of the record */
73276   int nField;            /* Number of fields in the record */
73277   char *zAffinity;       /* The affinity string for the record */
73278   int file_format;       /* File format to use for encoding */
73279   int i;                 /* Space used in zNewRecord[] header */
73280   int j;                 /* Space used in zNewRecord[] content */
73281   int len;               /* Length of a field */
73282
73283   /* Assuming the record contains N fields, the record format looks
73284   ** like this:
73285   **
73286   ** ------------------------------------------------------------------------
73287   ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 | 
73288   ** ------------------------------------------------------------------------
73289   **
73290   ** Data(0) is taken from register P1.  Data(1) comes from register P1+1
73291   ** and so forth.
73292   **
73293   ** Each type field is a varint representing the serial type of the 
73294   ** corresponding data element (see sqlite3VdbeSerialType()). The
73295   ** hdr-size field is also a varint which is the offset from the beginning
73296   ** of the record to data0.
73297   */
73298   nData = 0;         /* Number of bytes of data space */
73299   nHdr = 0;          /* Number of bytes of header space */
73300   nZero = 0;         /* Number of zero bytes at the end of the record */
73301   nField = pOp->p1;
73302   zAffinity = pOp->p4.z;
73303   assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem-p->nCursor)+1 );
73304   pData0 = &aMem[nField];
73305   nField = pOp->p2;
73306   pLast = &pData0[nField-1];
73307   file_format = p->minWriteFileFormat;
73308
73309   /* Identify the output register */
73310   assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
73311   pOut = &aMem[pOp->p3];
73312   memAboutToChange(p, pOut);
73313
73314   /* Apply the requested affinity to all inputs
73315   */
73316   assert( pData0<=pLast );
73317   if( zAffinity ){
73318     pRec = pData0;
73319     do{
73320       applyAffinity(pRec++, *(zAffinity++), encoding);
73321       assert( zAffinity[0]==0 || pRec<=pLast );
73322     }while( zAffinity[0] );
73323   }
73324
73325   /* Loop through the elements that will make up the record to figure
73326   ** out how much space is required for the new record.
73327   */
73328   pRec = pLast;
73329   do{
73330     assert( memIsValid(pRec) );
73331     pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format);
73332     len = sqlite3VdbeSerialTypeLen(serial_type);
73333     if( pRec->flags & MEM_Zero ){
73334       if( nData ){
73335         sqlite3VdbeMemExpandBlob(pRec);
73336       }else{
73337         nZero += pRec->u.nZero;
73338         len -= pRec->u.nZero;
73339       }
73340     }
73341     nData += len;
73342     testcase( serial_type==127 );
73343     testcase( serial_type==128 );
73344     nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
73345   }while( (--pRec)>=pData0 );
73346
73347   /* EVIDENCE-OF: R-22564-11647 The header begins with a single varint
73348   ** which determines the total number of bytes in the header. The varint
73349   ** value is the size of the header in bytes including the size varint
73350   ** itself. */
73351   testcase( nHdr==126 );
73352   testcase( nHdr==127 );
73353   if( nHdr<=126 ){
73354     /* The common case */
73355     nHdr += 1;
73356   }else{
73357     /* Rare case of a really large header */
73358     nVarint = sqlite3VarintLen(nHdr);
73359     nHdr += nVarint;
73360     if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
73361   }
73362   nByte = nHdr+nData;
73363   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
73364     goto too_big;
73365   }
73366
73367   /* Make sure the output register has a buffer large enough to store 
73368   ** the new record. The output register (pOp->p3) is not allowed to
73369   ** be one of the input registers (because the following call to
73370   ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
73371   */
73372   if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
73373     goto no_mem;
73374   }
73375   zNewRecord = (u8 *)pOut->z;
73376
73377   /* Write the record */
73378   i = putVarint32(zNewRecord, nHdr);
73379   j = nHdr;
73380   assert( pData0<=pLast );
73381   pRec = pData0;
73382   do{
73383     serial_type = pRec->uTemp;
73384     /* EVIDENCE-OF: R-06529-47362 Following the size varint are one or more
73385     ** additional varints, one per column. */
73386     i += putVarint32(&zNewRecord[i], serial_type);            /* serial type */
73387     /* EVIDENCE-OF: R-64536-51728 The values for each column in the record
73388     ** immediately follow the header. */
73389     j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
73390   }while( (++pRec)<=pLast );
73391   assert( i==nHdr );
73392   assert( j==nByte );
73393
73394   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
73395   pOut->n = (int)nByte;
73396   pOut->flags = MEM_Blob;
73397   if( nZero ){
73398     pOut->u.nZero = nZero;
73399     pOut->flags |= MEM_Zero;
73400   }
73401   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever converted to text */
73402   REGISTER_TRACE(pOp->p3, pOut);
73403   UPDATE_MAX_BLOBSIZE(pOut);
73404   break;
73405 }
73406
73407 /* Opcode: Count P1 P2 * * *
73408 ** Synopsis: r[P2]=count()
73409 **
73410 ** Store the number of entries (an integer value) in the table or index 
73411 ** opened by cursor P1 in register P2
73412 */
73413 #ifndef SQLITE_OMIT_BTREECOUNT
73414 case OP_Count: {         /* out2-prerelease */
73415   i64 nEntry;
73416   BtCursor *pCrsr;
73417
73418   pCrsr = p->apCsr[pOp->p1]->pCursor;
73419   assert( pCrsr );
73420   nEntry = 0;  /* Not needed.  Only used to silence a warning. */
73421   rc = sqlite3BtreeCount(pCrsr, &nEntry);
73422   pOut->u.i = nEntry;
73423   break;
73424 }
73425 #endif
73426
73427 /* Opcode: Savepoint P1 * * P4 *
73428 **
73429 ** Open, release or rollback the savepoint named by parameter P4, depending
73430 ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
73431 ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
73432 */
73433 case OP_Savepoint: {
73434   int p1;                         /* Value of P1 operand */
73435   char *zName;                    /* Name of savepoint */
73436   int nName;
73437   Savepoint *pNew;
73438   Savepoint *pSavepoint;
73439   Savepoint *pTmp;
73440   int iSavepoint;
73441   int ii;
73442
73443   p1 = pOp->p1;
73444   zName = pOp->p4.z;
73445
73446   /* Assert that the p1 parameter is valid. Also that if there is no open
73447   ** transaction, then there cannot be any savepoints. 
73448   */
73449   assert( db->pSavepoint==0 || db->autoCommit==0 );
73450   assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
73451   assert( db->pSavepoint || db->isTransactionSavepoint==0 );
73452   assert( checkSavepointCount(db) );
73453   assert( p->bIsReader );
73454
73455   if( p1==SAVEPOINT_BEGIN ){
73456     if( db->nVdbeWrite>0 ){
73457       /* A new savepoint cannot be created if there are active write 
73458       ** statements (i.e. open read/write incremental blob handles).
73459       */
73460       sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
73461         "SQL statements in progress");
73462       rc = SQLITE_BUSY;
73463     }else{
73464       nName = sqlite3Strlen30(zName);
73465
73466 #ifndef SQLITE_OMIT_VIRTUALTABLE
73467       /* This call is Ok even if this savepoint is actually a transaction
73468       ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
73469       ** If this is a transaction savepoint being opened, it is guaranteed
73470       ** that the db->aVTrans[] array is empty.  */
73471       assert( db->autoCommit==0 || db->nVTrans==0 );
73472       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
73473                                 db->nStatement+db->nSavepoint);
73474       if( rc!=SQLITE_OK ) goto abort_due_to_error;
73475 #endif
73476
73477       /* Create a new savepoint structure. */
73478       pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
73479       if( pNew ){
73480         pNew->zName = (char *)&pNew[1];
73481         memcpy(pNew->zName, zName, nName+1);
73482     
73483         /* If there is no open transaction, then mark this as a special
73484         ** "transaction savepoint". */
73485         if( db->autoCommit ){
73486           db->autoCommit = 0;
73487           db->isTransactionSavepoint = 1;
73488         }else{
73489           db->nSavepoint++;
73490         }
73491     
73492         /* Link the new savepoint into the database handle's list. */
73493         pNew->pNext = db->pSavepoint;
73494         db->pSavepoint = pNew;
73495         pNew->nDeferredCons = db->nDeferredCons;
73496         pNew->nDeferredImmCons = db->nDeferredImmCons;
73497       }
73498     }
73499   }else{
73500     iSavepoint = 0;
73501
73502     /* Find the named savepoint. If there is no such savepoint, then an
73503     ** an error is returned to the user.  */
73504     for(
73505       pSavepoint = db->pSavepoint; 
73506       pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
73507       pSavepoint = pSavepoint->pNext
73508     ){
73509       iSavepoint++;
73510     }
73511     if( !pSavepoint ){
73512       sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", zName);
73513       rc = SQLITE_ERROR;
73514     }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
73515       /* It is not possible to release (commit) a savepoint if there are 
73516       ** active write statements.
73517       */
73518       sqlite3SetString(&p->zErrMsg, db, 
73519         "cannot release savepoint - SQL statements in progress"
73520       );
73521       rc = SQLITE_BUSY;
73522     }else{
73523
73524       /* Determine whether or not this is a transaction savepoint. If so,
73525       ** and this is a RELEASE command, then the current transaction 
73526       ** is committed. 
73527       */
73528       int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
73529       if( isTransaction && p1==SAVEPOINT_RELEASE ){
73530         if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
73531           goto vdbe_return;
73532         }
73533         db->autoCommit = 1;
73534         if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
73535           p->pc = pc;
73536           db->autoCommit = 0;
73537           p->rc = rc = SQLITE_BUSY;
73538           goto vdbe_return;
73539         }
73540         db->isTransactionSavepoint = 0;
73541         rc = p->rc;
73542       }else{
73543         int isSchemaChange;
73544         iSavepoint = db->nSavepoint - iSavepoint - 1;
73545         if( p1==SAVEPOINT_ROLLBACK ){
73546           isSchemaChange = (db->flags & SQLITE_InternChanges)!=0;
73547           for(ii=0; ii<db->nDb; ii++){
73548             rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
73549                                        SQLITE_ABORT_ROLLBACK,
73550                                        isSchemaChange==0);
73551             if( rc!=SQLITE_OK ) goto abort_due_to_error;
73552           }
73553         }else{
73554           isSchemaChange = 0;
73555         }
73556         for(ii=0; ii<db->nDb; ii++){
73557           rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
73558           if( rc!=SQLITE_OK ){
73559             goto abort_due_to_error;
73560           }
73561         }
73562         if( isSchemaChange ){
73563           sqlite3ExpirePreparedStatements(db);
73564           sqlite3ResetAllSchemasOfConnection(db);
73565           db->flags = (db->flags | SQLITE_InternChanges);
73566         }
73567       }
73568   
73569       /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all 
73570       ** savepoints nested inside of the savepoint being operated on. */
73571       while( db->pSavepoint!=pSavepoint ){
73572         pTmp = db->pSavepoint;
73573         db->pSavepoint = pTmp->pNext;
73574         sqlite3DbFree(db, pTmp);
73575         db->nSavepoint--;
73576       }
73577
73578       /* If it is a RELEASE, then destroy the savepoint being operated on 
73579       ** too. If it is a ROLLBACK TO, then set the number of deferred 
73580       ** constraint violations present in the database to the value stored
73581       ** when the savepoint was created.  */
73582       if( p1==SAVEPOINT_RELEASE ){
73583         assert( pSavepoint==db->pSavepoint );
73584         db->pSavepoint = pSavepoint->pNext;
73585         sqlite3DbFree(db, pSavepoint);
73586         if( !isTransaction ){
73587           db->nSavepoint--;
73588         }
73589       }else{
73590         db->nDeferredCons = pSavepoint->nDeferredCons;
73591         db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
73592       }
73593
73594       if( !isTransaction ){
73595         rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
73596         if( rc!=SQLITE_OK ) goto abort_due_to_error;
73597       }
73598     }
73599   }
73600
73601   break;
73602 }
73603
73604 /* Opcode: AutoCommit P1 P2 * * *
73605 **
73606 ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
73607 ** back any currently active btree transactions. If there are any active
73608 ** VMs (apart from this one), then a ROLLBACK fails.  A COMMIT fails if
73609 ** there are active writing VMs or active VMs that use shared cache.
73610 **
73611 ** This instruction causes the VM to halt.
73612 */
73613 case OP_AutoCommit: {
73614   int desiredAutoCommit;
73615   int iRollback;
73616   int turnOnAC;
73617
73618   desiredAutoCommit = pOp->p1;
73619   iRollback = pOp->p2;
73620   turnOnAC = desiredAutoCommit && !db->autoCommit;
73621   assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
73622   assert( desiredAutoCommit==1 || iRollback==0 );
73623   assert( db->nVdbeActive>0 );  /* At least this one VM is active */
73624   assert( p->bIsReader );
73625
73626 #if 0
73627   if( turnOnAC && iRollback && db->nVdbeActive>1 ){
73628     /* If this instruction implements a ROLLBACK and other VMs are
73629     ** still running, and a transaction is active, return an error indicating
73630     ** that the other VMs must complete first. 
73631     */
73632     sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
73633         "SQL statements in progress");
73634     rc = SQLITE_BUSY;
73635   }else
73636 #endif
73637   if( turnOnAC && !iRollback && db->nVdbeWrite>0 ){
73638     /* If this instruction implements a COMMIT and other VMs are writing
73639     ** return an error indicating that the other VMs must complete first. 
73640     */
73641     sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
73642         "SQL statements in progress");
73643     rc = SQLITE_BUSY;
73644   }else if( desiredAutoCommit!=db->autoCommit ){
73645     if( iRollback ){
73646       assert( desiredAutoCommit==1 );
73647       sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
73648       db->autoCommit = 1;
73649     }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
73650       goto vdbe_return;
73651     }else{
73652       db->autoCommit = (u8)desiredAutoCommit;
73653       if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
73654         p->pc = pc;
73655         db->autoCommit = (u8)(1-desiredAutoCommit);
73656         p->rc = rc = SQLITE_BUSY;
73657         goto vdbe_return;
73658       }
73659     }
73660     assert( db->nStatement==0 );
73661     sqlite3CloseSavepoints(db);
73662     if( p->rc==SQLITE_OK ){
73663       rc = SQLITE_DONE;
73664     }else{
73665       rc = SQLITE_ERROR;
73666     }
73667     goto vdbe_return;
73668   }else{
73669     sqlite3SetString(&p->zErrMsg, db,
73670         (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
73671         (iRollback)?"cannot rollback - no transaction is active":
73672                    "cannot commit - no transaction is active"));
73673          
73674     rc = SQLITE_ERROR;
73675   }
73676   break;
73677 }
73678
73679 /* Opcode: Transaction P1 P2 P3 P4 P5
73680 **
73681 ** Begin a transaction on database P1 if a transaction is not already
73682 ** active.
73683 ** If P2 is non-zero, then a write-transaction is started, or if a 
73684 ** read-transaction is already active, it is upgraded to a write-transaction.
73685 ** If P2 is zero, then a read-transaction is started.
73686 **
73687 ** P1 is the index of the database file on which the transaction is
73688 ** started.  Index 0 is the main database file and index 1 is the
73689 ** file used for temporary tables.  Indices of 2 or more are used for
73690 ** attached databases.
73691 **
73692 ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
73693 ** true (this flag is set if the Vdbe may modify more than one row and may
73694 ** throw an ABORT exception), a statement transaction may also be opened.
73695 ** More specifically, a statement transaction is opened iff the database
73696 ** connection is currently not in autocommit mode, or if there are other
73697 ** active statements. A statement transaction allows the changes made by this
73698 ** VDBE to be rolled back after an error without having to roll back the
73699 ** entire transaction. If no error is encountered, the statement transaction
73700 ** will automatically commit when the VDBE halts.
73701 **
73702 ** If P5!=0 then this opcode also checks the schema cookie against P3
73703 ** and the schema generation counter against P4.
73704 ** The cookie changes its value whenever the database schema changes.
73705 ** This operation is used to detect when that the cookie has changed
73706 ** and that the current process needs to reread the schema.  If the schema
73707 ** cookie in P3 differs from the schema cookie in the database header or
73708 ** if the schema generation counter in P4 differs from the current
73709 ** generation counter, then an SQLITE_SCHEMA error is raised and execution
73710 ** halts.  The sqlite3_step() wrapper function might then reprepare the
73711 ** statement and rerun it from the beginning.
73712 */
73713 case OP_Transaction: {
73714   Btree *pBt;
73715   int iMeta;
73716   int iGen;
73717
73718   assert( p->bIsReader );
73719   assert( p->readOnly==0 || pOp->p2==0 );
73720   assert( pOp->p1>=0 && pOp->p1<db->nDb );
73721   assert( DbMaskTest(p->btreeMask, pOp->p1) );
73722   if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
73723     rc = SQLITE_READONLY;
73724     goto abort_due_to_error;
73725   }
73726   pBt = db->aDb[pOp->p1].pBt;
73727
73728   if( pBt ){
73729     rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
73730     if( rc==SQLITE_BUSY ){
73731       p->pc = pc;
73732       p->rc = rc = SQLITE_BUSY;
73733       goto vdbe_return;
73734     }
73735     if( rc!=SQLITE_OK ){
73736       goto abort_due_to_error;
73737     }
73738
73739     if( pOp->p2 && p->usesStmtJournal 
73740      && (db->autoCommit==0 || db->nVdbeRead>1) 
73741     ){
73742       assert( sqlite3BtreeIsInTrans(pBt) );
73743       if( p->iStatement==0 ){
73744         assert( db->nStatement>=0 && db->nSavepoint>=0 );
73745         db->nStatement++; 
73746         p->iStatement = db->nSavepoint + db->nStatement;
73747       }
73748
73749       rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
73750       if( rc==SQLITE_OK ){
73751         rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
73752       }
73753
73754       /* Store the current value of the database handles deferred constraint
73755       ** counter. If the statement transaction needs to be rolled back,
73756       ** the value of this counter needs to be restored too.  */
73757       p->nStmtDefCons = db->nDeferredCons;
73758       p->nStmtDefImmCons = db->nDeferredImmCons;
73759     }
73760
73761     /* Gather the schema version number for checking:
73762     ** IMPLEMENTATION-OF: R-32195-19465 The schema version is used by SQLite
73763     ** each time a query is executed to ensure that the internal cache of the
73764     ** schema used when compiling the SQL query matches the schema of the
73765     ** database against which the compiled query is actually executed.
73766     */
73767     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
73768     iGen = db->aDb[pOp->p1].pSchema->iGeneration;
73769   }else{
73770     iGen = iMeta = 0;
73771   }
73772   assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
73773   if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
73774     sqlite3DbFree(db, p->zErrMsg);
73775     p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
73776     /* If the schema-cookie from the database file matches the cookie 
73777     ** stored with the in-memory representation of the schema, do
73778     ** not reload the schema from the database file.
73779     **
73780     ** If virtual-tables are in use, this is not just an optimization.
73781     ** Often, v-tables store their data in other SQLite tables, which
73782     ** are queried from within xNext() and other v-table methods using
73783     ** prepared queries. If such a query is out-of-date, we do not want to
73784     ** discard the database schema, as the user code implementing the
73785     ** v-table would have to be ready for the sqlite3_vtab structure itself
73786     ** to be invalidated whenever sqlite3_step() is called from within 
73787     ** a v-table method.
73788     */
73789     if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
73790       sqlite3ResetOneSchema(db, pOp->p1);
73791     }
73792     p->expired = 1;
73793     rc = SQLITE_SCHEMA;
73794   }
73795   break;
73796 }
73797
73798 /* Opcode: ReadCookie P1 P2 P3 * *
73799 **
73800 ** Read cookie number P3 from database P1 and write it into register P2.
73801 ** P3==1 is the schema version.  P3==2 is the database format.
73802 ** P3==3 is the recommended pager cache size, and so forth.  P1==0 is
73803 ** the main database file and P1==1 is the database file used to store
73804 ** temporary tables.
73805 **
73806 ** There must be a read-lock on the database (either a transaction
73807 ** must be started or there must be an open cursor) before
73808 ** executing this instruction.
73809 */
73810 case OP_ReadCookie: {               /* out2-prerelease */
73811   int iMeta;
73812   int iDb;
73813   int iCookie;
73814
73815   assert( p->bIsReader );
73816   iDb = pOp->p1;
73817   iCookie = pOp->p3;
73818   assert( pOp->p3<SQLITE_N_BTREE_META );
73819   assert( iDb>=0 && iDb<db->nDb );
73820   assert( db->aDb[iDb].pBt!=0 );
73821   assert( DbMaskTest(p->btreeMask, iDb) );
73822
73823   sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
73824   pOut->u.i = iMeta;
73825   break;
73826 }
73827
73828 /* Opcode: SetCookie P1 P2 P3 * *
73829 **
73830 ** Write the content of register P3 (interpreted as an integer)
73831 ** into cookie number P2 of database P1.  P2==1 is the schema version.  
73832 ** P2==2 is the database format. P2==3 is the recommended pager cache 
73833 ** size, and so forth.  P1==0 is the main database file and P1==1 is the 
73834 ** database file used to store temporary tables.
73835 **
73836 ** A transaction must be started before executing this opcode.
73837 */
73838 case OP_SetCookie: {       /* in3 */
73839   Db *pDb;
73840   assert( pOp->p2<SQLITE_N_BTREE_META );
73841   assert( pOp->p1>=0 && pOp->p1<db->nDb );
73842   assert( DbMaskTest(p->btreeMask, pOp->p1) );
73843   assert( p->readOnly==0 );
73844   pDb = &db->aDb[pOp->p1];
73845   assert( pDb->pBt!=0 );
73846   assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
73847   pIn3 = &aMem[pOp->p3];
73848   sqlite3VdbeMemIntegerify(pIn3);
73849   /* See note about index shifting on OP_ReadCookie */
73850   rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, (int)pIn3->u.i);
73851   if( pOp->p2==BTREE_SCHEMA_VERSION ){
73852     /* When the schema cookie changes, record the new cookie internally */
73853     pDb->pSchema->schema_cookie = (int)pIn3->u.i;
73854     db->flags |= SQLITE_InternChanges;
73855   }else if( pOp->p2==BTREE_FILE_FORMAT ){
73856     /* Record changes in the file format */
73857     pDb->pSchema->file_format = (u8)pIn3->u.i;
73858   }
73859   if( pOp->p1==1 ){
73860     /* Invalidate all prepared statements whenever the TEMP database
73861     ** schema is changed.  Ticket #1644 */
73862     sqlite3ExpirePreparedStatements(db);
73863     p->expired = 0;
73864   }
73865   break;
73866 }
73867
73868 /* Opcode: OpenRead P1 P2 P3 P4 P5
73869 ** Synopsis: root=P2 iDb=P3
73870 **
73871 ** Open a read-only cursor for the database table whose root page is
73872 ** P2 in a database file.  The database file is determined by P3. 
73873 ** P3==0 means the main database, P3==1 means the database used for 
73874 ** temporary tables, and P3>1 means used the corresponding attached
73875 ** database.  Give the new cursor an identifier of P1.  The P1
73876 ** values need not be contiguous but all P1 values should be small integers.
73877 ** It is an error for P1 to be negative.
73878 **
73879 ** If P5!=0 then use the content of register P2 as the root page, not
73880 ** the value of P2 itself.
73881 **
73882 ** There will be a read lock on the database whenever there is an
73883 ** open cursor.  If the database was unlocked prior to this instruction
73884 ** then a read lock is acquired as part of this instruction.  A read
73885 ** lock allows other processes to read the database but prohibits
73886 ** any other process from modifying the database.  The read lock is
73887 ** released when all cursors are closed.  If this instruction attempts
73888 ** to get a read lock but fails, the script terminates with an
73889 ** SQLITE_BUSY error code.
73890 **
73891 ** The P4 value may be either an integer (P4_INT32) or a pointer to
73892 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
73893 ** structure, then said structure defines the content and collating 
73894 ** sequence of the index being opened. Otherwise, if P4 is an integer 
73895 ** value, it is set to the number of columns in the table.
73896 **
73897 ** See also: OpenWrite, ReopenIdx
73898 */
73899 /* Opcode: ReopenIdx P1 P2 P3 P4 P5
73900 ** Synopsis: root=P2 iDb=P3
73901 **
73902 ** The ReopenIdx opcode works exactly like ReadOpen except that it first
73903 ** checks to see if the cursor on P1 is already open with a root page
73904 ** number of P2 and if it is this opcode becomes a no-op.  In other words,
73905 ** if the cursor is already open, do not reopen it.
73906 **
73907 ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
73908 ** a P4_KEYINFO object.  Furthermore, the P3 value must be the same as
73909 ** every other ReopenIdx or OpenRead for the same cursor number.
73910 **
73911 ** See the OpenRead opcode documentation for additional information.
73912 */
73913 /* Opcode: OpenWrite P1 P2 P3 P4 P5
73914 ** Synopsis: root=P2 iDb=P3
73915 **
73916 ** Open a read/write cursor named P1 on the table or index whose root
73917 ** page is P2.  Or if P5!=0 use the content of register P2 to find the
73918 ** root page.
73919 **
73920 ** The P4 value may be either an integer (P4_INT32) or a pointer to
73921 ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo 
73922 ** structure, then said structure defines the content and collating 
73923 ** sequence of the index being opened. Otherwise, if P4 is an integer 
73924 ** value, it is set to the number of columns in the table, or to the
73925 ** largest index of any column of the table that is actually used.
73926 **
73927 ** This instruction works just like OpenRead except that it opens the cursor
73928 ** in read/write mode.  For a given table, there can be one or more read-only
73929 ** cursors or a single read/write cursor but not both.
73930 **
73931 ** See also OpenRead.
73932 */
73933 case OP_ReopenIdx: {
73934   int nField;
73935   KeyInfo *pKeyInfo;
73936   int p2;
73937   int iDb;
73938   int wrFlag;
73939   Btree *pX;
73940   VdbeCursor *pCur;
73941   Db *pDb;
73942
73943   assert( pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
73944   assert( pOp->p4type==P4_KEYINFO );
73945   pCur = p->apCsr[pOp->p1];
73946   if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
73947     assert( pCur->iDb==pOp->p3 );      /* Guaranteed by the code generator */
73948     goto open_cursor_set_hints;
73949   }
73950   /* If the cursor is not currently open or is open on a different
73951   ** index, then fall through into OP_OpenRead to force a reopen */
73952 case OP_OpenRead:
73953 case OP_OpenWrite:
73954
73955   assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR|OPFLAG_SEEKEQ))==pOp->p5 );
73956   assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 || pOp->p5==OPFLAG_SEEKEQ );
73957   assert( p->bIsReader );
73958   assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
73959           || p->readOnly==0 );
73960
73961   if( p->expired ){
73962     rc = SQLITE_ABORT_ROLLBACK;
73963     break;
73964   }
73965
73966   nField = 0;
73967   pKeyInfo = 0;
73968   p2 = pOp->p2;
73969   iDb = pOp->p3;
73970   assert( iDb>=0 && iDb<db->nDb );
73971   assert( DbMaskTest(p->btreeMask, iDb) );
73972   pDb = &db->aDb[iDb];
73973   pX = pDb->pBt;
73974   assert( pX!=0 );
73975   if( pOp->opcode==OP_OpenWrite ){
73976     wrFlag = 1;
73977     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
73978     if( pDb->pSchema->file_format < p->minWriteFileFormat ){
73979       p->minWriteFileFormat = pDb->pSchema->file_format;
73980     }
73981   }else{
73982     wrFlag = 0;
73983   }
73984   if( pOp->p5 & OPFLAG_P2ISREG ){
73985     assert( p2>0 );
73986     assert( p2<=(p->nMem-p->nCursor) );
73987     pIn2 = &aMem[p2];
73988     assert( memIsValid(pIn2) );
73989     assert( (pIn2->flags & MEM_Int)!=0 );
73990     sqlite3VdbeMemIntegerify(pIn2);
73991     p2 = (int)pIn2->u.i;
73992     /* The p2 value always comes from a prior OP_CreateTable opcode and
73993     ** that opcode will always set the p2 value to 2 or more or else fail.
73994     ** If there were a failure, the prepared statement would have halted
73995     ** before reaching this instruction. */
73996     if( NEVER(p2<2) ) {
73997       rc = SQLITE_CORRUPT_BKPT;
73998       goto abort_due_to_error;
73999     }
74000   }
74001   if( pOp->p4type==P4_KEYINFO ){
74002     pKeyInfo = pOp->p4.pKeyInfo;
74003     assert( pKeyInfo->enc==ENC(db) );
74004     assert( pKeyInfo->db==db );
74005     nField = pKeyInfo->nField+pKeyInfo->nXField;
74006   }else if( pOp->p4type==P4_INT32 ){
74007     nField = pOp->p4.i;
74008   }
74009   assert( pOp->p1>=0 );
74010   assert( nField>=0 );
74011   testcase( nField==0 );  /* Table with INTEGER PRIMARY KEY and nothing else */
74012   pCur = allocateCursor(p, pOp->p1, nField, iDb, 1);
74013   if( pCur==0 ) goto no_mem;
74014   pCur->nullRow = 1;
74015   pCur->isOrdered = 1;
74016   pCur->pgnoRoot = p2;
74017   rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->pCursor);
74018   pCur->pKeyInfo = pKeyInfo;
74019   /* Set the VdbeCursor.isTable variable. Previous versions of
74020   ** SQLite used to check if the root-page flags were sane at this point
74021   ** and report database corruption if they were not, but this check has
74022   ** since moved into the btree layer.  */  
74023   pCur->isTable = pOp->p4type!=P4_KEYINFO;
74024
74025 open_cursor_set_hints:
74026   assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
74027   assert( OPFLAG_SEEKEQ==BTREE_SEEK_EQ );
74028   sqlite3BtreeCursorHints(pCur->pCursor,
74029                           (pOp->p5 & (OPFLAG_BULKCSR|OPFLAG_SEEKEQ)));
74030   break;
74031 }
74032
74033 /* Opcode: OpenEphemeral P1 P2 * P4 P5
74034 ** Synopsis: nColumn=P2
74035 **
74036 ** Open a new cursor P1 to a transient table.
74037 ** The cursor is always opened read/write even if 
74038 ** the main database is read-only.  The ephemeral
74039 ** table is deleted automatically when the cursor is closed.
74040 **
74041 ** P2 is the number of columns in the ephemeral table.
74042 ** The cursor points to a BTree table if P4==0 and to a BTree index
74043 ** if P4 is not 0.  If P4 is not NULL, it points to a KeyInfo structure
74044 ** that defines the format of keys in the index.
74045 **
74046 ** The P5 parameter can be a mask of the BTREE_* flags defined
74047 ** in btree.h.  These flags control aspects of the operation of
74048 ** the btree.  The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
74049 ** added automatically.
74050 */
74051 /* Opcode: OpenAutoindex P1 P2 * P4 *
74052 ** Synopsis: nColumn=P2
74053 **
74054 ** This opcode works the same as OP_OpenEphemeral.  It has a
74055 ** different name to distinguish its use.  Tables created using
74056 ** by this opcode will be used for automatically created transient
74057 ** indices in joins.
74058 */
74059 case OP_OpenAutoindex: 
74060 case OP_OpenEphemeral: {
74061   VdbeCursor *pCx;
74062   KeyInfo *pKeyInfo;
74063
74064   static const int vfsFlags = 
74065       SQLITE_OPEN_READWRITE |
74066       SQLITE_OPEN_CREATE |
74067       SQLITE_OPEN_EXCLUSIVE |
74068       SQLITE_OPEN_DELETEONCLOSE |
74069       SQLITE_OPEN_TRANSIENT_DB;
74070   assert( pOp->p1>=0 );
74071   assert( pOp->p2>=0 );
74072   pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
74073   if( pCx==0 ) goto no_mem;
74074   pCx->nullRow = 1;
74075   pCx->isEphemeral = 1;
74076   rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt, 
74077                         BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
74078   if( rc==SQLITE_OK ){
74079     rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
74080   }
74081   if( rc==SQLITE_OK ){
74082     /* If a transient index is required, create it by calling
74083     ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
74084     ** opening it. If a transient table is required, just use the
74085     ** automatically created table with root-page 1 (an BLOB_INTKEY table).
74086     */
74087     if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
74088       int pgno;
74089       assert( pOp->p4type==P4_KEYINFO );
74090       rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5); 
74091       if( rc==SQLITE_OK ){
74092         assert( pgno==MASTER_ROOT+1 );
74093         assert( pKeyInfo->db==db );
74094         assert( pKeyInfo->enc==ENC(db) );
74095         pCx->pKeyInfo = pKeyInfo;
74096         rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, pKeyInfo, pCx->pCursor);
74097       }
74098       pCx->isTable = 0;
74099     }else{
74100       rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
74101       pCx->isTable = 1;
74102     }
74103   }
74104   pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
74105   break;
74106 }
74107
74108 /* Opcode: SorterOpen P1 P2 P3 P4 *
74109 **
74110 ** This opcode works like OP_OpenEphemeral except that it opens
74111 ** a transient index that is specifically designed to sort large
74112 ** tables using an external merge-sort algorithm.
74113 **
74114 ** If argument P3 is non-zero, then it indicates that the sorter may
74115 ** assume that a stable sort considering the first P3 fields of each
74116 ** key is sufficient to produce the required results.
74117 */
74118 case OP_SorterOpen: {
74119   VdbeCursor *pCx;
74120
74121   assert( pOp->p1>=0 );
74122   assert( pOp->p2>=0 );
74123   pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
74124   if( pCx==0 ) goto no_mem;
74125   pCx->pKeyInfo = pOp->p4.pKeyInfo;
74126   assert( pCx->pKeyInfo->db==db );
74127   assert( pCx->pKeyInfo->enc==ENC(db) );
74128   rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
74129   break;
74130 }
74131
74132 /* Opcode: SequenceTest P1 P2 * * *
74133 ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
74134 **
74135 ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
74136 ** to P2. Regardless of whether or not the jump is taken, increment the
74137 ** the sequence value.
74138 */
74139 case OP_SequenceTest: {
74140   VdbeCursor *pC;
74141   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
74142   pC = p->apCsr[pOp->p1];
74143   assert( pC->pSorter );
74144   if( (pC->seqCount++)==0 ){
74145     pc = pOp->p2 - 1;
74146   }
74147   break;
74148 }
74149
74150 /* Opcode: OpenPseudo P1 P2 P3 * *
74151 ** Synopsis: P3 columns in r[P2]
74152 **
74153 ** Open a new cursor that points to a fake table that contains a single
74154 ** row of data.  The content of that one row is the content of memory
74155 ** register P2.  In other words, cursor P1 becomes an alias for the 
74156 ** MEM_Blob content contained in register P2.
74157 **
74158 ** A pseudo-table created by this opcode is used to hold a single
74159 ** row output from the sorter so that the row can be decomposed into
74160 ** individual columns using the OP_Column opcode.  The OP_Column opcode
74161 ** is the only cursor opcode that works with a pseudo-table.
74162 **
74163 ** P3 is the number of fields in the records that will be stored by
74164 ** the pseudo-table.
74165 */
74166 case OP_OpenPseudo: {
74167   VdbeCursor *pCx;
74168
74169   assert( pOp->p1>=0 );
74170   assert( pOp->p3>=0 );
74171   pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
74172   if( pCx==0 ) goto no_mem;
74173   pCx->nullRow = 1;
74174   pCx->pseudoTableReg = pOp->p2;
74175   pCx->isTable = 1;
74176   assert( pOp->p5==0 );
74177   break;
74178 }
74179
74180 /* Opcode: Close P1 * * * *
74181 **
74182 ** Close a cursor previously opened as P1.  If P1 is not
74183 ** currently open, this instruction is a no-op.
74184 */
74185 case OP_Close: {
74186   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
74187   sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
74188   p->apCsr[pOp->p1] = 0;
74189   break;
74190 }
74191
74192 /* Opcode: SeekGE P1 P2 P3 P4 *
74193 ** Synopsis: key=r[P3@P4]
74194 **
74195 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
74196 ** use the value in register P3 as the key.  If cursor P1 refers 
74197 ** to an SQL index, then P3 is the first in an array of P4 registers 
74198 ** that are used as an unpacked index key. 
74199 **
74200 ** Reposition cursor P1 so that  it points to the smallest entry that 
74201 ** is greater than or equal to the key value. If there are no records 
74202 ** greater than or equal to the key and P2 is not zero, then jump to P2.
74203 **
74204 ** This opcode leaves the cursor configured to move in forward order,
74205 ** from the beginning toward the end.  In other words, the cursor is
74206 ** configured to use Next, not Prev.
74207 **
74208 ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
74209 */
74210 /* Opcode: SeekGT P1 P2 P3 P4 *
74211 ** Synopsis: key=r[P3@P4]
74212 **
74213 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
74214 ** use the value in register P3 as a key. If cursor P1 refers 
74215 ** to an SQL index, then P3 is the first in an array of P4 registers 
74216 ** that are used as an unpacked index key. 
74217 **
74218 ** Reposition cursor P1 so that  it points to the smallest entry that 
74219 ** is greater than the key value. If there are no records greater than 
74220 ** the key and P2 is not zero, then jump to P2.
74221 **
74222 ** This opcode leaves the cursor configured to move in forward order,
74223 ** from the beginning toward the end.  In other words, the cursor is
74224 ** configured to use Next, not Prev.
74225 **
74226 ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
74227 */
74228 /* Opcode: SeekLT P1 P2 P3 P4 * 
74229 ** Synopsis: key=r[P3@P4]
74230 **
74231 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
74232 ** use the value in register P3 as a key. If cursor P1 refers 
74233 ** to an SQL index, then P3 is the first in an array of P4 registers 
74234 ** that are used as an unpacked index key. 
74235 **
74236 ** Reposition cursor P1 so that  it points to the largest entry that 
74237 ** is less than the key value. If there are no records less than 
74238 ** the key and P2 is not zero, then jump to P2.
74239 **
74240 ** This opcode leaves the cursor configured to move in reverse order,
74241 ** from the end toward the beginning.  In other words, the cursor is
74242 ** configured to use Prev, not Next.
74243 **
74244 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
74245 */
74246 /* Opcode: SeekLE P1 P2 P3 P4 *
74247 ** Synopsis: key=r[P3@P4]
74248 **
74249 ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys), 
74250 ** use the value in register P3 as a key. If cursor P1 refers 
74251 ** to an SQL index, then P3 is the first in an array of P4 registers 
74252 ** that are used as an unpacked index key. 
74253 **
74254 ** Reposition cursor P1 so that it points to the largest entry that 
74255 ** is less than or equal to the key value. If there are no records 
74256 ** less than or equal to the key and P2 is not zero, then jump to P2.
74257 **
74258 ** This opcode leaves the cursor configured to move in reverse order,
74259 ** from the end toward the beginning.  In other words, the cursor is
74260 ** configured to use Prev, not Next.
74261 **
74262 ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
74263 */
74264 case OP_SeekLT:         /* jump, in3 */
74265 case OP_SeekLE:         /* jump, in3 */
74266 case OP_SeekGE:         /* jump, in3 */
74267 case OP_SeekGT: {       /* jump, in3 */
74268   int res;
74269   int oc;
74270   VdbeCursor *pC;
74271   UnpackedRecord r;
74272   int nField;
74273   i64 iKey;      /* The rowid we are to seek to */
74274
74275   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
74276   assert( pOp->p2!=0 );
74277   pC = p->apCsr[pOp->p1];
74278   assert( pC!=0 );
74279   assert( pC->pseudoTableReg==0 );
74280   assert( OP_SeekLE == OP_SeekLT+1 );
74281   assert( OP_SeekGE == OP_SeekLT+2 );
74282   assert( OP_SeekGT == OP_SeekLT+3 );
74283   assert( pC->isOrdered );
74284   assert( pC->pCursor!=0 );
74285   oc = pOp->opcode;
74286   pC->nullRow = 0;
74287 #ifdef SQLITE_DEBUG
74288   pC->seekOp = pOp->opcode;
74289 #endif
74290
74291   /* For a cursor with the BTREE_SEEK_EQ hint, only the OP_SeekGE and
74292   ** OP_SeekLE opcodes are allowed, and these must be immediately followed
74293   ** by an OP_IdxGT or OP_IdxLT opcode, respectively, with the same key.
74294   */
74295 #ifdef SQLITE_DEBUG
74296   if( sqlite3BtreeCursorHasHint(pC->pCursor, BTREE_SEEK_EQ) ){
74297     assert( pOp->opcode==OP_SeekGE || pOp->opcode==OP_SeekLE );
74298     assert( pOp[1].opcode==OP_IdxLT || pOp[1].opcode==OP_IdxGT );
74299     assert( pOp[1].p1==pOp[0].p1 );
74300     assert( pOp[1].p2==pOp[0].p2 );
74301     assert( pOp[1].p3==pOp[0].p3 );
74302     assert( pOp[1].p4.i==pOp[0].p4.i );
74303   }
74304 #endif
74305  
74306   if( pC->isTable ){
74307     /* The input value in P3 might be of any type: integer, real, string,
74308     ** blob, or NULL.  But it needs to be an integer before we can do
74309     ** the seek, so convert it. */
74310     pIn3 = &aMem[pOp->p3];
74311     if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
74312       applyNumericAffinity(pIn3, 0);
74313     }
74314     iKey = sqlite3VdbeIntValue(pIn3);
74315
74316     /* If the P3 value could not be converted into an integer without
74317     ** loss of information, then special processing is required... */
74318     if( (pIn3->flags & MEM_Int)==0 ){
74319       if( (pIn3->flags & MEM_Real)==0 ){
74320         /* If the P3 value cannot be converted into any kind of a number,
74321         ** then the seek is not possible, so jump to P2 */
74322         pc = pOp->p2 - 1;  VdbeBranchTaken(1,2);
74323         break;
74324       }
74325
74326       /* If the approximation iKey is larger than the actual real search
74327       ** term, substitute >= for > and < for <=. e.g. if the search term
74328       ** is 4.9 and the integer approximation 5:
74329       **
74330       **        (x >  4.9)    ->     (x >= 5)
74331       **        (x <= 4.9)    ->     (x <  5)
74332       */
74333       if( pIn3->u.r<(double)iKey ){
74334         assert( OP_SeekGE==(OP_SeekGT-1) );
74335         assert( OP_SeekLT==(OP_SeekLE-1) );
74336         assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
74337         if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
74338       }
74339
74340       /* If the approximation iKey is smaller than the actual real search
74341       ** term, substitute <= for < and > for >=.  */
74342       else if( pIn3->u.r>(double)iKey ){
74343         assert( OP_SeekLE==(OP_SeekLT+1) );
74344         assert( OP_SeekGT==(OP_SeekGE+1) );
74345         assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
74346         if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
74347       }
74348     } 
74349     rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
74350     pC->movetoTarget = iKey;  /* Used by OP_Delete */
74351     if( rc!=SQLITE_OK ){
74352       goto abort_due_to_error;
74353     }
74354   }else{
74355     nField = pOp->p4.i;
74356     assert( pOp->p4type==P4_INT32 );
74357     assert( nField>0 );
74358     r.pKeyInfo = pC->pKeyInfo;
74359     r.nField = (u16)nField;
74360
74361     /* The next line of code computes as follows, only faster:
74362     **   if( oc==OP_SeekGT || oc==OP_SeekLE ){
74363     **     r.default_rc = -1;
74364     **   }else{
74365     **     r.default_rc = +1;
74366     **   }
74367     */
74368     r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
74369     assert( oc!=OP_SeekGT || r.default_rc==-1 );
74370     assert( oc!=OP_SeekLE || r.default_rc==-1 );
74371     assert( oc!=OP_SeekGE || r.default_rc==+1 );
74372     assert( oc!=OP_SeekLT || r.default_rc==+1 );
74373
74374     r.aMem = &aMem[pOp->p3];
74375 #ifdef SQLITE_DEBUG
74376     { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
74377 #endif
74378     ExpandBlob(r.aMem);
74379     rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
74380     if( rc!=SQLITE_OK ){
74381       goto abort_due_to_error;
74382     }
74383   }
74384   pC->deferredMoveto = 0;
74385   pC->cacheStatus = CACHE_STALE;
74386 #ifdef SQLITE_TEST
74387   sqlite3_search_count++;
74388 #endif
74389   if( oc>=OP_SeekGE ){  assert( oc==OP_SeekGE || oc==OP_SeekGT );
74390     if( res<0 || (res==0 && oc==OP_SeekGT) ){
74391       res = 0;
74392       rc = sqlite3BtreeNext(pC->pCursor, &res);
74393       if( rc!=SQLITE_OK ) goto abort_due_to_error;
74394     }else{
74395       res = 0;
74396     }
74397   }else{
74398     assert( oc==OP_SeekLT || oc==OP_SeekLE );
74399     if( res>0 || (res==0 && oc==OP_SeekLT) ){
74400       res = 0;
74401       rc = sqlite3BtreePrevious(pC->pCursor, &res);
74402       if( rc!=SQLITE_OK ) goto abort_due_to_error;
74403     }else{
74404       /* res might be negative because the table is empty.  Check to
74405       ** see if this is the case.
74406       */
74407       res = sqlite3BtreeEof(pC->pCursor);
74408     }
74409   }
74410   assert( pOp->p2>0 );
74411   VdbeBranchTaken(res!=0,2);
74412   if( res ){
74413     pc = pOp->p2 - 1;
74414   }
74415   break;
74416 }
74417
74418 /* Opcode: Seek P1 P2 * * *
74419 ** Synopsis:  intkey=r[P2]
74420 **
74421 ** P1 is an open table cursor and P2 is a rowid integer.  Arrange
74422 ** for P1 to move so that it points to the rowid given by P2.
74423 **
74424 ** This is actually a deferred seek.  Nothing actually happens until
74425 ** the cursor is used to read a record.  That way, if no reads
74426 ** occur, no unnecessary I/O happens.
74427 */
74428 case OP_Seek: {    /* in2 */
74429   VdbeCursor *pC;
74430
74431   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
74432   pC = p->apCsr[pOp->p1];
74433   assert( pC!=0 );
74434   assert( pC->pCursor!=0 );
74435   assert( pC->isTable );
74436   pC->nullRow = 0;
74437   pIn2 = &aMem[pOp->p2];
74438   pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
74439   pC->deferredMoveto = 1;
74440   break;
74441 }
74442   
74443
74444 /* Opcode: Found P1 P2 P3 P4 *
74445 ** Synopsis: key=r[P3@P4]
74446 **
74447 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
74448 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
74449 ** record.
74450 **
74451 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
74452 ** is a prefix of any entry in P1 then a jump is made to P2 and
74453 ** P1 is left pointing at the matching entry.
74454 **
74455 ** This operation leaves the cursor in a state where it can be
74456 ** advanced in the forward direction.  The Next instruction will work,
74457 ** but not the Prev instruction.
74458 **
74459 ** See also: NotFound, NoConflict, NotExists. SeekGe
74460 */
74461 /* Opcode: NotFound P1 P2 P3 P4 *
74462 ** Synopsis: key=r[P3@P4]
74463 **
74464 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
74465 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
74466 ** record.
74467 ** 
74468 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
74469 ** is not the prefix of any entry in P1 then a jump is made to P2.  If P1 
74470 ** does contain an entry whose prefix matches the P3/P4 record then control
74471 ** falls through to the next instruction and P1 is left pointing at the
74472 ** matching entry.
74473 **
74474 ** This operation leaves the cursor in a state where it cannot be
74475 ** advanced in either direction.  In other words, the Next and Prev
74476 ** opcodes do not work after this operation.
74477 **
74478 ** See also: Found, NotExists, NoConflict
74479 */
74480 /* Opcode: NoConflict P1 P2 P3 P4 *
74481 ** Synopsis: key=r[P3@P4]
74482 **
74483 ** If P4==0 then register P3 holds a blob constructed by MakeRecord.  If
74484 ** P4>0 then register P3 is the first of P4 registers that form an unpacked
74485 ** record.
74486 ** 
74487 ** Cursor P1 is on an index btree.  If the record identified by P3 and P4
74488 ** contains any NULL value, jump immediately to P2.  If all terms of the
74489 ** record are not-NULL then a check is done to determine if any row in the
74490 ** P1 index btree has a matching key prefix.  If there are no matches, jump
74491 ** immediately to P2.  If there is a match, fall through and leave the P1
74492 ** cursor pointing to the matching row.
74493 **
74494 ** This opcode is similar to OP_NotFound with the exceptions that the
74495 ** branch is always taken if any part of the search key input is NULL.
74496 **
74497 ** This operation leaves the cursor in a state where it cannot be
74498 ** advanced in either direction.  In other words, the Next and Prev
74499 ** opcodes do not work after this operation.
74500 **
74501 ** See also: NotFound, Found, NotExists
74502 */
74503 case OP_NoConflict:     /* jump, in3 */
74504 case OP_NotFound:       /* jump, in3 */
74505 case OP_Found: {        /* jump, in3 */
74506   int alreadyExists;
74507   int ii;
74508   VdbeCursor *pC;
74509   int res;
74510   char *pFree;
74511   UnpackedRecord *pIdxKey;
74512   UnpackedRecord r;
74513   char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
74514
74515 #ifdef SQLITE_TEST
74516   if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
74517 #endif
74518
74519   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
74520   assert( pOp->p4type==P4_INT32 );
74521   pC = p->apCsr[pOp->p1];
74522   assert( pC!=0 );
74523 #ifdef SQLITE_DEBUG
74524   pC->seekOp = pOp->opcode;
74525 #endif
74526   pIn3 = &aMem[pOp->p3];
74527   assert( pC->pCursor!=0 );
74528   assert( pC->isTable==0 );
74529   pFree = 0;  /* Not needed.  Only used to suppress a compiler warning. */
74530   if( pOp->p4.i>0 ){
74531     r.pKeyInfo = pC->pKeyInfo;
74532     r.nField = (u16)pOp->p4.i;
74533     r.aMem = pIn3;
74534     for(ii=0; ii<r.nField; ii++){
74535       assert( memIsValid(&r.aMem[ii]) );
74536       ExpandBlob(&r.aMem[ii]);
74537 #ifdef SQLITE_DEBUG
74538       if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
74539 #endif
74540     }
74541     pIdxKey = &r;
74542   }else{
74543     pIdxKey = sqlite3VdbeAllocUnpackedRecord(
74544         pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
74545     );
74546     if( pIdxKey==0 ) goto no_mem;
74547     assert( pIn3->flags & MEM_Blob );
74548     ExpandBlob(pIn3);
74549     sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
74550   }
74551   pIdxKey->default_rc = 0;
74552   if( pOp->opcode==OP_NoConflict ){
74553     /* For the OP_NoConflict opcode, take the jump if any of the
74554     ** input fields are NULL, since any key with a NULL will not
74555     ** conflict */
74556     for(ii=0; ii<pIdxKey->nField; ii++){
74557       if( pIdxKey->aMem[ii].flags & MEM_Null ){
74558         pc = pOp->p2 - 1; VdbeBranchTaken(1,2);
74559         break;
74560       }
74561     }
74562   }
74563   rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
74564   if( pOp->p4.i==0 ){
74565     sqlite3DbFree(db, pFree);
74566   }
74567   if( rc!=SQLITE_OK ){
74568     break;
74569   }
74570   pC->seekResult = res;
74571   alreadyExists = (res==0);
74572   pC->nullRow = 1-alreadyExists;
74573   pC->deferredMoveto = 0;
74574   pC->cacheStatus = CACHE_STALE;
74575   if( pOp->opcode==OP_Found ){
74576     VdbeBranchTaken(alreadyExists!=0,2);
74577     if( alreadyExists ) pc = pOp->p2 - 1;
74578   }else{
74579     VdbeBranchTaken(alreadyExists==0,2);
74580     if( !alreadyExists ) pc = pOp->p2 - 1;
74581   }
74582   break;
74583 }
74584
74585 /* Opcode: NotExists P1 P2 P3 * *
74586 ** Synopsis: intkey=r[P3]
74587 **
74588 ** P1 is the index of a cursor open on an SQL table btree (with integer
74589 ** keys).  P3 is an integer rowid.  If P1 does not contain a record with
74590 ** rowid P3 then jump immediately to P2.  If P1 does contain a record
74591 ** with rowid P3 then leave the cursor pointing at that record and fall
74592 ** through to the next instruction.
74593 **
74594 ** The OP_NotFound opcode performs the same operation on index btrees
74595 ** (with arbitrary multi-value keys).
74596 **
74597 ** This opcode leaves the cursor in a state where it cannot be advanced
74598 ** in either direction.  In other words, the Next and Prev opcodes will
74599 ** not work following this opcode.
74600 **
74601 ** See also: Found, NotFound, NoConflict
74602 */
74603 case OP_NotExists: {        /* jump, in3 */
74604   VdbeCursor *pC;
74605   BtCursor *pCrsr;
74606   int res;
74607   u64 iKey;
74608
74609   pIn3 = &aMem[pOp->p3];
74610   assert( pIn3->flags & MEM_Int );
74611   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
74612   pC = p->apCsr[pOp->p1];
74613   assert( pC!=0 );
74614 #ifdef SQLITE_DEBUG
74615   pC->seekOp = 0;
74616 #endif
74617   assert( pC->isTable );
74618   assert( pC->pseudoTableReg==0 );
74619   pCrsr = pC->pCursor;
74620   assert( pCrsr!=0 );
74621   res = 0;
74622   iKey = pIn3->u.i;
74623   rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
74624   pC->movetoTarget = iKey;  /* Used by OP_Delete */
74625   pC->nullRow = 0;
74626   pC->cacheStatus = CACHE_STALE;
74627   pC->deferredMoveto = 0;
74628   VdbeBranchTaken(res!=0,2);
74629   if( res!=0 ){
74630     pc = pOp->p2 - 1;
74631   }
74632   pC->seekResult = res;
74633   break;
74634 }
74635
74636 /* Opcode: Sequence P1 P2 * * *
74637 ** Synopsis: r[P2]=cursor[P1].ctr++
74638 **
74639 ** Find the next available sequence number for cursor P1.
74640 ** Write the sequence number into register P2.
74641 ** The sequence number on the cursor is incremented after this
74642 ** instruction.  
74643 */
74644 case OP_Sequence: {           /* out2-prerelease */
74645   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
74646   assert( p->apCsr[pOp->p1]!=0 );
74647   pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
74648   break;
74649 }
74650
74651
74652 /* Opcode: NewRowid P1 P2 P3 * *
74653 ** Synopsis: r[P2]=rowid
74654 **
74655 ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
74656 ** The record number is not previously used as a key in the database
74657 ** table that cursor P1 points to.  The new record number is written
74658 ** written to register P2.
74659 **
74660 ** If P3>0 then P3 is a register in the root frame of this VDBE that holds 
74661 ** the largest previously generated record number. No new record numbers are
74662 ** allowed to be less than this value. When this value reaches its maximum, 
74663 ** an SQLITE_FULL error is generated. The P3 register is updated with the '
74664 ** generated record number. This P3 mechanism is used to help implement the
74665 ** AUTOINCREMENT feature.
74666 */
74667 case OP_NewRowid: {           /* out2-prerelease */
74668   i64 v;                 /* The new rowid */
74669   VdbeCursor *pC;        /* Cursor of table to get the new rowid */
74670   int res;               /* Result of an sqlite3BtreeLast() */
74671   int cnt;               /* Counter to limit the number of searches */
74672   Mem *pMem;             /* Register holding largest rowid for AUTOINCREMENT */
74673   VdbeFrame *pFrame;     /* Root frame of VDBE */
74674
74675   v = 0;
74676   res = 0;
74677   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
74678   pC = p->apCsr[pOp->p1];
74679   assert( pC!=0 );
74680   if( NEVER(pC->pCursor==0) ){
74681     /* The zero initialization above is all that is needed */
74682   }else{
74683     /* The next rowid or record number (different terms for the same
74684     ** thing) is obtained in a two-step algorithm.
74685     **
74686     ** First we attempt to find the largest existing rowid and add one
74687     ** to that.  But if the largest existing rowid is already the maximum
74688     ** positive integer, we have to fall through to the second
74689     ** probabilistic algorithm
74690     **
74691     ** The second algorithm is to select a rowid at random and see if
74692     ** it already exists in the table.  If it does not exist, we have
74693     ** succeeded.  If the random rowid does exist, we select a new one
74694     ** and try again, up to 100 times.
74695     */
74696     assert( pC->isTable );
74697
74698 #ifdef SQLITE_32BIT_ROWID
74699 #   define MAX_ROWID 0x7fffffff
74700 #else
74701     /* Some compilers complain about constants of the form 0x7fffffffffffffff.
74702     ** Others complain about 0x7ffffffffffffffffLL.  The following macro seems
74703     ** to provide the constant while making all compilers happy.
74704     */
74705 #   define MAX_ROWID  (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
74706 #endif
74707
74708     if( !pC->useRandomRowid ){
74709       rc = sqlite3BtreeLast(pC->pCursor, &res);
74710       if( rc!=SQLITE_OK ){
74711         goto abort_due_to_error;
74712       }
74713       if( res ){
74714         v = 1;   /* IMP: R-61914-48074 */
74715       }else{
74716         assert( sqlite3BtreeCursorIsValid(pC->pCursor) );
74717         rc = sqlite3BtreeKeySize(pC->pCursor, &v);
74718         assert( rc==SQLITE_OK );   /* Cannot fail following BtreeLast() */
74719         if( v>=MAX_ROWID ){
74720           pC->useRandomRowid = 1;
74721         }else{
74722           v++;   /* IMP: R-29538-34987 */
74723         }
74724       }
74725     }
74726
74727 #ifndef SQLITE_OMIT_AUTOINCREMENT
74728     if( pOp->p3 ){
74729       /* Assert that P3 is a valid memory cell. */
74730       assert( pOp->p3>0 );
74731       if( p->pFrame ){
74732         for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
74733         /* Assert that P3 is a valid memory cell. */
74734         assert( pOp->p3<=pFrame->nMem );
74735         pMem = &pFrame->aMem[pOp->p3];
74736       }else{
74737         /* Assert that P3 is a valid memory cell. */
74738         assert( pOp->p3<=(p->nMem-p->nCursor) );
74739         pMem = &aMem[pOp->p3];
74740         memAboutToChange(p, pMem);
74741       }
74742       assert( memIsValid(pMem) );
74743
74744       REGISTER_TRACE(pOp->p3, pMem);
74745       sqlite3VdbeMemIntegerify(pMem);
74746       assert( (pMem->flags & MEM_Int)!=0 );  /* mem(P3) holds an integer */
74747       if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
74748         rc = SQLITE_FULL;   /* IMP: R-12275-61338 */
74749         goto abort_due_to_error;
74750       }
74751       if( v<pMem->u.i+1 ){
74752         v = pMem->u.i + 1;
74753       }
74754       pMem->u.i = v;
74755     }
74756 #endif
74757     if( pC->useRandomRowid ){
74758       /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
74759       ** largest possible integer (9223372036854775807) then the database
74760       ** engine starts picking positive candidate ROWIDs at random until
74761       ** it finds one that is not previously used. */
74762       assert( pOp->p3==0 );  /* We cannot be in random rowid mode if this is
74763                              ** an AUTOINCREMENT table. */
74764       cnt = 0;
74765       do{
74766         sqlite3_randomness(sizeof(v), &v);
74767         v &= (MAX_ROWID>>1); v++;  /* Ensure that v is greater than zero */
74768       }while(  ((rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)v,
74769                                                  0, &res))==SQLITE_OK)
74770             && (res==0)
74771             && (++cnt<100));
74772       if( rc==SQLITE_OK && res==0 ){
74773         rc = SQLITE_FULL;   /* IMP: R-38219-53002 */
74774         goto abort_due_to_error;
74775       }
74776       assert( v>0 );  /* EV: R-40812-03570 */
74777     }
74778     pC->deferredMoveto = 0;
74779     pC->cacheStatus = CACHE_STALE;
74780   }
74781   pOut->u.i = v;
74782   break;
74783 }
74784
74785 /* Opcode: Insert P1 P2 P3 P4 P5
74786 ** Synopsis: intkey=r[P3] data=r[P2]
74787 **
74788 ** Write an entry into the table of cursor P1.  A new entry is
74789 ** created if it doesn't already exist or the data for an existing
74790 ** entry is overwritten.  The data is the value MEM_Blob stored in register
74791 ** number P2. The key is stored in register P3. The key must
74792 ** be a MEM_Int.
74793 **
74794 ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
74795 ** incremented (otherwise not).  If the OPFLAG_LASTROWID flag of P5 is set,
74796 ** then rowid is stored for subsequent return by the
74797 ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
74798 **
74799 ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
74800 ** the last seek operation (OP_NotExists) was a success, then this
74801 ** operation will not attempt to find the appropriate row before doing
74802 ** the insert but will instead overwrite the row that the cursor is
74803 ** currently pointing to.  Presumably, the prior OP_NotExists opcode
74804 ** has already positioned the cursor correctly.  This is an optimization
74805 ** that boosts performance by avoiding redundant seeks.
74806 **
74807 ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
74808 ** UPDATE operation.  Otherwise (if the flag is clear) then this opcode
74809 ** is part of an INSERT operation.  The difference is only important to
74810 ** the update hook.
74811 **
74812 ** Parameter P4 may point to a string containing the table-name, or
74813 ** may be NULL. If it is not NULL, then the update-hook 
74814 ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
74815 **
74816 ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
74817 ** allocated, then ownership of P2 is transferred to the pseudo-cursor
74818 ** and register P2 becomes ephemeral.  If the cursor is changed, the
74819 ** value of register P2 will then change.  Make sure this does not
74820 ** cause any problems.)
74821 **
74822 ** This instruction only works on tables.  The equivalent instruction
74823 ** for indices is OP_IdxInsert.
74824 */
74825 /* Opcode: InsertInt P1 P2 P3 P4 P5
74826 ** Synopsis:  intkey=P3 data=r[P2]
74827 **
74828 ** This works exactly like OP_Insert except that the key is the
74829 ** integer value P3, not the value of the integer stored in register P3.
74830 */
74831 case OP_Insert: 
74832 case OP_InsertInt: {
74833   Mem *pData;       /* MEM cell holding data for the record to be inserted */
74834   Mem *pKey;        /* MEM cell holding key  for the record */
74835   i64 iKey;         /* The integer ROWID or key for the record to be inserted */
74836   VdbeCursor *pC;   /* Cursor to table into which insert is written */
74837   int nZero;        /* Number of zero-bytes to append */
74838   int seekResult;   /* Result of prior seek or 0 if no USESEEKRESULT flag */
74839   const char *zDb;  /* database name - used by the update hook */
74840   const char *zTbl; /* Table name - used by the opdate hook */
74841   int op;           /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
74842
74843   pData = &aMem[pOp->p2];
74844   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
74845   assert( memIsValid(pData) );
74846   pC = p->apCsr[pOp->p1];
74847   assert( pC!=0 );
74848   assert( pC->pCursor!=0 );
74849   assert( pC->pseudoTableReg==0 );
74850   assert( pC->isTable );
74851   REGISTER_TRACE(pOp->p2, pData);
74852
74853   if( pOp->opcode==OP_Insert ){
74854     pKey = &aMem[pOp->p3];
74855     assert( pKey->flags & MEM_Int );
74856     assert( memIsValid(pKey) );
74857     REGISTER_TRACE(pOp->p3, pKey);
74858     iKey = pKey->u.i;
74859   }else{
74860     assert( pOp->opcode==OP_InsertInt );
74861     iKey = pOp->p3;
74862   }
74863
74864   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
74865   if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
74866   if( pData->flags & MEM_Null ){
74867     pData->z = 0;
74868     pData->n = 0;
74869   }else{
74870     assert( pData->flags & (MEM_Blob|MEM_Str) );
74871   }
74872   seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
74873   if( pData->flags & MEM_Zero ){
74874     nZero = pData->u.nZero;
74875   }else{
74876     nZero = 0;
74877   }
74878   rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
74879                           pData->z, pData->n, nZero,
74880                           (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
74881   );
74882   pC->deferredMoveto = 0;
74883   pC->cacheStatus = CACHE_STALE;
74884
74885   /* Invoke the update-hook if required. */
74886   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
74887     zDb = db->aDb[pC->iDb].zName;
74888     zTbl = pOp->p4.z;
74889     op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
74890     assert( pC->isTable );
74891     db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
74892     assert( pC->iDb>=0 );
74893   }
74894   break;
74895 }
74896
74897 /* Opcode: Delete P1 P2 * P4 *
74898 **
74899 ** Delete the record at which the P1 cursor is currently pointing.
74900 **
74901 ** The cursor will be left pointing at either the next or the previous
74902 ** record in the table. If it is left pointing at the next record, then
74903 ** the next Next instruction will be a no-op.  Hence it is OK to delete
74904 ** a record from within a Next loop.
74905 **
74906 ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
74907 ** incremented (otherwise not).
74908 **
74909 ** P1 must not be pseudo-table.  It has to be a real table with
74910 ** multiple rows.
74911 **
74912 ** If P4 is not NULL, then it is the name of the table that P1 is
74913 ** pointing to.  The update hook will be invoked, if it exists.
74914 ** If P4 is not NULL then the P1 cursor must have been positioned
74915 ** using OP_NotFound prior to invoking this opcode.
74916 */
74917 case OP_Delete: {
74918   VdbeCursor *pC;
74919
74920   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
74921   pC = p->apCsr[pOp->p1];
74922   assert( pC!=0 );
74923   assert( pC->pCursor!=0 );  /* Only valid for real tables, no pseudotables */
74924   assert( pC->deferredMoveto==0 );
74925
74926 #ifdef SQLITE_DEBUG
74927   /* The seek operation that positioned the cursor prior to OP_Delete will
74928   ** have also set the pC->movetoTarget field to the rowid of the row that
74929   ** is being deleted */
74930   if( pOp->p4.z && pC->isTable ){
74931     i64 iKey = 0;
74932     sqlite3BtreeKeySize(pC->pCursor, &iKey);
74933     assert( pC->movetoTarget==iKey ); 
74934   }
74935 #endif
74936  
74937   rc = sqlite3BtreeDelete(pC->pCursor);
74938   pC->cacheStatus = CACHE_STALE;
74939
74940   /* Invoke the update-hook if required. */
74941   if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z && pC->isTable ){
74942     db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE,
74943                         db->aDb[pC->iDb].zName, pOp->p4.z, pC->movetoTarget);
74944     assert( pC->iDb>=0 );
74945   }
74946   if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
74947   break;
74948 }
74949 /* Opcode: ResetCount * * * * *
74950 **
74951 ** The value of the change counter is copied to the database handle
74952 ** change counter (returned by subsequent calls to sqlite3_changes()).
74953 ** Then the VMs internal change counter resets to 0.
74954 ** This is used by trigger programs.
74955 */
74956 case OP_ResetCount: {
74957   sqlite3VdbeSetChanges(db, p->nChange);
74958   p->nChange = 0;
74959   break;
74960 }
74961
74962 /* Opcode: SorterCompare P1 P2 P3 P4
74963 ** Synopsis:  if key(P1)!=trim(r[P3],P4) goto P2
74964 **
74965 ** P1 is a sorter cursor. This instruction compares a prefix of the
74966 ** record blob in register P3 against a prefix of the entry that 
74967 ** the sorter cursor currently points to.  Only the first P4 fields
74968 ** of r[P3] and the sorter record are compared.
74969 **
74970 ** If either P3 or the sorter contains a NULL in one of their significant
74971 ** fields (not counting the P4 fields at the end which are ignored) then
74972 ** the comparison is assumed to be equal.
74973 **
74974 ** Fall through to next instruction if the two records compare equal to
74975 ** each other.  Jump to P2 if they are different.
74976 */
74977 case OP_SorterCompare: {
74978   VdbeCursor *pC;
74979   int res;
74980   int nKeyCol;
74981
74982   pC = p->apCsr[pOp->p1];
74983   assert( isSorter(pC) );
74984   assert( pOp->p4type==P4_INT32 );
74985   pIn3 = &aMem[pOp->p3];
74986   nKeyCol = pOp->p4.i;
74987   res = 0;
74988   rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
74989   VdbeBranchTaken(res!=0,2);
74990   if( res ){
74991     pc = pOp->p2-1;
74992   }
74993   break;
74994 };
74995
74996 /* Opcode: SorterData P1 P2 P3 * *
74997 ** Synopsis: r[P2]=data
74998 **
74999 ** Write into register P2 the current sorter data for sorter cursor P1.
75000 ** Then clear the column header cache on cursor P3.
75001 **
75002 ** This opcode is normally use to move a record out of the sorter and into
75003 ** a register that is the source for a pseudo-table cursor created using
75004 ** OpenPseudo.  That pseudo-table cursor is the one that is identified by
75005 ** parameter P3.  Clearing the P3 column cache as part of this opcode saves
75006 ** us from having to issue a separate NullRow instruction to clear that cache.
75007 */
75008 case OP_SorterData: {
75009   VdbeCursor *pC;
75010
75011   pOut = &aMem[pOp->p2];
75012   pC = p->apCsr[pOp->p1];
75013   assert( isSorter(pC) );
75014   rc = sqlite3VdbeSorterRowkey(pC, pOut);
75015   assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
75016   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75017   p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
75018   break;
75019 }
75020
75021 /* Opcode: RowData P1 P2 * * *
75022 ** Synopsis: r[P2]=data
75023 **
75024 ** Write into register P2 the complete row data for cursor P1.
75025 ** There is no interpretation of the data.  
75026 ** It is just copied onto the P2 register exactly as 
75027 ** it is found in the database file.
75028 **
75029 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
75030 ** of a real table, not a pseudo-table.
75031 */
75032 /* Opcode: RowKey P1 P2 * * *
75033 ** Synopsis: r[P2]=key
75034 **
75035 ** Write into register P2 the complete row key for cursor P1.
75036 ** There is no interpretation of the data.  
75037 ** The key is copied onto the P2 register exactly as 
75038 ** it is found in the database file.
75039 **
75040 ** If the P1 cursor must be pointing to a valid row (not a NULL row)
75041 ** of a real table, not a pseudo-table.
75042 */
75043 case OP_RowKey:
75044 case OP_RowData: {
75045   VdbeCursor *pC;
75046   BtCursor *pCrsr;
75047   u32 n;
75048   i64 n64;
75049
75050   pOut = &aMem[pOp->p2];
75051   memAboutToChange(p, pOut);
75052
75053   /* Note that RowKey and RowData are really exactly the same instruction */
75054   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75055   pC = p->apCsr[pOp->p1];
75056   assert( isSorter(pC)==0 );
75057   assert( pC->isTable || pOp->opcode!=OP_RowData );
75058   assert( pC->isTable==0 || pOp->opcode==OP_RowData );
75059   assert( pC!=0 );
75060   assert( pC->nullRow==0 );
75061   assert( pC->pseudoTableReg==0 );
75062   assert( pC->pCursor!=0 );
75063   pCrsr = pC->pCursor;
75064
75065   /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
75066   ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
75067   ** the cursor.  If this where not the case, on of the following assert()s
75068   ** would fail.  Should this ever change (because of changes in the code
75069   ** generator) then the fix would be to insert a call to
75070   ** sqlite3VdbeCursorMoveto().
75071   */
75072   assert( pC->deferredMoveto==0 );
75073   assert( sqlite3BtreeCursorIsValid(pCrsr) );
75074 #if 0  /* Not required due to the previous to assert() statements */
75075   rc = sqlite3VdbeCursorMoveto(pC);
75076   if( rc!=SQLITE_OK ) goto abort_due_to_error;
75077 #endif
75078
75079   if( pC->isTable==0 ){
75080     assert( !pC->isTable );
75081     VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &n64);
75082     assert( rc==SQLITE_OK );    /* True because of CursorMoveto() call above */
75083     if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
75084       goto too_big;
75085     }
75086     n = (u32)n64;
75087   }else{
75088     VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &n);
75089     assert( rc==SQLITE_OK );    /* DataSize() cannot fail */
75090     if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
75091       goto too_big;
75092     }
75093   }
75094   testcase( n==0 );
75095   if( sqlite3VdbeMemClearAndResize(pOut, MAX(n,32)) ){
75096     goto no_mem;
75097   }
75098   pOut->n = n;
75099   MemSetTypeFlag(pOut, MEM_Blob);
75100   if( pC->isTable==0 ){
75101     rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
75102   }else{
75103     rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
75104   }
75105   pOut->enc = SQLITE_UTF8;  /* In case the blob is ever cast to text */
75106   UPDATE_MAX_BLOBSIZE(pOut);
75107   REGISTER_TRACE(pOp->p2, pOut);
75108   break;
75109 }
75110
75111 /* Opcode: Rowid P1 P2 * * *
75112 ** Synopsis: r[P2]=rowid
75113 **
75114 ** Store in register P2 an integer which is the key of the table entry that
75115 ** P1 is currently point to.
75116 **
75117 ** P1 can be either an ordinary table or a virtual table.  There used to
75118 ** be a separate OP_VRowid opcode for use with virtual tables, but this
75119 ** one opcode now works for both table types.
75120 */
75121 case OP_Rowid: {                 /* out2-prerelease */
75122   VdbeCursor *pC;
75123   i64 v;
75124   sqlite3_vtab *pVtab;
75125   const sqlite3_module *pModule;
75126
75127   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75128   pC = p->apCsr[pOp->p1];
75129   assert( pC!=0 );
75130   assert( pC->pseudoTableReg==0 || pC->nullRow );
75131   if( pC->nullRow ){
75132     pOut->flags = MEM_Null;
75133     break;
75134   }else if( pC->deferredMoveto ){
75135     v = pC->movetoTarget;
75136 #ifndef SQLITE_OMIT_VIRTUALTABLE
75137   }else if( pC->pVtabCursor ){
75138     pVtab = pC->pVtabCursor->pVtab;
75139     pModule = pVtab->pModule;
75140     assert( pModule->xRowid );
75141     rc = pModule->xRowid(pC->pVtabCursor, &v);
75142     sqlite3VtabImportErrmsg(p, pVtab);
75143 #endif /* SQLITE_OMIT_VIRTUALTABLE */
75144   }else{
75145     assert( pC->pCursor!=0 );
75146     rc = sqlite3VdbeCursorRestore(pC);
75147     if( rc ) goto abort_due_to_error;
75148     if( pC->nullRow ){
75149       pOut->flags = MEM_Null;
75150       break;
75151     }
75152     rc = sqlite3BtreeKeySize(pC->pCursor, &v);
75153     assert( rc==SQLITE_OK );  /* Always so because of CursorRestore() above */
75154   }
75155   pOut->u.i = v;
75156   break;
75157 }
75158
75159 /* Opcode: NullRow P1 * * * *
75160 **
75161 ** Move the cursor P1 to a null row.  Any OP_Column operations
75162 ** that occur while the cursor is on the null row will always
75163 ** write a NULL.
75164 */
75165 case OP_NullRow: {
75166   VdbeCursor *pC;
75167
75168   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75169   pC = p->apCsr[pOp->p1];
75170   assert( pC!=0 );
75171   pC->nullRow = 1;
75172   pC->cacheStatus = CACHE_STALE;
75173   if( pC->pCursor ){
75174     sqlite3BtreeClearCursor(pC->pCursor);
75175   }
75176   break;
75177 }
75178
75179 /* Opcode: Last P1 P2 * * *
75180 **
75181 ** The next use of the Rowid or Column or Prev instruction for P1 
75182 ** will refer to the last entry in the database table or index.
75183 ** If the table or index is empty and P2>0, then jump immediately to P2.
75184 ** If P2 is 0 or if the table or index is not empty, fall through
75185 ** to the following instruction.
75186 **
75187 ** This opcode leaves the cursor configured to move in reverse order,
75188 ** from the end toward the beginning.  In other words, the cursor is
75189 ** configured to use Prev, not Next.
75190 */
75191 case OP_Last: {        /* jump */
75192   VdbeCursor *pC;
75193   BtCursor *pCrsr;
75194   int res;
75195
75196   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75197   pC = p->apCsr[pOp->p1];
75198   assert( pC!=0 );
75199   pCrsr = pC->pCursor;
75200   res = 0;
75201   assert( pCrsr!=0 );
75202   rc = sqlite3BtreeLast(pCrsr, &res);
75203   pC->nullRow = (u8)res;
75204   pC->deferredMoveto = 0;
75205   pC->cacheStatus = CACHE_STALE;
75206 #ifdef SQLITE_DEBUG
75207   pC->seekOp = OP_Last;
75208 #endif
75209   if( pOp->p2>0 ){
75210     VdbeBranchTaken(res!=0,2);
75211     if( res ) pc = pOp->p2 - 1;
75212   }
75213   break;
75214 }
75215
75216
75217 /* Opcode: Sort P1 P2 * * *
75218 **
75219 ** This opcode does exactly the same thing as OP_Rewind except that
75220 ** it increments an undocumented global variable used for testing.
75221 **
75222 ** Sorting is accomplished by writing records into a sorting index,
75223 ** then rewinding that index and playing it back from beginning to
75224 ** end.  We use the OP_Sort opcode instead of OP_Rewind to do the
75225 ** rewinding so that the global variable will be incremented and
75226 ** regression tests can determine whether or not the optimizer is
75227 ** correctly optimizing out sorts.
75228 */
75229 case OP_SorterSort:    /* jump */
75230 case OP_Sort: {        /* jump */
75231 #ifdef SQLITE_TEST
75232   sqlite3_sort_count++;
75233   sqlite3_search_count--;
75234 #endif
75235   p->aCounter[SQLITE_STMTSTATUS_SORT]++;
75236   /* Fall through into OP_Rewind */
75237 }
75238 /* Opcode: Rewind P1 P2 * * *
75239 **
75240 ** The next use of the Rowid or Column or Next instruction for P1 
75241 ** will refer to the first entry in the database table or index.
75242 ** If the table or index is empty, jump immediately to P2.
75243 ** If the table or index is not empty, fall through to the following 
75244 ** instruction.
75245 **
75246 ** This opcode leaves the cursor configured to move in forward order,
75247 ** from the beginning toward the end.  In other words, the cursor is
75248 ** configured to use Next, not Prev.
75249 */
75250 case OP_Rewind: {        /* jump */
75251   VdbeCursor *pC;
75252   BtCursor *pCrsr;
75253   int res;
75254
75255   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75256   pC = p->apCsr[pOp->p1];
75257   assert( pC!=0 );
75258   assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
75259   res = 1;
75260 #ifdef SQLITE_DEBUG
75261   pC->seekOp = OP_Rewind;
75262 #endif
75263   if( isSorter(pC) ){
75264     rc = sqlite3VdbeSorterRewind(pC, &res);
75265   }else{
75266     pCrsr = pC->pCursor;
75267     assert( pCrsr );
75268     rc = sqlite3BtreeFirst(pCrsr, &res);
75269     pC->deferredMoveto = 0;
75270     pC->cacheStatus = CACHE_STALE;
75271   }
75272   pC->nullRow = (u8)res;
75273   assert( pOp->p2>0 && pOp->p2<p->nOp );
75274   VdbeBranchTaken(res!=0,2);
75275   if( res ){
75276     pc = pOp->p2 - 1;
75277   }
75278   break;
75279 }
75280
75281 /* Opcode: Next P1 P2 P3 P4 P5
75282 **
75283 ** Advance cursor P1 so that it points to the next key/data pair in its
75284 ** table or index.  If there are no more key/value pairs then fall through
75285 ** to the following instruction.  But if the cursor advance was successful,
75286 ** jump immediately to P2.
75287 **
75288 ** The Next opcode is only valid following an SeekGT, SeekGE, or
75289 ** OP_Rewind opcode used to position the cursor.  Next is not allowed
75290 ** to follow SeekLT, SeekLE, or OP_Last.
75291 **
75292 ** The P1 cursor must be for a real table, not a pseudo-table.  P1 must have
75293 ** been opened prior to this opcode or the program will segfault.
75294 **
75295 ** The P3 value is a hint to the btree implementation. If P3==1, that
75296 ** means P1 is an SQL index and that this instruction could have been
75297 ** omitted if that index had been unique.  P3 is usually 0.  P3 is
75298 ** always either 0 or 1.
75299 **
75300 ** P4 is always of type P4_ADVANCE. The function pointer points to
75301 ** sqlite3BtreeNext().
75302 **
75303 ** If P5 is positive and the jump is taken, then event counter
75304 ** number P5-1 in the prepared statement is incremented.
75305 **
75306 ** See also: Prev, NextIfOpen
75307 */
75308 /* Opcode: NextIfOpen P1 P2 P3 P4 P5
75309 **
75310 ** This opcode works just like Next except that if cursor P1 is not
75311 ** open it behaves a no-op.
75312 */
75313 /* Opcode: Prev P1 P2 P3 P4 P5
75314 **
75315 ** Back up cursor P1 so that it points to the previous key/data pair in its
75316 ** table or index.  If there is no previous key/value pairs then fall through
75317 ** to the following instruction.  But if the cursor backup was successful,
75318 ** jump immediately to P2.
75319 **
75320 **
75321 ** The Prev opcode is only valid following an SeekLT, SeekLE, or
75322 ** OP_Last opcode used to position the cursor.  Prev is not allowed
75323 ** to follow SeekGT, SeekGE, or OP_Rewind.
75324 **
75325 ** The P1 cursor must be for a real table, not a pseudo-table.  If P1 is
75326 ** not open then the behavior is undefined.
75327 **
75328 ** The P3 value is a hint to the btree implementation. If P3==1, that
75329 ** means P1 is an SQL index and that this instruction could have been
75330 ** omitted if that index had been unique.  P3 is usually 0.  P3 is
75331 ** always either 0 or 1.
75332 **
75333 ** P4 is always of type P4_ADVANCE. The function pointer points to
75334 ** sqlite3BtreePrevious().
75335 **
75336 ** If P5 is positive and the jump is taken, then event counter
75337 ** number P5-1 in the prepared statement is incremented.
75338 */
75339 /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
75340 **
75341 ** This opcode works just like Prev except that if cursor P1 is not
75342 ** open it behaves a no-op.
75343 */
75344 case OP_SorterNext: {  /* jump */
75345   VdbeCursor *pC;
75346   int res;
75347
75348   pC = p->apCsr[pOp->p1];
75349   assert( isSorter(pC) );
75350   res = 0;
75351   rc = sqlite3VdbeSorterNext(db, pC, &res);
75352   goto next_tail;
75353 case OP_PrevIfOpen:    /* jump */
75354 case OP_NextIfOpen:    /* jump */
75355   if( p->apCsr[pOp->p1]==0 ) break;
75356   /* Fall through */
75357 case OP_Prev:          /* jump */
75358 case OP_Next:          /* jump */
75359   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75360   assert( pOp->p5<ArraySize(p->aCounter) );
75361   pC = p->apCsr[pOp->p1];
75362   res = pOp->p3;
75363   assert( pC!=0 );
75364   assert( pC->deferredMoveto==0 );
75365   assert( pC->pCursor );
75366   assert( res==0 || (res==1 && pC->isTable==0) );
75367   testcase( res==1 );
75368   assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
75369   assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
75370   assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
75371   assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
75372
75373   /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
75374   ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
75375   assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
75376        || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
75377        || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
75378   assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
75379        || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
75380        || pC->seekOp==OP_Last );
75381
75382   rc = pOp->p4.xAdvance(pC->pCursor, &res);
75383 next_tail:
75384   pC->cacheStatus = CACHE_STALE;
75385   VdbeBranchTaken(res==0,2);
75386   if( res==0 ){
75387     pC->nullRow = 0;
75388     pc = pOp->p2 - 1;
75389     p->aCounter[pOp->p5]++;
75390 #ifdef SQLITE_TEST
75391     sqlite3_search_count++;
75392 #endif
75393   }else{
75394     pC->nullRow = 1;
75395   }
75396   goto check_for_interrupt;
75397 }
75398
75399 /* Opcode: IdxInsert P1 P2 P3 * P5
75400 ** Synopsis: key=r[P2]
75401 **
75402 ** Register P2 holds an SQL index key made using the
75403 ** MakeRecord instructions.  This opcode writes that key
75404 ** into the index P1.  Data for the entry is nil.
75405 **
75406 ** P3 is a flag that provides a hint to the b-tree layer that this
75407 ** insert is likely to be an append.
75408 **
75409 ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
75410 ** incremented by this instruction.  If the OPFLAG_NCHANGE bit is clear,
75411 ** then the change counter is unchanged.
75412 **
75413 ** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
75414 ** just done a seek to the spot where the new entry is to be inserted.
75415 ** This flag avoids doing an extra seek.
75416 **
75417 ** This instruction only works for indices.  The equivalent instruction
75418 ** for tables is OP_Insert.
75419 */
75420 case OP_SorterInsert:       /* in2 */
75421 case OP_IdxInsert: {        /* in2 */
75422   VdbeCursor *pC;
75423   BtCursor *pCrsr;
75424   int nKey;
75425   const char *zKey;
75426
75427   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75428   pC = p->apCsr[pOp->p1];
75429   assert( pC!=0 );
75430   assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
75431   pIn2 = &aMem[pOp->p2];
75432   assert( pIn2->flags & MEM_Blob );
75433   pCrsr = pC->pCursor;
75434   if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
75435   assert( pCrsr!=0 );
75436   assert( pC->isTable==0 );
75437   rc = ExpandBlob(pIn2);
75438   if( rc==SQLITE_OK ){
75439     if( isSorter(pC) ){
75440       rc = sqlite3VdbeSorterWrite(pC, pIn2);
75441     }else{
75442       nKey = pIn2->n;
75443       zKey = pIn2->z;
75444       rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3, 
75445           ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
75446           );
75447       assert( pC->deferredMoveto==0 );
75448       pC->cacheStatus = CACHE_STALE;
75449     }
75450   }
75451   break;
75452 }
75453
75454 /* Opcode: IdxDelete P1 P2 P3 * *
75455 ** Synopsis: key=r[P2@P3]
75456 **
75457 ** The content of P3 registers starting at register P2 form
75458 ** an unpacked index key. This opcode removes that entry from the 
75459 ** index opened by cursor P1.
75460 */
75461 case OP_IdxDelete: {
75462   VdbeCursor *pC;
75463   BtCursor *pCrsr;
75464   int res;
75465   UnpackedRecord r;
75466
75467   assert( pOp->p3>0 );
75468   assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
75469   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75470   pC = p->apCsr[pOp->p1];
75471   assert( pC!=0 );
75472   pCrsr = pC->pCursor;
75473   assert( pCrsr!=0 );
75474   assert( pOp->p5==0 );
75475   r.pKeyInfo = pC->pKeyInfo;
75476   r.nField = (u16)pOp->p3;
75477   r.default_rc = 0;
75478   r.aMem = &aMem[pOp->p2];
75479 #ifdef SQLITE_DEBUG
75480   { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
75481 #endif
75482   rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
75483   if( rc==SQLITE_OK && res==0 ){
75484     rc = sqlite3BtreeDelete(pCrsr);
75485   }
75486   assert( pC->deferredMoveto==0 );
75487   pC->cacheStatus = CACHE_STALE;
75488   break;
75489 }
75490
75491 /* Opcode: IdxRowid P1 P2 * * *
75492 ** Synopsis: r[P2]=rowid
75493 **
75494 ** Write into register P2 an integer which is the last entry in the record at
75495 ** the end of the index key pointed to by cursor P1.  This integer should be
75496 ** the rowid of the table entry to which this index entry points.
75497 **
75498 ** See also: Rowid, MakeRecord.
75499 */
75500 case OP_IdxRowid: {              /* out2-prerelease */
75501   BtCursor *pCrsr;
75502   VdbeCursor *pC;
75503   i64 rowid;
75504
75505   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75506   pC = p->apCsr[pOp->p1];
75507   assert( pC!=0 );
75508   pCrsr = pC->pCursor;
75509   assert( pCrsr!=0 );
75510   pOut->flags = MEM_Null;
75511   assert( pC->isTable==0 );
75512   assert( pC->deferredMoveto==0 );
75513
75514   /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
75515   ** out from under the cursor.  That will never happend for an IdxRowid
75516   ** opcode, hence the NEVER() arround the check of the return value.
75517   */
75518   rc = sqlite3VdbeCursorRestore(pC);
75519   if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
75520
75521   if( !pC->nullRow ){
75522     rowid = 0;  /* Not needed.  Only used to silence a warning. */
75523     rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid);
75524     if( rc!=SQLITE_OK ){
75525       goto abort_due_to_error;
75526     }
75527     pOut->u.i = rowid;
75528     pOut->flags = MEM_Int;
75529   }
75530   break;
75531 }
75532
75533 /* Opcode: IdxGE P1 P2 P3 P4 P5
75534 ** Synopsis: key=r[P3@P4]
75535 **
75536 ** The P4 register values beginning with P3 form an unpacked index 
75537 ** key that omits the PRIMARY KEY.  Compare this key value against the index 
75538 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID 
75539 ** fields at the end.
75540 **
75541 ** If the P1 index entry is greater than or equal to the key value
75542 ** then jump to P2.  Otherwise fall through to the next instruction.
75543 */
75544 /* Opcode: IdxGT P1 P2 P3 P4 P5
75545 ** Synopsis: key=r[P3@P4]
75546 **
75547 ** The P4 register values beginning with P3 form an unpacked index 
75548 ** key that omits the PRIMARY KEY.  Compare this key value against the index 
75549 ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID 
75550 ** fields at the end.
75551 **
75552 ** If the P1 index entry is greater than the key value
75553 ** then jump to P2.  Otherwise fall through to the next instruction.
75554 */
75555 /* Opcode: IdxLT P1 P2 P3 P4 P5
75556 ** Synopsis: key=r[P3@P4]
75557 **
75558 ** The P4 register values beginning with P3 form an unpacked index 
75559 ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
75560 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
75561 ** ROWID on the P1 index.
75562 **
75563 ** If the P1 index entry is less than the key value then jump to P2.
75564 ** Otherwise fall through to the next instruction.
75565 */
75566 /* Opcode: IdxLE P1 P2 P3 P4 P5
75567 ** Synopsis: key=r[P3@P4]
75568 **
75569 ** The P4 register values beginning with P3 form an unpacked index 
75570 ** key that omits the PRIMARY KEY or ROWID.  Compare this key value against
75571 ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
75572 ** ROWID on the P1 index.
75573 **
75574 ** If the P1 index entry is less than or equal to the key value then jump
75575 ** to P2. Otherwise fall through to the next instruction.
75576 */
75577 case OP_IdxLE:          /* jump */
75578 case OP_IdxGT:          /* jump */
75579 case OP_IdxLT:          /* jump */
75580 case OP_IdxGE:  {       /* jump */
75581   VdbeCursor *pC;
75582   int res;
75583   UnpackedRecord r;
75584
75585   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75586   pC = p->apCsr[pOp->p1];
75587   assert( pC!=0 );
75588   assert( pC->isOrdered );
75589   assert( pC->pCursor!=0);
75590   assert( pC->deferredMoveto==0 );
75591   assert( pOp->p5==0 || pOp->p5==1 );
75592   assert( pOp->p4type==P4_INT32 );
75593   r.pKeyInfo = pC->pKeyInfo;
75594   r.nField = (u16)pOp->p4.i;
75595   if( pOp->opcode<OP_IdxLT ){
75596     assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
75597     r.default_rc = -1;
75598   }else{
75599     assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
75600     r.default_rc = 0;
75601   }
75602   r.aMem = &aMem[pOp->p3];
75603 #ifdef SQLITE_DEBUG
75604   { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
75605 #endif
75606   res = 0;  /* Not needed.  Only used to silence a warning. */
75607   rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
75608   assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
75609   if( (pOp->opcode&1)==(OP_IdxLT&1) ){
75610     assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
75611     res = -res;
75612   }else{
75613     assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
75614     res++;
75615   }
75616   VdbeBranchTaken(res>0,2);
75617   if( res>0 ){
75618     pc = pOp->p2 - 1 ;
75619   }
75620   break;
75621 }
75622
75623 /* Opcode: Destroy P1 P2 P3 * *
75624 **
75625 ** Delete an entire database table or index whose root page in the database
75626 ** file is given by P1.
75627 **
75628 ** The table being destroyed is in the main database file if P3==0.  If
75629 ** P3==1 then the table to be clear is in the auxiliary database file
75630 ** that is used to store tables create using CREATE TEMPORARY TABLE.
75631 **
75632 ** If AUTOVACUUM is enabled then it is possible that another root page
75633 ** might be moved into the newly deleted root page in order to keep all
75634 ** root pages contiguous at the beginning of the database.  The former
75635 ** value of the root page that moved - its value before the move occurred -
75636 ** is stored in register P2.  If no page 
75637 ** movement was required (because the table being dropped was already 
75638 ** the last one in the database) then a zero is stored in register P2.
75639 ** If AUTOVACUUM is disabled then a zero is stored in register P2.
75640 **
75641 ** See also: Clear
75642 */
75643 case OP_Destroy: {     /* out2-prerelease */
75644   int iMoved;
75645   int iDb;
75646
75647   assert( p->readOnly==0 );
75648   pOut->flags = MEM_Null;
75649   if( db->nVdbeRead > db->nVDestroy+1 ){
75650     rc = SQLITE_LOCKED;
75651     p->errorAction = OE_Abort;
75652   }else{
75653     iDb = pOp->p3;
75654     assert( DbMaskTest(p->btreeMask, iDb) );
75655     iMoved = 0;  /* Not needed.  Only to silence a warning. */
75656     rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
75657     pOut->flags = MEM_Int;
75658     pOut->u.i = iMoved;
75659 #ifndef SQLITE_OMIT_AUTOVACUUM
75660     if( rc==SQLITE_OK && iMoved!=0 ){
75661       sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
75662       /* All OP_Destroy operations occur on the same btree */
75663       assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
75664       resetSchemaOnFault = iDb+1;
75665     }
75666 #endif
75667   }
75668   break;
75669 }
75670
75671 /* Opcode: Clear P1 P2 P3
75672 **
75673 ** Delete all contents of the database table or index whose root page
75674 ** in the database file is given by P1.  But, unlike Destroy, do not
75675 ** remove the table or index from the database file.
75676 **
75677 ** The table being clear is in the main database file if P2==0.  If
75678 ** P2==1 then the table to be clear is in the auxiliary database file
75679 ** that is used to store tables create using CREATE TEMPORARY TABLE.
75680 **
75681 ** If the P3 value is non-zero, then the table referred to must be an
75682 ** intkey table (an SQL table, not an index). In this case the row change 
75683 ** count is incremented by the number of rows in the table being cleared. 
75684 ** If P3 is greater than zero, then the value stored in register P3 is
75685 ** also incremented by the number of rows in the table being cleared.
75686 **
75687 ** See also: Destroy
75688 */
75689 case OP_Clear: {
75690   int nChange;
75691  
75692   nChange = 0;
75693   assert( p->readOnly==0 );
75694   assert( DbMaskTest(p->btreeMask, pOp->p2) );
75695   rc = sqlite3BtreeClearTable(
75696       db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
75697   );
75698   if( pOp->p3 ){
75699     p->nChange += nChange;
75700     if( pOp->p3>0 ){
75701       assert( memIsValid(&aMem[pOp->p3]) );
75702       memAboutToChange(p, &aMem[pOp->p3]);
75703       aMem[pOp->p3].u.i += nChange;
75704     }
75705   }
75706   break;
75707 }
75708
75709 /* Opcode: ResetSorter P1 * * * *
75710 **
75711 ** Delete all contents from the ephemeral table or sorter
75712 ** that is open on cursor P1.
75713 **
75714 ** This opcode only works for cursors used for sorting and
75715 ** opened with OP_OpenEphemeral or OP_SorterOpen.
75716 */
75717 case OP_ResetSorter: {
75718   VdbeCursor *pC;
75719  
75720   assert( pOp->p1>=0 && pOp->p1<p->nCursor );
75721   pC = p->apCsr[pOp->p1];
75722   assert( pC!=0 );
75723   if( pC->pSorter ){
75724     sqlite3VdbeSorterReset(db, pC->pSorter);
75725   }else{
75726     assert( pC->isEphemeral );
75727     rc = sqlite3BtreeClearTableOfCursor(pC->pCursor);
75728   }
75729   break;
75730 }
75731
75732 /* Opcode: CreateTable P1 P2 * * *
75733 ** Synopsis: r[P2]=root iDb=P1
75734 **
75735 ** Allocate a new table in the main database file if P1==0 or in the
75736 ** auxiliary database file if P1==1 or in an attached database if
75737 ** P1>1.  Write the root page number of the new table into
75738 ** register P2
75739 **
75740 ** The difference between a table and an index is this:  A table must
75741 ** have a 4-byte integer key and can have arbitrary data.  An index
75742 ** has an arbitrary key but no data.
75743 **
75744 ** See also: CreateIndex
75745 */
75746 /* Opcode: CreateIndex P1 P2 * * *
75747 ** Synopsis: r[P2]=root iDb=P1
75748 **
75749 ** Allocate a new index in the main database file if P1==0 or in the
75750 ** auxiliary database file if P1==1 or in an attached database if
75751 ** P1>1.  Write the root page number of the new table into
75752 ** register P2.
75753 **
75754 ** See documentation on OP_CreateTable for additional information.
75755 */
75756 case OP_CreateIndex:            /* out2-prerelease */
75757 case OP_CreateTable: {          /* out2-prerelease */
75758   int pgno;
75759   int flags;
75760   Db *pDb;
75761
75762   pgno = 0;
75763   assert( pOp->p1>=0 && pOp->p1<db->nDb );
75764   assert( DbMaskTest(p->btreeMask, pOp->p1) );
75765   assert( p->readOnly==0 );
75766   pDb = &db->aDb[pOp->p1];
75767   assert( pDb->pBt!=0 );
75768   if( pOp->opcode==OP_CreateTable ){
75769     /* flags = BTREE_INTKEY; */
75770     flags = BTREE_INTKEY;
75771   }else{
75772     flags = BTREE_BLOBKEY;
75773   }
75774   rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
75775   pOut->u.i = pgno;
75776   break;
75777 }
75778
75779 /* Opcode: ParseSchema P1 * * P4 *
75780 **
75781 ** Read and parse all entries from the SQLITE_MASTER table of database P1
75782 ** that match the WHERE clause P4. 
75783 **
75784 ** This opcode invokes the parser to create a new virtual machine,
75785 ** then runs the new virtual machine.  It is thus a re-entrant opcode.
75786 */
75787 case OP_ParseSchema: {
75788   int iDb;
75789   const char *zMaster;
75790   char *zSql;
75791   InitData initData;
75792
75793   /* Any prepared statement that invokes this opcode will hold mutexes
75794   ** on every btree.  This is a prerequisite for invoking 
75795   ** sqlite3InitCallback().
75796   */
75797 #ifdef SQLITE_DEBUG
75798   for(iDb=0; iDb<db->nDb; iDb++){
75799     assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
75800   }
75801 #endif
75802
75803   iDb = pOp->p1;
75804   assert( iDb>=0 && iDb<db->nDb );
75805   assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
75806   /* Used to be a conditional */ {
75807     zMaster = SCHEMA_TABLE(iDb);
75808     initData.db = db;
75809     initData.iDb = pOp->p1;
75810     initData.pzErrMsg = &p->zErrMsg;
75811     zSql = sqlite3MPrintf(db,
75812        "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
75813        db->aDb[iDb].zName, zMaster, pOp->p4.z);
75814     if( zSql==0 ){
75815       rc = SQLITE_NOMEM;
75816     }else{
75817       assert( db->init.busy==0 );
75818       db->init.busy = 1;
75819       initData.rc = SQLITE_OK;
75820       assert( !db->mallocFailed );
75821       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
75822       if( rc==SQLITE_OK ) rc = initData.rc;
75823       sqlite3DbFree(db, zSql);
75824       db->init.busy = 0;
75825     }
75826   }
75827   if( rc ) sqlite3ResetAllSchemasOfConnection(db);
75828   if( rc==SQLITE_NOMEM ){
75829     goto no_mem;
75830   }
75831   break;  
75832 }
75833
75834 #if !defined(SQLITE_OMIT_ANALYZE)
75835 /* Opcode: LoadAnalysis P1 * * * *
75836 **
75837 ** Read the sqlite_stat1 table for database P1 and load the content
75838 ** of that table into the internal index hash table.  This will cause
75839 ** the analysis to be used when preparing all subsequent queries.
75840 */
75841 case OP_LoadAnalysis: {
75842   assert( pOp->p1>=0 && pOp->p1<db->nDb );
75843   rc = sqlite3AnalysisLoad(db, pOp->p1);
75844   break;  
75845 }
75846 #endif /* !defined(SQLITE_OMIT_ANALYZE) */
75847
75848 /* Opcode: DropTable P1 * * P4 *
75849 **
75850 ** Remove the internal (in-memory) data structures that describe
75851 ** the table named P4 in database P1.  This is called after a table
75852 ** is dropped from disk (using the Destroy opcode) in order to keep 
75853 ** the internal representation of the
75854 ** schema consistent with what is on disk.
75855 */
75856 case OP_DropTable: {
75857   sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
75858   break;
75859 }
75860
75861 /* Opcode: DropIndex P1 * * P4 *
75862 **
75863 ** Remove the internal (in-memory) data structures that describe
75864 ** the index named P4 in database P1.  This is called after an index
75865 ** is dropped from disk (using the Destroy opcode)
75866 ** in order to keep the internal representation of the
75867 ** schema consistent with what is on disk.
75868 */
75869 case OP_DropIndex: {
75870   sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
75871   break;
75872 }
75873
75874 /* Opcode: DropTrigger P1 * * P4 *
75875 **
75876 ** Remove the internal (in-memory) data structures that describe
75877 ** the trigger named P4 in database P1.  This is called after a trigger
75878 ** is dropped from disk (using the Destroy opcode) in order to keep 
75879 ** the internal representation of the
75880 ** schema consistent with what is on disk.
75881 */
75882 case OP_DropTrigger: {
75883   sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
75884   break;
75885 }
75886
75887
75888 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
75889 /* Opcode: IntegrityCk P1 P2 P3 * P5
75890 **
75891 ** Do an analysis of the currently open database.  Store in
75892 ** register P1 the text of an error message describing any problems.
75893 ** If no problems are found, store a NULL in register P1.
75894 **
75895 ** The register P3 contains the maximum number of allowed errors.
75896 ** At most reg(P3) errors will be reported.
75897 ** In other words, the analysis stops as soon as reg(P1) errors are 
75898 ** seen.  Reg(P1) is updated with the number of errors remaining.
75899 **
75900 ** The root page numbers of all tables in the database are integer
75901 ** stored in reg(P1), reg(P1+1), reg(P1+2), ....  There are P2 tables
75902 ** total.
75903 **
75904 ** If P5 is not zero, the check is done on the auxiliary database
75905 ** file, not the main database file.
75906 **
75907 ** This opcode is used to implement the integrity_check pragma.
75908 */
75909 case OP_IntegrityCk: {
75910   int nRoot;      /* Number of tables to check.  (Number of root pages.) */
75911   int *aRoot;     /* Array of rootpage numbers for tables to be checked */
75912   int j;          /* Loop counter */
75913   int nErr;       /* Number of errors reported */
75914   char *z;        /* Text of the error report */
75915   Mem *pnErr;     /* Register keeping track of errors remaining */
75916
75917   assert( p->bIsReader );
75918   nRoot = pOp->p2;
75919   assert( nRoot>0 );
75920   aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
75921   if( aRoot==0 ) goto no_mem;
75922   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
75923   pnErr = &aMem[pOp->p3];
75924   assert( (pnErr->flags & MEM_Int)!=0 );
75925   assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
75926   pIn1 = &aMem[pOp->p1];
75927   for(j=0; j<nRoot; j++){
75928     aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
75929   }
75930   aRoot[j] = 0;
75931   assert( pOp->p5<db->nDb );
75932   assert( DbMaskTest(p->btreeMask, pOp->p5) );
75933   z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
75934                                  (int)pnErr->u.i, &nErr);
75935   sqlite3DbFree(db, aRoot);
75936   pnErr->u.i -= nErr;
75937   sqlite3VdbeMemSetNull(pIn1);
75938   if( nErr==0 ){
75939     assert( z==0 );
75940   }else if( z==0 ){
75941     goto no_mem;
75942   }else{
75943     sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
75944   }
75945   UPDATE_MAX_BLOBSIZE(pIn1);
75946   sqlite3VdbeChangeEncoding(pIn1, encoding);
75947   break;
75948 }
75949 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
75950
75951 /* Opcode: RowSetAdd P1 P2 * * *
75952 ** Synopsis:  rowset(P1)=r[P2]
75953 **
75954 ** Insert the integer value held by register P2 into a boolean index
75955 ** held in register P1.
75956 **
75957 ** An assertion fails if P2 is not an integer.
75958 */
75959 case OP_RowSetAdd: {       /* in1, in2 */
75960   pIn1 = &aMem[pOp->p1];
75961   pIn2 = &aMem[pOp->p2];
75962   assert( (pIn2->flags & MEM_Int)!=0 );
75963   if( (pIn1->flags & MEM_RowSet)==0 ){
75964     sqlite3VdbeMemSetRowSet(pIn1);
75965     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
75966   }
75967   sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
75968   break;
75969 }
75970
75971 /* Opcode: RowSetRead P1 P2 P3 * *
75972 ** Synopsis:  r[P3]=rowset(P1)
75973 **
75974 ** Extract the smallest value from boolean index P1 and put that value into
75975 ** register P3.  Or, if boolean index P1 is initially empty, leave P3
75976 ** unchanged and jump to instruction P2.
75977 */
75978 case OP_RowSetRead: {       /* jump, in1, out3 */
75979   i64 val;
75980
75981   pIn1 = &aMem[pOp->p1];
75982   if( (pIn1->flags & MEM_RowSet)==0 
75983    || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
75984   ){
75985     /* The boolean index is empty */
75986     sqlite3VdbeMemSetNull(pIn1);
75987     pc = pOp->p2 - 1;
75988     VdbeBranchTaken(1,2);
75989   }else{
75990     /* A value was pulled from the index */
75991     sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
75992     VdbeBranchTaken(0,2);
75993   }
75994   goto check_for_interrupt;
75995 }
75996
75997 /* Opcode: RowSetTest P1 P2 P3 P4
75998 ** Synopsis: if r[P3] in rowset(P1) goto P2
75999 **
76000 ** Register P3 is assumed to hold a 64-bit integer value. If register P1
76001 ** contains a RowSet object and that RowSet object contains
76002 ** the value held in P3, jump to register P2. Otherwise, insert the
76003 ** integer in P3 into the RowSet and continue on to the
76004 ** next opcode.
76005 **
76006 ** The RowSet object is optimized for the case where successive sets
76007 ** of integers, where each set contains no duplicates. Each set
76008 ** of values is identified by a unique P4 value. The first set
76009 ** must have P4==0, the final set P4=-1.  P4 must be either -1 or
76010 ** non-negative.  For non-negative values of P4 only the lower 4
76011 ** bits are significant.
76012 **
76013 ** This allows optimizations: (a) when P4==0 there is no need to test
76014 ** the rowset object for P3, as it is guaranteed not to contain it,
76015 ** (b) when P4==-1 there is no need to insert the value, as it will
76016 ** never be tested for, and (c) when a value that is part of set X is
76017 ** inserted, there is no need to search to see if the same value was
76018 ** previously inserted as part of set X (only if it was previously
76019 ** inserted as part of some other set).
76020 */
76021 case OP_RowSetTest: {                     /* jump, in1, in3 */
76022   int iSet;
76023   int exists;
76024
76025   pIn1 = &aMem[pOp->p1];
76026   pIn3 = &aMem[pOp->p3];
76027   iSet = pOp->p4.i;
76028   assert( pIn3->flags&MEM_Int );
76029
76030   /* If there is anything other than a rowset object in memory cell P1,
76031   ** delete it now and initialize P1 with an empty rowset
76032   */
76033   if( (pIn1->flags & MEM_RowSet)==0 ){
76034     sqlite3VdbeMemSetRowSet(pIn1);
76035     if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
76036   }
76037
76038   assert( pOp->p4type==P4_INT32 );
76039   assert( iSet==-1 || iSet>=0 );
76040   if( iSet ){
76041     exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
76042     VdbeBranchTaken(exists!=0,2);
76043     if( exists ){
76044       pc = pOp->p2 - 1;
76045       break;
76046     }
76047   }
76048   if( iSet>=0 ){
76049     sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
76050   }
76051   break;
76052 }
76053
76054
76055 #ifndef SQLITE_OMIT_TRIGGER
76056
76057 /* Opcode: Program P1 P2 P3 P4 P5
76058 **
76059 ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM). 
76060 **
76061 ** P1 contains the address of the memory cell that contains the first memory 
76062 ** cell in an array of values used as arguments to the sub-program. P2 
76063 ** contains the address to jump to if the sub-program throws an IGNORE 
76064 ** exception using the RAISE() function. Register P3 contains the address 
76065 ** of a memory cell in this (the parent) VM that is used to allocate the 
76066 ** memory required by the sub-vdbe at runtime.
76067 **
76068 ** P4 is a pointer to the VM containing the trigger program.
76069 **
76070 ** If P5 is non-zero, then recursive program invocation is enabled.
76071 */
76072 case OP_Program: {        /* jump */
76073   int nMem;               /* Number of memory registers for sub-program */
76074   int nByte;              /* Bytes of runtime space required for sub-program */
76075   Mem *pRt;               /* Register to allocate runtime space */
76076   Mem *pMem;              /* Used to iterate through memory cells */
76077   Mem *pEnd;              /* Last memory cell in new array */
76078   VdbeFrame *pFrame;      /* New vdbe frame to execute in */
76079   SubProgram *pProgram;   /* Sub-program to execute */
76080   void *t;                /* Token identifying trigger */
76081
76082   pProgram = pOp->p4.pProgram;
76083   pRt = &aMem[pOp->p3];
76084   assert( pProgram->nOp>0 );
76085   
76086   /* If the p5 flag is clear, then recursive invocation of triggers is 
76087   ** disabled for backwards compatibility (p5 is set if this sub-program
76088   ** is really a trigger, not a foreign key action, and the flag set
76089   ** and cleared by the "PRAGMA recursive_triggers" command is clear).
76090   ** 
76091   ** It is recursive invocation of triggers, at the SQL level, that is 
76092   ** disabled. In some cases a single trigger may generate more than one 
76093   ** SubProgram (if the trigger may be executed with more than one different 
76094   ** ON CONFLICT algorithm). SubProgram structures associated with a
76095   ** single trigger all have the same value for the SubProgram.token 
76096   ** variable.  */
76097   if( pOp->p5 ){
76098     t = pProgram->token;
76099     for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
76100     if( pFrame ) break;
76101   }
76102
76103   if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
76104     rc = SQLITE_ERROR;
76105     sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
76106     break;
76107   }
76108
76109   /* Register pRt is used to store the memory required to save the state
76110   ** of the current program, and the memory required at runtime to execute
76111   ** the trigger program. If this trigger has been fired before, then pRt 
76112   ** is already allocated. Otherwise, it must be initialized.  */
76113   if( (pRt->flags&MEM_Frame)==0 ){
76114     /* SubProgram.nMem is set to the number of memory cells used by the 
76115     ** program stored in SubProgram.aOp. As well as these, one memory
76116     ** cell is required for each cursor used by the program. Set local
76117     ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
76118     */
76119     nMem = pProgram->nMem + pProgram->nCsr;
76120     nByte = ROUND8(sizeof(VdbeFrame))
76121               + nMem * sizeof(Mem)
76122               + pProgram->nCsr * sizeof(VdbeCursor *)
76123               + pProgram->nOnce * sizeof(u8);
76124     pFrame = sqlite3DbMallocZero(db, nByte);
76125     if( !pFrame ){
76126       goto no_mem;
76127     }
76128     sqlite3VdbeMemRelease(pRt);
76129     pRt->flags = MEM_Frame;
76130     pRt->u.pFrame = pFrame;
76131
76132     pFrame->v = p;
76133     pFrame->nChildMem = nMem;
76134     pFrame->nChildCsr = pProgram->nCsr;
76135     pFrame->pc = pc;
76136     pFrame->aMem = p->aMem;
76137     pFrame->nMem = p->nMem;
76138     pFrame->apCsr = p->apCsr;
76139     pFrame->nCursor = p->nCursor;
76140     pFrame->aOp = p->aOp;
76141     pFrame->nOp = p->nOp;
76142     pFrame->token = pProgram->token;
76143     pFrame->aOnceFlag = p->aOnceFlag;
76144     pFrame->nOnceFlag = p->nOnceFlag;
76145 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
76146     pFrame->anExec = p->anExec;
76147 #endif
76148
76149     pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
76150     for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
76151       pMem->flags = MEM_Undefined;
76152       pMem->db = db;
76153     }
76154   }else{
76155     pFrame = pRt->u.pFrame;
76156     assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem );
76157     assert( pProgram->nCsr==pFrame->nChildCsr );
76158     assert( pc==pFrame->pc );
76159   }
76160
76161   p->nFrame++;
76162   pFrame->pParent = p->pFrame;
76163   pFrame->lastRowid = lastRowid;
76164   pFrame->nChange = p->nChange;
76165   pFrame->nDbChange = p->db->nChange;
76166   p->nChange = 0;
76167   p->pFrame = pFrame;
76168   p->aMem = aMem = &VdbeFrameMem(pFrame)[-1];
76169   p->nMem = pFrame->nChildMem;
76170   p->nCursor = (u16)pFrame->nChildCsr;
76171   p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
76172   p->aOp = aOp = pProgram->aOp;
76173   p->nOp = pProgram->nOp;
76174   p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
76175   p->nOnceFlag = pProgram->nOnce;
76176 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
76177   p->anExec = 0;
76178 #endif
76179   pc = -1;
76180   memset(p->aOnceFlag, 0, p->nOnceFlag);
76181
76182   break;
76183 }
76184
76185 /* Opcode: Param P1 P2 * * *
76186 **
76187 ** This opcode is only ever present in sub-programs called via the 
76188 ** OP_Program instruction. Copy a value currently stored in a memory 
76189 ** cell of the calling (parent) frame to cell P2 in the current frames 
76190 ** address space. This is used by trigger programs to access the new.* 
76191 ** and old.* values.
76192 **
76193 ** The address of the cell in the parent frame is determined by adding
76194 ** the value of the P1 argument to the value of the P1 argument to the
76195 ** calling OP_Program instruction.
76196 */
76197 case OP_Param: {           /* out2-prerelease */
76198   VdbeFrame *pFrame;
76199   Mem *pIn;
76200   pFrame = p->pFrame;
76201   pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];   
76202   sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
76203   break;
76204 }
76205
76206 #endif /* #ifndef SQLITE_OMIT_TRIGGER */
76207
76208 #ifndef SQLITE_OMIT_FOREIGN_KEY
76209 /* Opcode: FkCounter P1 P2 * * *
76210 ** Synopsis: fkctr[P1]+=P2
76211 **
76212 ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
76213 ** If P1 is non-zero, the database constraint counter is incremented 
76214 ** (deferred foreign key constraints). Otherwise, if P1 is zero, the 
76215 ** statement counter is incremented (immediate foreign key constraints).
76216 */
76217 case OP_FkCounter: {
76218   if( db->flags & SQLITE_DeferFKs ){
76219     db->nDeferredImmCons += pOp->p2;
76220   }else if( pOp->p1 ){
76221     db->nDeferredCons += pOp->p2;
76222   }else{
76223     p->nFkConstraint += pOp->p2;
76224   }
76225   break;
76226 }
76227
76228 /* Opcode: FkIfZero P1 P2 * * *
76229 ** Synopsis: if fkctr[P1]==0 goto P2
76230 **
76231 ** This opcode tests if a foreign key constraint-counter is currently zero.
76232 ** If so, jump to instruction P2. Otherwise, fall through to the next 
76233 ** instruction.
76234 **
76235 ** If P1 is non-zero, then the jump is taken if the database constraint-counter
76236 ** is zero (the one that counts deferred constraint violations). If P1 is
76237 ** zero, the jump is taken if the statement constraint-counter is zero
76238 ** (immediate foreign key constraint violations).
76239 */
76240 case OP_FkIfZero: {         /* jump */
76241   if( pOp->p1 ){
76242     VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
76243     if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
76244   }else{
76245     VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
76246     if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
76247   }
76248   break;
76249 }
76250 #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
76251
76252 #ifndef SQLITE_OMIT_AUTOINCREMENT
76253 /* Opcode: MemMax P1 P2 * * *
76254 ** Synopsis: r[P1]=max(r[P1],r[P2])
76255 **
76256 ** P1 is a register in the root frame of this VM (the root frame is
76257 ** different from the current frame if this instruction is being executed
76258 ** within a sub-program). Set the value of register P1 to the maximum of 
76259 ** its current value and the value in register P2.
76260 **
76261 ** This instruction throws an error if the memory cell is not initially
76262 ** an integer.
76263 */
76264 case OP_MemMax: {        /* in2 */
76265   VdbeFrame *pFrame;
76266   if( p->pFrame ){
76267     for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
76268     pIn1 = &pFrame->aMem[pOp->p1];
76269   }else{
76270     pIn1 = &aMem[pOp->p1];
76271   }
76272   assert( memIsValid(pIn1) );
76273   sqlite3VdbeMemIntegerify(pIn1);
76274   pIn2 = &aMem[pOp->p2];
76275   sqlite3VdbeMemIntegerify(pIn2);
76276   if( pIn1->u.i<pIn2->u.i){
76277     pIn1->u.i = pIn2->u.i;
76278   }
76279   break;
76280 }
76281 #endif /* SQLITE_OMIT_AUTOINCREMENT */
76282
76283 /* Opcode: IfPos P1 P2 * * *
76284 ** Synopsis: if r[P1]>0 goto P2
76285 **
76286 ** Register P1 must contain an integer.
76287 ** If the value of register P1 is 1 or greater, jump to P2 and
76288 ** add the literal value P3 to register P1.
76289 **
76290 ** If the initial value of register P1 is less than 1, then the
76291 ** value is unchanged and control passes through to the next instruction.
76292 */
76293 case OP_IfPos: {        /* jump, in1 */
76294   pIn1 = &aMem[pOp->p1];
76295   assert( pIn1->flags&MEM_Int );
76296   VdbeBranchTaken( pIn1->u.i>0, 2);
76297   if( pIn1->u.i>0 ){
76298      pc = pOp->p2 - 1;
76299   }
76300   break;
76301 }
76302
76303 /* Opcode: IfNeg P1 P2 P3 * *
76304 ** Synopsis: r[P1]+=P3, if r[P1]<0 goto P2
76305 **
76306 ** Register P1 must contain an integer.  Add literal P3 to the value in
76307 ** register P1 then if the value of register P1 is less than zero, jump to P2. 
76308 */
76309 case OP_IfNeg: {        /* jump, in1 */
76310   pIn1 = &aMem[pOp->p1];
76311   assert( pIn1->flags&MEM_Int );
76312   pIn1->u.i += pOp->p3;
76313   VdbeBranchTaken(pIn1->u.i<0, 2);
76314   if( pIn1->u.i<0 ){
76315      pc = pOp->p2 - 1;
76316   }
76317   break;
76318 }
76319
76320 /* Opcode: IfNotZero P1 P2 P3 * *
76321 ** Synopsis: if r[P1]!=0 then r[P1]+=P3, goto P2
76322 **
76323 ** Register P1 must contain an integer.  If the content of register P1 is
76324 ** initially nonzero, then add P3 to P1 and jump to P2.  If register P1 is
76325 ** initially zero, leave it unchanged and fall through.
76326 */
76327 case OP_IfNotZero: {        /* jump, in1 */
76328   pIn1 = &aMem[pOp->p1];
76329   assert( pIn1->flags&MEM_Int );
76330   VdbeBranchTaken(pIn1->u.i<0, 2);
76331   if( pIn1->u.i ){
76332      pIn1->u.i += pOp->p3;
76333      pc = pOp->p2 - 1;
76334   }
76335   break;
76336 }
76337
76338 /* Opcode: DecrJumpZero P1 P2 * * *
76339 ** Synopsis: if (--r[P1])==0 goto P2
76340 **
76341 ** Register P1 must hold an integer.  Decrement the value in register P1
76342 ** then jump to P2 if the new value is exactly zero.
76343 */
76344 case OP_DecrJumpZero: {      /* jump, in1 */
76345   pIn1 = &aMem[pOp->p1];
76346   assert( pIn1->flags&MEM_Int );
76347   pIn1->u.i--;
76348   VdbeBranchTaken(pIn1->u.i==0, 2);
76349   if( pIn1->u.i==0 ){
76350      pc = pOp->p2 - 1;
76351   }
76352   break;
76353 }
76354
76355
76356 /* Opcode: JumpZeroIncr P1 P2 * * *
76357 ** Synopsis: if (r[P1]++)==0 ) goto P2
76358 **
76359 ** The register P1 must contain an integer.  If register P1 is initially
76360 ** zero, then jump to P2.  Increment register P1 regardless of whether or
76361 ** not the jump is taken.
76362 */
76363 case OP_JumpZeroIncr: {        /* jump, in1 */
76364   pIn1 = &aMem[pOp->p1];
76365   assert( pIn1->flags&MEM_Int );
76366   VdbeBranchTaken(pIn1->u.i==0, 2);
76367   if( (pIn1->u.i++)==0 ){
76368      pc = pOp->p2 - 1;
76369   }
76370   break;
76371 }
76372
76373 /* Opcode: AggStep * P2 P3 P4 P5
76374 ** Synopsis: accum=r[P3] step(r[P2@P5])
76375 **
76376 ** Execute the step function for an aggregate.  The
76377 ** function has P5 arguments.   P4 is a pointer to the FuncDef
76378 ** structure that specifies the function.  Use register
76379 ** P3 as the accumulator.
76380 **
76381 ** The P5 arguments are taken from register P2 and its
76382 ** successors.
76383 */
76384 case OP_AggStep: {
76385   int n;
76386   int i;
76387   Mem *pMem;
76388   Mem *pRec;
76389   Mem t;
76390   sqlite3_context ctx;
76391   sqlite3_value **apVal;
76392
76393   n = pOp->p5;
76394   assert( n>=0 );
76395   pRec = &aMem[pOp->p2];
76396   apVal = p->apArg;
76397   assert( apVal || n==0 );
76398   for(i=0; i<n; i++, pRec++){
76399     assert( memIsValid(pRec) );
76400     apVal[i] = pRec;
76401     memAboutToChange(p, pRec);
76402   }
76403   ctx.pFunc = pOp->p4.pFunc;
76404   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
76405   ctx.pMem = pMem = &aMem[pOp->p3];
76406   pMem->n++;
76407   sqlite3VdbeMemInit(&t, db, MEM_Null);
76408   ctx.pOut = &t;
76409   ctx.isError = 0;
76410   ctx.pVdbe = p;
76411   ctx.iOp = pc;
76412   ctx.skipFlag = 0;
76413   (ctx.pFunc->xStep)(&ctx, n, apVal); /* IMP: R-24505-23230 */
76414   if( ctx.isError ){
76415     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&t));
76416     rc = ctx.isError;
76417   }
76418   if( ctx.skipFlag ){
76419     assert( pOp[-1].opcode==OP_CollSeq );
76420     i = pOp[-1].p1;
76421     if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
76422   }
76423   sqlite3VdbeMemRelease(&t);
76424   break;
76425 }
76426
76427 /* Opcode: AggFinal P1 P2 * P4 *
76428 ** Synopsis: accum=r[P1] N=P2
76429 **
76430 ** Execute the finalizer function for an aggregate.  P1 is
76431 ** the memory location that is the accumulator for the aggregate.
76432 **
76433 ** P2 is the number of arguments that the step function takes and
76434 ** P4 is a pointer to the FuncDef for this function.  The P2
76435 ** argument is not used by this opcode.  It is only there to disambiguate
76436 ** functions that can take varying numbers of arguments.  The
76437 ** P4 argument is only needed for the degenerate case where
76438 ** the step function was not previously called.
76439 */
76440 case OP_AggFinal: {
76441   Mem *pMem;
76442   assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
76443   pMem = &aMem[pOp->p1];
76444   assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
76445   rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
76446   if( rc ){
76447     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem));
76448   }
76449   sqlite3VdbeChangeEncoding(pMem, encoding);
76450   UPDATE_MAX_BLOBSIZE(pMem);
76451   if( sqlite3VdbeMemTooBig(pMem) ){
76452     goto too_big;
76453   }
76454   break;
76455 }
76456
76457 #ifndef SQLITE_OMIT_WAL
76458 /* Opcode: Checkpoint P1 P2 P3 * *
76459 **
76460 ** Checkpoint database P1. This is a no-op if P1 is not currently in
76461 ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL,
76462 ** RESTART, or TRUNCATE.  Write 1 or 0 into mem[P3] if the checkpoint returns
76463 ** SQLITE_BUSY or not, respectively.  Write the number of pages in the
76464 ** WAL after the checkpoint into mem[P3+1] and the number of pages
76465 ** in the WAL that have been checkpointed after the checkpoint
76466 ** completes into mem[P3+2].  However on an error, mem[P3+1] and
76467 ** mem[P3+2] are initialized to -1.
76468 */
76469 case OP_Checkpoint: {
76470   int i;                          /* Loop counter */
76471   int aRes[3];                    /* Results */
76472   Mem *pMem;                      /* Write results here */
76473
76474   assert( p->readOnly==0 );
76475   aRes[0] = 0;
76476   aRes[1] = aRes[2] = -1;
76477   assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
76478        || pOp->p2==SQLITE_CHECKPOINT_FULL
76479        || pOp->p2==SQLITE_CHECKPOINT_RESTART
76480        || pOp->p2==SQLITE_CHECKPOINT_TRUNCATE
76481   );
76482   rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
76483   if( rc==SQLITE_BUSY ){
76484     rc = SQLITE_OK;
76485     aRes[0] = 1;
76486   }
76487   for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
76488     sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
76489   }    
76490   break;
76491 };  
76492 #endif
76493
76494 #ifndef SQLITE_OMIT_PRAGMA
76495 /* Opcode: JournalMode P1 P2 P3 * *
76496 **
76497 ** Change the journal mode of database P1 to P3. P3 must be one of the
76498 ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
76499 ** modes (delete, truncate, persist, off and memory), this is a simple
76500 ** operation. No IO is required.
76501 **
76502 ** If changing into or out of WAL mode the procedure is more complicated.
76503 **
76504 ** Write a string containing the final journal-mode to register P2.
76505 */
76506 case OP_JournalMode: {    /* out2-prerelease */
76507   Btree *pBt;                     /* Btree to change journal mode of */
76508   Pager *pPager;                  /* Pager associated with pBt */
76509   int eNew;                       /* New journal mode */
76510   int eOld;                       /* The old journal mode */
76511 #ifndef SQLITE_OMIT_WAL
76512   const char *zFilename;          /* Name of database file for pPager */
76513 #endif
76514
76515   eNew = pOp->p3;
76516   assert( eNew==PAGER_JOURNALMODE_DELETE 
76517        || eNew==PAGER_JOURNALMODE_TRUNCATE 
76518        || eNew==PAGER_JOURNALMODE_PERSIST 
76519        || eNew==PAGER_JOURNALMODE_OFF
76520        || eNew==PAGER_JOURNALMODE_MEMORY
76521        || eNew==PAGER_JOURNALMODE_WAL
76522        || eNew==PAGER_JOURNALMODE_QUERY
76523   );
76524   assert( pOp->p1>=0 && pOp->p1<db->nDb );
76525   assert( p->readOnly==0 );
76526
76527   pBt = db->aDb[pOp->p1].pBt;
76528   pPager = sqlite3BtreePager(pBt);
76529   eOld = sqlite3PagerGetJournalMode(pPager);
76530   if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
76531   if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
76532
76533 #ifndef SQLITE_OMIT_WAL
76534   zFilename = sqlite3PagerFilename(pPager, 1);
76535
76536   /* Do not allow a transition to journal_mode=WAL for a database
76537   ** in temporary storage or if the VFS does not support shared memory 
76538   */
76539   if( eNew==PAGER_JOURNALMODE_WAL
76540    && (sqlite3Strlen30(zFilename)==0           /* Temp file */
76541        || !sqlite3PagerWalSupported(pPager))   /* No shared-memory support */
76542   ){
76543     eNew = eOld;
76544   }
76545
76546   if( (eNew!=eOld)
76547    && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
76548   ){
76549     if( !db->autoCommit || db->nVdbeRead>1 ){
76550       rc = SQLITE_ERROR;
76551       sqlite3SetString(&p->zErrMsg, db, 
76552           "cannot change %s wal mode from within a transaction",
76553           (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
76554       );
76555       break;
76556     }else{
76557  
76558       if( eOld==PAGER_JOURNALMODE_WAL ){
76559         /* If leaving WAL mode, close the log file. If successful, the call
76560         ** to PagerCloseWal() checkpoints and deletes the write-ahead-log 
76561         ** file. An EXCLUSIVE lock may still be held on the database file 
76562         ** after a successful return. 
76563         */
76564         rc = sqlite3PagerCloseWal(pPager);
76565         if( rc==SQLITE_OK ){
76566           sqlite3PagerSetJournalMode(pPager, eNew);
76567         }
76568       }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
76569         /* Cannot transition directly from MEMORY to WAL.  Use mode OFF
76570         ** as an intermediate */
76571         sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
76572       }
76573   
76574       /* Open a transaction on the database file. Regardless of the journal
76575       ** mode, this transaction always uses a rollback journal.
76576       */
76577       assert( sqlite3BtreeIsInTrans(pBt)==0 );
76578       if( rc==SQLITE_OK ){
76579         rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
76580       }
76581     }
76582   }
76583 #endif /* ifndef SQLITE_OMIT_WAL */
76584
76585   if( rc ){
76586     eNew = eOld;
76587   }
76588   eNew = sqlite3PagerSetJournalMode(pPager, eNew);
76589
76590   pOut = &aMem[pOp->p2];
76591   pOut->flags = MEM_Str|MEM_Static|MEM_Term;
76592   pOut->z = (char *)sqlite3JournalModename(eNew);
76593   pOut->n = sqlite3Strlen30(pOut->z);
76594   pOut->enc = SQLITE_UTF8;
76595   sqlite3VdbeChangeEncoding(pOut, encoding);
76596   break;
76597 };
76598 #endif /* SQLITE_OMIT_PRAGMA */
76599
76600 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
76601 /* Opcode: Vacuum * * * * *
76602 **
76603 ** Vacuum the entire database.  This opcode will cause other virtual
76604 ** machines to be created and run.  It may not be called from within
76605 ** a transaction.
76606 */
76607 case OP_Vacuum: {
76608   assert( p->readOnly==0 );
76609   rc = sqlite3RunVacuum(&p->zErrMsg, db);
76610   break;
76611 }
76612 #endif
76613
76614 #if !defined(SQLITE_OMIT_AUTOVACUUM)
76615 /* Opcode: IncrVacuum P1 P2 * * *
76616 **
76617 ** Perform a single step of the incremental vacuum procedure on
76618 ** the P1 database. If the vacuum has finished, jump to instruction
76619 ** P2. Otherwise, fall through to the next instruction.
76620 */
76621 case OP_IncrVacuum: {        /* jump */
76622   Btree *pBt;
76623
76624   assert( pOp->p1>=0 && pOp->p1<db->nDb );
76625   assert( DbMaskTest(p->btreeMask, pOp->p1) );
76626   assert( p->readOnly==0 );
76627   pBt = db->aDb[pOp->p1].pBt;
76628   rc = sqlite3BtreeIncrVacuum(pBt);
76629   VdbeBranchTaken(rc==SQLITE_DONE,2);
76630   if( rc==SQLITE_DONE ){
76631     pc = pOp->p2 - 1;
76632     rc = SQLITE_OK;
76633   }
76634   break;
76635 }
76636 #endif
76637
76638 /* Opcode: Expire P1 * * * *
76639 **
76640 ** Cause precompiled statements to expire.  When an expired statement
76641 ** is executed using sqlite3_step() it will either automatically
76642 ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
76643 ** or it will fail with SQLITE_SCHEMA.
76644 ** 
76645 ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
76646 ** then only the currently executing statement is expired.
76647 */
76648 case OP_Expire: {
76649   if( !pOp->p1 ){
76650     sqlite3ExpirePreparedStatements(db);
76651   }else{
76652     p->expired = 1;
76653   }
76654   break;
76655 }
76656
76657 #ifndef SQLITE_OMIT_SHARED_CACHE
76658 /* Opcode: TableLock P1 P2 P3 P4 *
76659 ** Synopsis: iDb=P1 root=P2 write=P3
76660 **
76661 ** Obtain a lock on a particular table. This instruction is only used when
76662 ** the shared-cache feature is enabled. 
76663 **
76664 ** P1 is the index of the database in sqlite3.aDb[] of the database
76665 ** on which the lock is acquired.  A readlock is obtained if P3==0 or
76666 ** a write lock if P3==1.
76667 **
76668 ** P2 contains the root-page of the table to lock.
76669 **
76670 ** P4 contains a pointer to the name of the table being locked. This is only
76671 ** used to generate an error message if the lock cannot be obtained.
76672 */
76673 case OP_TableLock: {
76674   u8 isWriteLock = (u8)pOp->p3;
76675   if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
76676     int p1 = pOp->p1; 
76677     assert( p1>=0 && p1<db->nDb );
76678     assert( DbMaskTest(p->btreeMask, p1) );
76679     assert( isWriteLock==0 || isWriteLock==1 );
76680     rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
76681     if( (rc&0xFF)==SQLITE_LOCKED ){
76682       const char *z = pOp->p4.z;
76683       sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
76684     }
76685   }
76686   break;
76687 }
76688 #endif /* SQLITE_OMIT_SHARED_CACHE */
76689
76690 #ifndef SQLITE_OMIT_VIRTUALTABLE
76691 /* Opcode: VBegin * * * P4 *
76692 **
76693 ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the 
76694 ** xBegin method for that table.
76695 **
76696 ** Also, whether or not P4 is set, check that this is not being called from
76697 ** within a callback to a virtual table xSync() method. If it is, the error
76698 ** code will be set to SQLITE_LOCKED.
76699 */
76700 case OP_VBegin: {
76701   VTable *pVTab;
76702   pVTab = pOp->p4.pVtab;
76703   rc = sqlite3VtabBegin(db, pVTab);
76704   if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
76705   break;
76706 }
76707 #endif /* SQLITE_OMIT_VIRTUALTABLE */
76708
76709 #ifndef SQLITE_OMIT_VIRTUALTABLE
76710 /* Opcode: VCreate P1 P2 * * *
76711 **
76712 ** P2 is a register that holds the name of a virtual table in database 
76713 ** P1. Call the xCreate method for that table.
76714 */
76715 case OP_VCreate: {
76716   Mem sMem;          /* For storing the record being decoded */
76717   const char *zTab;  /* Name of the virtual table */
76718
76719   memset(&sMem, 0, sizeof(sMem));
76720   sMem.db = db;
76721   /* Because P2 is always a static string, it is impossible for the
76722   ** sqlite3VdbeMemCopy() to fail */
76723   assert( (aMem[pOp->p2].flags & MEM_Str)!=0 );
76724   assert( (aMem[pOp->p2].flags & MEM_Static)!=0 );
76725   rc = sqlite3VdbeMemCopy(&sMem, &aMem[pOp->p2]);
76726   assert( rc==SQLITE_OK );
76727   zTab = (const char*)sqlite3_value_text(&sMem);
76728   assert( zTab || db->mallocFailed );
76729   if( zTab ){
76730     rc = sqlite3VtabCallCreate(db, pOp->p1, zTab, &p->zErrMsg);
76731   }
76732   sqlite3VdbeMemRelease(&sMem);
76733   break;
76734 }
76735 #endif /* SQLITE_OMIT_VIRTUALTABLE */
76736
76737 #ifndef SQLITE_OMIT_VIRTUALTABLE
76738 /* Opcode: VDestroy P1 * * P4 *
76739 **
76740 ** P4 is the name of a virtual table in database P1.  Call the xDestroy method
76741 ** of that table.
76742 */
76743 case OP_VDestroy: {
76744   db->nVDestroy++;
76745   rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
76746   db->nVDestroy--;
76747   break;
76748 }
76749 #endif /* SQLITE_OMIT_VIRTUALTABLE */
76750
76751 #ifndef SQLITE_OMIT_VIRTUALTABLE
76752 /* Opcode: VOpen P1 * * P4 *
76753 **
76754 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
76755 ** P1 is a cursor number.  This opcode opens a cursor to the virtual
76756 ** table and stores that cursor in P1.
76757 */
76758 case OP_VOpen: {
76759   VdbeCursor *pCur;
76760   sqlite3_vtab_cursor *pVtabCursor;
76761   sqlite3_vtab *pVtab;
76762   const sqlite3_module *pModule;
76763
76764   assert( p->bIsReader );
76765   pCur = 0;
76766   pVtabCursor = 0;
76767   pVtab = pOp->p4.pVtab->pVtab;
76768   if( pVtab==0 || NEVER(pVtab->pModule==0) ){
76769     rc = SQLITE_LOCKED;
76770     break;
76771   }
76772   pModule = pVtab->pModule;
76773   rc = pModule->xOpen(pVtab, &pVtabCursor);
76774   sqlite3VtabImportErrmsg(p, pVtab);
76775   if( SQLITE_OK==rc ){
76776     /* Initialize sqlite3_vtab_cursor base class */
76777     pVtabCursor->pVtab = pVtab;
76778
76779     /* Initialize vdbe cursor object */
76780     pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
76781     if( pCur ){
76782       pCur->pVtabCursor = pVtabCursor;
76783       pVtab->nRef++;
76784     }else{
76785       db->mallocFailed = 1;
76786       pModule->xClose(pVtabCursor);
76787     }
76788   }
76789   break;
76790 }
76791 #endif /* SQLITE_OMIT_VIRTUALTABLE */
76792
76793 #ifndef SQLITE_OMIT_VIRTUALTABLE
76794 /* Opcode: VFilter P1 P2 P3 P4 *
76795 ** Synopsis: iplan=r[P3] zplan='P4'
76796 **
76797 ** P1 is a cursor opened using VOpen.  P2 is an address to jump to if
76798 ** the filtered result set is empty.
76799 **
76800 ** P4 is either NULL or a string that was generated by the xBestIndex
76801 ** method of the module.  The interpretation of the P4 string is left
76802 ** to the module implementation.
76803 **
76804 ** This opcode invokes the xFilter method on the virtual table specified
76805 ** by P1.  The integer query plan parameter to xFilter is stored in register
76806 ** P3. Register P3+1 stores the argc parameter to be passed to the
76807 ** xFilter method. Registers P3+2..P3+1+argc are the argc
76808 ** additional parameters which are passed to
76809 ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
76810 **
76811 ** A jump is made to P2 if the result set after filtering would be empty.
76812 */
76813 case OP_VFilter: {   /* jump */
76814   int nArg;
76815   int iQuery;
76816   const sqlite3_module *pModule;
76817   Mem *pQuery;
76818   Mem *pArgc;
76819   sqlite3_vtab_cursor *pVtabCursor;
76820   sqlite3_vtab *pVtab;
76821   VdbeCursor *pCur;
76822   int res;
76823   int i;
76824   Mem **apArg;
76825
76826   pQuery = &aMem[pOp->p3];
76827   pArgc = &pQuery[1];
76828   pCur = p->apCsr[pOp->p1];
76829   assert( memIsValid(pQuery) );
76830   REGISTER_TRACE(pOp->p3, pQuery);
76831   assert( pCur->pVtabCursor );
76832   pVtabCursor = pCur->pVtabCursor;
76833   pVtab = pVtabCursor->pVtab;
76834   pModule = pVtab->pModule;
76835
76836   /* Grab the index number and argc parameters */
76837   assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
76838   nArg = (int)pArgc->u.i;
76839   iQuery = (int)pQuery->u.i;
76840
76841   /* Invoke the xFilter method */
76842   {
76843     res = 0;
76844     apArg = p->apArg;
76845     for(i = 0; i<nArg; i++){
76846       apArg[i] = &pArgc[i+1];
76847     }
76848
76849     rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
76850     sqlite3VtabImportErrmsg(p, pVtab);
76851     if( rc==SQLITE_OK ){
76852       res = pModule->xEof(pVtabCursor);
76853     }
76854     VdbeBranchTaken(res!=0,2);
76855     if( res ){
76856       pc = pOp->p2 - 1;
76857     }
76858   }
76859   pCur->nullRow = 0;
76860
76861   break;
76862 }
76863 #endif /* SQLITE_OMIT_VIRTUALTABLE */
76864
76865 #ifndef SQLITE_OMIT_VIRTUALTABLE
76866 /* Opcode: VColumn P1 P2 P3 * *
76867 ** Synopsis: r[P3]=vcolumn(P2)
76868 **
76869 ** Store the value of the P2-th column of
76870 ** the row of the virtual-table that the 
76871 ** P1 cursor is pointing to into register P3.
76872 */
76873 case OP_VColumn: {
76874   sqlite3_vtab *pVtab;
76875   const sqlite3_module *pModule;
76876   Mem *pDest;
76877   sqlite3_context sContext;
76878
76879   VdbeCursor *pCur = p->apCsr[pOp->p1];
76880   assert( pCur->pVtabCursor );
76881   assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
76882   pDest = &aMem[pOp->p3];
76883   memAboutToChange(p, pDest);
76884   if( pCur->nullRow ){
76885     sqlite3VdbeMemSetNull(pDest);
76886     break;
76887   }
76888   pVtab = pCur->pVtabCursor->pVtab;
76889   pModule = pVtab->pModule;
76890   assert( pModule->xColumn );
76891   memset(&sContext, 0, sizeof(sContext));
76892   sContext.pOut = pDest;
76893   MemSetTypeFlag(pDest, MEM_Null);
76894   rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
76895   sqlite3VtabImportErrmsg(p, pVtab);
76896   if( sContext.isError ){
76897     rc = sContext.isError;
76898   }
76899   sqlite3VdbeChangeEncoding(pDest, encoding);
76900   REGISTER_TRACE(pOp->p3, pDest);
76901   UPDATE_MAX_BLOBSIZE(pDest);
76902
76903   if( sqlite3VdbeMemTooBig(pDest) ){
76904     goto too_big;
76905   }
76906   break;
76907 }
76908 #endif /* SQLITE_OMIT_VIRTUALTABLE */
76909
76910 #ifndef SQLITE_OMIT_VIRTUALTABLE
76911 /* Opcode: VNext P1 P2 * * *
76912 **
76913 ** Advance virtual table P1 to the next row in its result set and
76914 ** jump to instruction P2.  Or, if the virtual table has reached
76915 ** the end of its result set, then fall through to the next instruction.
76916 */
76917 case OP_VNext: {   /* jump */
76918   sqlite3_vtab *pVtab;
76919   const sqlite3_module *pModule;
76920   int res;
76921   VdbeCursor *pCur;
76922
76923   res = 0;
76924   pCur = p->apCsr[pOp->p1];
76925   assert( pCur->pVtabCursor );
76926   if( pCur->nullRow ){
76927     break;
76928   }
76929   pVtab = pCur->pVtabCursor->pVtab;
76930   pModule = pVtab->pModule;
76931   assert( pModule->xNext );
76932
76933   /* Invoke the xNext() method of the module. There is no way for the
76934   ** underlying implementation to return an error if one occurs during
76935   ** xNext(). Instead, if an error occurs, true is returned (indicating that 
76936   ** data is available) and the error code returned when xColumn or
76937   ** some other method is next invoked on the save virtual table cursor.
76938   */
76939   rc = pModule->xNext(pCur->pVtabCursor);
76940   sqlite3VtabImportErrmsg(p, pVtab);
76941   if( rc==SQLITE_OK ){
76942     res = pModule->xEof(pCur->pVtabCursor);
76943   }
76944   VdbeBranchTaken(!res,2);
76945   if( !res ){
76946     /* If there is data, jump to P2 */
76947     pc = pOp->p2 - 1;
76948   }
76949   goto check_for_interrupt;
76950 }
76951 #endif /* SQLITE_OMIT_VIRTUALTABLE */
76952
76953 #ifndef SQLITE_OMIT_VIRTUALTABLE
76954 /* Opcode: VRename P1 * * P4 *
76955 **
76956 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
76957 ** This opcode invokes the corresponding xRename method. The value
76958 ** in register P1 is passed as the zName argument to the xRename method.
76959 */
76960 case OP_VRename: {
76961   sqlite3_vtab *pVtab;
76962   Mem *pName;
76963
76964   pVtab = pOp->p4.pVtab->pVtab;
76965   pName = &aMem[pOp->p1];
76966   assert( pVtab->pModule->xRename );
76967   assert( memIsValid(pName) );
76968   assert( p->readOnly==0 );
76969   REGISTER_TRACE(pOp->p1, pName);
76970   assert( pName->flags & MEM_Str );
76971   testcase( pName->enc==SQLITE_UTF8 );
76972   testcase( pName->enc==SQLITE_UTF16BE );
76973   testcase( pName->enc==SQLITE_UTF16LE );
76974   rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
76975   if( rc==SQLITE_OK ){
76976     rc = pVtab->pModule->xRename(pVtab, pName->z);
76977     sqlite3VtabImportErrmsg(p, pVtab);
76978     p->expired = 0;
76979   }
76980   break;
76981 }
76982 #endif
76983
76984 #ifndef SQLITE_OMIT_VIRTUALTABLE
76985 /* Opcode: VUpdate P1 P2 P3 P4 P5
76986 ** Synopsis: data=r[P3@P2]
76987 **
76988 ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
76989 ** This opcode invokes the corresponding xUpdate method. P2 values
76990 ** are contiguous memory cells starting at P3 to pass to the xUpdate 
76991 ** invocation. The value in register (P3+P2-1) corresponds to the 
76992 ** p2th element of the argv array passed to xUpdate.
76993 **
76994 ** The xUpdate method will do a DELETE or an INSERT or both.
76995 ** The argv[0] element (which corresponds to memory cell P3)
76996 ** is the rowid of a row to delete.  If argv[0] is NULL then no 
76997 ** deletion occurs.  The argv[1] element is the rowid of the new 
76998 ** row.  This can be NULL to have the virtual table select the new 
76999 ** rowid for itself.  The subsequent elements in the array are 
77000 ** the values of columns in the new row.
77001 **
77002 ** If P2==1 then no insert is performed.  argv[0] is the rowid of
77003 ** a row to delete.
77004 **
77005 ** P1 is a boolean flag. If it is set to true and the xUpdate call
77006 ** is successful, then the value returned by sqlite3_last_insert_rowid() 
77007 ** is set to the value of the rowid for the row just inserted.
77008 **
77009 ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
77010 ** apply in the case of a constraint failure on an insert or update.
77011 */
77012 case OP_VUpdate: {
77013   sqlite3_vtab *pVtab;
77014   const sqlite3_module *pModule;
77015   int nArg;
77016   int i;
77017   sqlite_int64 rowid;
77018   Mem **apArg;
77019   Mem *pX;
77020
77021   assert( pOp->p2==1        || pOp->p5==OE_Fail   || pOp->p5==OE_Rollback 
77022        || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
77023   );
77024   assert( p->readOnly==0 );
77025   pVtab = pOp->p4.pVtab->pVtab;
77026   if( pVtab==0 || NEVER(pVtab->pModule==0) ){
77027     rc = SQLITE_LOCKED;
77028     break;
77029   }
77030   pModule = pVtab->pModule;
77031   nArg = pOp->p2;
77032   assert( pOp->p4type==P4_VTAB );
77033   if( ALWAYS(pModule->xUpdate) ){
77034     u8 vtabOnConflict = db->vtabOnConflict;
77035     apArg = p->apArg;
77036     pX = &aMem[pOp->p3];
77037     for(i=0; i<nArg; i++){
77038       assert( memIsValid(pX) );
77039       memAboutToChange(p, pX);
77040       apArg[i] = pX;
77041       pX++;
77042     }
77043     db->vtabOnConflict = pOp->p5;
77044     rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
77045     db->vtabOnConflict = vtabOnConflict;
77046     sqlite3VtabImportErrmsg(p, pVtab);
77047     if( rc==SQLITE_OK && pOp->p1 ){
77048       assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
77049       db->lastRowid = lastRowid = rowid;
77050     }
77051     if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
77052       if( pOp->p5==OE_Ignore ){
77053         rc = SQLITE_OK;
77054       }else{
77055         p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
77056       }
77057     }else{
77058       p->nChange++;
77059     }
77060   }
77061   break;
77062 }
77063 #endif /* SQLITE_OMIT_VIRTUALTABLE */
77064
77065 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
77066 /* Opcode: Pagecount P1 P2 * * *
77067 **
77068 ** Write the current number of pages in database P1 to memory cell P2.
77069 */
77070 case OP_Pagecount: {            /* out2-prerelease */
77071   pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
77072   break;
77073 }
77074 #endif
77075
77076
77077 #ifndef  SQLITE_OMIT_PAGER_PRAGMAS
77078 /* Opcode: MaxPgcnt P1 P2 P3 * *
77079 **
77080 ** Try to set the maximum page count for database P1 to the value in P3.
77081 ** Do not let the maximum page count fall below the current page count and
77082 ** do not change the maximum page count value if P3==0.
77083 **
77084 ** Store the maximum page count after the change in register P2.
77085 */
77086 case OP_MaxPgcnt: {            /* out2-prerelease */
77087   unsigned int newMax;
77088   Btree *pBt;
77089
77090   pBt = db->aDb[pOp->p1].pBt;
77091   newMax = 0;
77092   if( pOp->p3 ){
77093     newMax = sqlite3BtreeLastPage(pBt);
77094     if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
77095   }
77096   pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
77097   break;
77098 }
77099 #endif
77100
77101
77102 /* Opcode: Init * P2 * P4 *
77103 ** Synopsis:  Start at P2
77104 **
77105 ** Programs contain a single instance of this opcode as the very first
77106 ** opcode.
77107 **
77108 ** If tracing is enabled (by the sqlite3_trace()) interface, then
77109 ** the UTF-8 string contained in P4 is emitted on the trace callback.
77110 ** Or if P4 is blank, use the string returned by sqlite3_sql().
77111 **
77112 ** If P2 is not zero, jump to instruction P2.
77113 */
77114 case OP_Init: {          /* jump */
77115   char *zTrace;
77116   char *z;
77117
77118   if( pOp->p2 ){
77119     pc = pOp->p2 - 1;
77120   }
77121 #ifndef SQLITE_OMIT_TRACE
77122   if( db->xTrace
77123    && !p->doingRerun
77124    && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
77125   ){
77126     z = sqlite3VdbeExpandSql(p, zTrace);
77127     db->xTrace(db->pTraceArg, z);
77128     sqlite3DbFree(db, z);
77129   }
77130 #ifdef SQLITE_USE_FCNTL_TRACE
77131   zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
77132   if( zTrace ){
77133     int i;
77134     for(i=0; i<db->nDb; i++){
77135       if( DbMaskTest(p->btreeMask, i)==0 ) continue;
77136       sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
77137     }
77138   }
77139 #endif /* SQLITE_USE_FCNTL_TRACE */
77140 #ifdef SQLITE_DEBUG
77141   if( (db->flags & SQLITE_SqlTrace)!=0
77142    && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
77143   ){
77144     sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
77145   }
77146 #endif /* SQLITE_DEBUG */
77147 #endif /* SQLITE_OMIT_TRACE */
77148   break;
77149 }
77150
77151
77152 /* Opcode: Noop * * * * *
77153 **
77154 ** Do nothing.  This instruction is often useful as a jump
77155 ** destination.
77156 */
77157 /*
77158 ** The magic Explain opcode are only inserted when explain==2 (which
77159 ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
77160 ** This opcode records information from the optimizer.  It is the
77161 ** the same as a no-op.  This opcodesnever appears in a real VM program.
77162 */
77163 default: {          /* This is really OP_Noop and OP_Explain */
77164   assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
77165   break;
77166 }
77167
77168 /*****************************************************************************
77169 ** The cases of the switch statement above this line should all be indented
77170 ** by 6 spaces.  But the left-most 6 spaces have been removed to improve the
77171 ** readability.  From this point on down, the normal indentation rules are
77172 ** restored.
77173 *****************************************************************************/
77174     }
77175
77176 #ifdef VDBE_PROFILE
77177     {
77178       u64 endTime = sqlite3Hwtime();
77179       if( endTime>start ) pOp->cycles += endTime - start;
77180       pOp->cnt++;
77181     }
77182 #endif
77183
77184     /* The following code adds nothing to the actual functionality
77185     ** of the program.  It is only here for testing and debugging.
77186     ** On the other hand, it does burn CPU cycles every time through
77187     ** the evaluator loop.  So we can leave it out when NDEBUG is defined.
77188     */
77189 #ifndef NDEBUG
77190     assert( pc>=-1 && pc<p->nOp );
77191
77192 #ifdef SQLITE_DEBUG
77193     if( db->flags & SQLITE_VdbeTrace ){
77194       if( rc!=0 ) printf("rc=%d\n",rc);
77195       if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
77196         registerTrace(pOp->p2, &aMem[pOp->p2]);
77197       }
77198       if( pOp->opflags & OPFLG_OUT3 ){
77199         registerTrace(pOp->p3, &aMem[pOp->p3]);
77200       }
77201     }
77202 #endif  /* SQLITE_DEBUG */
77203 #endif  /* NDEBUG */
77204   }  /* The end of the for(;;) loop the loops through opcodes */
77205
77206   /* If we reach this point, it means that execution is finished with
77207   ** an error of some kind.
77208   */
77209 vdbe_error_halt:
77210   assert( rc );
77211   p->rc = rc;
77212   testcase( sqlite3GlobalConfig.xLog!=0 );
77213   sqlite3_log(rc, "statement aborts at %d: [%s] %s", 
77214                    pc, p->zSql, p->zErrMsg);
77215   sqlite3VdbeHalt(p);
77216   if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
77217   rc = SQLITE_ERROR;
77218   if( resetSchemaOnFault>0 ){
77219     sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
77220   }
77221
77222   /* This is the only way out of this procedure.  We have to
77223   ** release the mutexes on btrees that were acquired at the
77224   ** top. */
77225 vdbe_return:
77226   db->lastRowid = lastRowid;
77227   testcase( nVmStep>0 );
77228   p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
77229   sqlite3VdbeLeave(p);
77230   return rc;
77231
77232   /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
77233   ** is encountered.
77234   */
77235 too_big:
77236   sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
77237   rc = SQLITE_TOOBIG;
77238   goto vdbe_error_halt;
77239
77240   /* Jump to here if a malloc() fails.
77241   */
77242 no_mem:
77243   db->mallocFailed = 1;
77244   sqlite3SetString(&p->zErrMsg, db, "out of memory");
77245   rc = SQLITE_NOMEM;
77246   goto vdbe_error_halt;
77247
77248   /* Jump to here for any other kind of fatal error.  The "rc" variable
77249   ** should hold the error number.
77250   */
77251 abort_due_to_error:
77252   assert( p->zErrMsg==0 );
77253   if( db->mallocFailed ) rc = SQLITE_NOMEM;
77254   if( rc!=SQLITE_IOERR_NOMEM ){
77255     sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
77256   }
77257   goto vdbe_error_halt;
77258
77259   /* Jump to here if the sqlite3_interrupt() API sets the interrupt
77260   ** flag.
77261   */
77262 abort_due_to_interrupt:
77263   assert( db->u1.isInterrupted );
77264   rc = SQLITE_INTERRUPT;
77265   p->rc = rc;
77266   sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
77267   goto vdbe_error_halt;
77268 }
77269
77270
77271 /************** End of vdbe.c ************************************************/
77272 /************** Begin file vdbeblob.c ****************************************/
77273 /*
77274 ** 2007 May 1
77275 **
77276 ** The author disclaims copyright to this source code.  In place of
77277 ** a legal notice, here is a blessing:
77278 **
77279 **    May you do good and not evil.
77280 **    May you find forgiveness for yourself and forgive others.
77281 **    May you share freely, never taking more than you give.
77282 **
77283 *************************************************************************
77284 **
77285 ** This file contains code used to implement incremental BLOB I/O.
77286 */
77287
77288
77289 #ifndef SQLITE_OMIT_INCRBLOB
77290
77291 /*
77292 ** Valid sqlite3_blob* handles point to Incrblob structures.
77293 */
77294 typedef struct Incrblob Incrblob;
77295 struct Incrblob {
77296   int flags;              /* Copy of "flags" passed to sqlite3_blob_open() */
77297   int nByte;              /* Size of open blob, in bytes */
77298   int iOffset;            /* Byte offset of blob in cursor data */
77299   int iCol;               /* Table column this handle is open on */
77300   BtCursor *pCsr;         /* Cursor pointing at blob row */
77301   sqlite3_stmt *pStmt;    /* Statement holding cursor open */
77302   sqlite3 *db;            /* The associated database */
77303 };
77304
77305
77306 /*
77307 ** This function is used by both blob_open() and blob_reopen(). It seeks
77308 ** the b-tree cursor associated with blob handle p to point to row iRow.
77309 ** If successful, SQLITE_OK is returned and subsequent calls to
77310 ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
77311 **
77312 ** If an error occurs, or if the specified row does not exist or does not
77313 ** contain a value of type TEXT or BLOB in the column nominated when the
77314 ** blob handle was opened, then an error code is returned and *pzErr may
77315 ** be set to point to a buffer containing an error message. It is the
77316 ** responsibility of the caller to free the error message buffer using
77317 ** sqlite3DbFree().
77318 **
77319 ** If an error does occur, then the b-tree cursor is closed. All subsequent
77320 ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will 
77321 ** immediately return SQLITE_ABORT.
77322 */
77323 static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
77324   int rc;                         /* Error code */
77325   char *zErr = 0;                 /* Error message */
77326   Vdbe *v = (Vdbe *)p->pStmt;
77327
77328   /* Set the value of the SQL statements only variable to integer iRow. 
77329   ** This is done directly instead of using sqlite3_bind_int64() to avoid 
77330   ** triggering asserts related to mutexes.
77331   */
77332   assert( v->aVar[0].flags&MEM_Int );
77333   v->aVar[0].u.i = iRow;
77334
77335   rc = sqlite3_step(p->pStmt);
77336   if( rc==SQLITE_ROW ){
77337     VdbeCursor *pC = v->apCsr[0];
77338     u32 type = pC->aType[p->iCol];
77339     if( type<12 ){
77340       zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
77341           type==0?"null": type==7?"real": "integer"
77342       );
77343       rc = SQLITE_ERROR;
77344       sqlite3_finalize(p->pStmt);
77345       p->pStmt = 0;
77346     }else{
77347       p->iOffset = pC->aType[p->iCol + pC->nField];
77348       p->nByte = sqlite3VdbeSerialTypeLen(type);
77349       p->pCsr =  pC->pCursor;
77350       sqlite3BtreeIncrblobCursor(p->pCsr);
77351     }
77352   }
77353
77354   if( rc==SQLITE_ROW ){
77355     rc = SQLITE_OK;
77356   }else if( p->pStmt ){
77357     rc = sqlite3_finalize(p->pStmt);
77358     p->pStmt = 0;
77359     if( rc==SQLITE_OK ){
77360       zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
77361       rc = SQLITE_ERROR;
77362     }else{
77363       zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
77364     }
77365   }
77366
77367   assert( rc!=SQLITE_OK || zErr==0 );
77368   assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
77369
77370   *pzErr = zErr;
77371   return rc;
77372 }
77373
77374 /*
77375 ** Open a blob handle.
77376 */
77377 SQLITE_API int SQLITE_STDCALL sqlite3_blob_open(
77378   sqlite3* db,            /* The database connection */
77379   const char *zDb,        /* The attached database containing the blob */
77380   const char *zTable,     /* The table containing the blob */
77381   const char *zColumn,    /* The column containing the blob */
77382   sqlite_int64 iRow,      /* The row containing the glob */
77383   int flags,              /* True -> read/write access, false -> read-only */
77384   sqlite3_blob **ppBlob   /* Handle for accessing the blob returned here */
77385 ){
77386   int nAttempt = 0;
77387   int iCol;               /* Index of zColumn in row-record */
77388
77389   /* This VDBE program seeks a btree cursor to the identified 
77390   ** db/table/row entry. The reason for using a vdbe program instead
77391   ** of writing code to use the b-tree layer directly is that the
77392   ** vdbe program will take advantage of the various transaction,
77393   ** locking and error handling infrastructure built into the vdbe.
77394   **
77395   ** After seeking the cursor, the vdbe executes an OP_ResultRow.
77396   ** Code external to the Vdbe then "borrows" the b-tree cursor and
77397   ** uses it to implement the blob_read(), blob_write() and 
77398   ** blob_bytes() functions.
77399   **
77400   ** The sqlite3_blob_close() function finalizes the vdbe program,
77401   ** which closes the b-tree cursor and (possibly) commits the 
77402   ** transaction.
77403   */
77404   static const int iLn = VDBE_OFFSET_LINENO(4);
77405   static const VdbeOpList openBlob[] = {
77406     /* {OP_Transaction, 0, 0, 0},  // 0: Inserted separately */
77407     {OP_TableLock, 0, 0, 0},       /* 1: Acquire a read or write lock */
77408     /* One of the following two instructions is replaced by an OP_Noop. */
77409     {OP_OpenRead, 0, 0, 0},        /* 2: Open cursor 0 for reading */
77410     {OP_OpenWrite, 0, 0, 0},       /* 3: Open cursor 0 for read/write */
77411     {OP_Variable, 1, 1, 1},        /* 4: Push the rowid to the stack */
77412     {OP_NotExists, 0, 10, 1},      /* 5: Seek the cursor */
77413     {OP_Column, 0, 0, 1},          /* 6  */
77414     {OP_ResultRow, 1, 0, 0},       /* 7  */
77415     {OP_Goto, 0, 4, 0},            /* 8  */
77416     {OP_Close, 0, 0, 0},           /* 9  */
77417     {OP_Halt, 0, 0, 0},            /* 10 */
77418   };
77419
77420   int rc = SQLITE_OK;
77421   char *zErr = 0;
77422   Table *pTab;
77423   Parse *pParse = 0;
77424   Incrblob *pBlob = 0;
77425
77426 #ifdef SQLITE_ENABLE_API_ARMOR
77427   if( ppBlob==0 ){
77428     return SQLITE_MISUSE_BKPT;
77429   }
77430 #endif
77431   *ppBlob = 0;
77432 #ifdef SQLITE_ENABLE_API_ARMOR
77433   if( !sqlite3SafetyCheckOk(db) || zTable==0 ){
77434     return SQLITE_MISUSE_BKPT;
77435   }
77436 #endif
77437   flags = !!flags;                /* flags = (flags ? 1 : 0); */
77438
77439   sqlite3_mutex_enter(db->mutex);
77440
77441   pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
77442   if( !pBlob ) goto blob_open_out;
77443   pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
77444   if( !pParse ) goto blob_open_out;
77445
77446   do {
77447     memset(pParse, 0, sizeof(Parse));
77448     pParse->db = db;
77449     sqlite3DbFree(db, zErr);
77450     zErr = 0;
77451
77452     sqlite3BtreeEnterAll(db);
77453     pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
77454     if( pTab && IsVirtual(pTab) ){
77455       pTab = 0;
77456       sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
77457     }
77458     if( pTab && !HasRowid(pTab) ){
77459       pTab = 0;
77460       sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
77461     }
77462 #ifndef SQLITE_OMIT_VIEW
77463     if( pTab && pTab->pSelect ){
77464       pTab = 0;
77465       sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
77466     }
77467 #endif
77468     if( !pTab ){
77469       if( pParse->zErrMsg ){
77470         sqlite3DbFree(db, zErr);
77471         zErr = pParse->zErrMsg;
77472         pParse->zErrMsg = 0;
77473       }
77474       rc = SQLITE_ERROR;
77475       sqlite3BtreeLeaveAll(db);
77476       goto blob_open_out;
77477     }
77478
77479     /* Now search pTab for the exact column. */
77480     for(iCol=0; iCol<pTab->nCol; iCol++) {
77481       if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
77482         break;
77483       }
77484     }
77485     if( iCol==pTab->nCol ){
77486       sqlite3DbFree(db, zErr);
77487       zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
77488       rc = SQLITE_ERROR;
77489       sqlite3BtreeLeaveAll(db);
77490       goto blob_open_out;
77491     }
77492
77493     /* If the value is being opened for writing, check that the
77494     ** column is not indexed, and that it is not part of a foreign key. 
77495     ** It is against the rules to open a column to which either of these
77496     ** descriptions applies for writing.  */
77497     if( flags ){
77498       const char *zFault = 0;
77499       Index *pIdx;
77500 #ifndef SQLITE_OMIT_FOREIGN_KEY
77501       if( db->flags&SQLITE_ForeignKeys ){
77502         /* Check that the column is not part of an FK child key definition. It
77503         ** is not necessary to check if it is part of a parent key, as parent
77504         ** key columns must be indexed. The check below will pick up this 
77505         ** case.  */
77506         FKey *pFKey;
77507         for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
77508           int j;
77509           for(j=0; j<pFKey->nCol; j++){
77510             if( pFKey->aCol[j].iFrom==iCol ){
77511               zFault = "foreign key";
77512             }
77513           }
77514         }
77515       }
77516 #endif
77517       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
77518         int j;
77519         for(j=0; j<pIdx->nKeyCol; j++){
77520           if( pIdx->aiColumn[j]==iCol ){
77521             zFault = "indexed";
77522           }
77523         }
77524       }
77525       if( zFault ){
77526         sqlite3DbFree(db, zErr);
77527         zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
77528         rc = SQLITE_ERROR;
77529         sqlite3BtreeLeaveAll(db);
77530         goto blob_open_out;
77531       }
77532     }
77533
77534     pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
77535     assert( pBlob->pStmt || db->mallocFailed );
77536     if( pBlob->pStmt ){
77537       Vdbe *v = (Vdbe *)pBlob->pStmt;
77538       int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
77539
77540
77541       sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags, 
77542                            pTab->pSchema->schema_cookie,
77543                            pTab->pSchema->iGeneration);
77544       sqlite3VdbeChangeP5(v, 1);     
77545       sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
77546
77547       /* Make sure a mutex is held on the table to be accessed */
77548       sqlite3VdbeUsesBtree(v, iDb); 
77549
77550       /* Configure the OP_TableLock instruction */
77551 #ifdef SQLITE_OMIT_SHARED_CACHE
77552       sqlite3VdbeChangeToNoop(v, 1);
77553 #else
77554       sqlite3VdbeChangeP1(v, 1, iDb);
77555       sqlite3VdbeChangeP2(v, 1, pTab->tnum);
77556       sqlite3VdbeChangeP3(v, 1, flags);
77557       sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
77558 #endif
77559
77560       /* Remove either the OP_OpenWrite or OpenRead. Set the P2 
77561       ** parameter of the other to pTab->tnum.  */
77562       sqlite3VdbeChangeToNoop(v, 3 - flags);
77563       sqlite3VdbeChangeP2(v, 2 + flags, pTab->tnum);
77564       sqlite3VdbeChangeP3(v, 2 + flags, iDb);
77565
77566       /* Configure the number of columns. Configure the cursor to
77567       ** think that the table has one more column than it really
77568       ** does. An OP_Column to retrieve this imaginary column will
77569       ** always return an SQL NULL. This is useful because it means
77570       ** we can invoke OP_Column to fill in the vdbe cursors type 
77571       ** and offset cache without causing any IO.
77572       */
77573       sqlite3VdbeChangeP4(v, 2+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
77574       sqlite3VdbeChangeP2(v, 6, pTab->nCol);
77575       if( !db->mallocFailed ){
77576         pParse->nVar = 1;
77577         pParse->nMem = 1;
77578         pParse->nTab = 1;
77579         sqlite3VdbeMakeReady(v, pParse);
77580       }
77581     }
77582    
77583     pBlob->flags = flags;
77584     pBlob->iCol = iCol;
77585     pBlob->db = db;
77586     sqlite3BtreeLeaveAll(db);
77587     if( db->mallocFailed ){
77588       goto blob_open_out;
77589     }
77590     sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
77591     rc = blobSeekToRow(pBlob, iRow, &zErr);
77592   } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
77593
77594 blob_open_out:
77595   if( rc==SQLITE_OK && db->mallocFailed==0 ){
77596     *ppBlob = (sqlite3_blob *)pBlob;
77597   }else{
77598     if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
77599     sqlite3DbFree(db, pBlob);
77600   }
77601   sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
77602   sqlite3DbFree(db, zErr);
77603   sqlite3ParserReset(pParse);
77604   sqlite3StackFree(db, pParse);
77605   rc = sqlite3ApiExit(db, rc);
77606   sqlite3_mutex_leave(db->mutex);
77607   return rc;
77608 }
77609
77610 /*
77611 ** Close a blob handle that was previously created using
77612 ** sqlite3_blob_open().
77613 */
77614 SQLITE_API int SQLITE_STDCALL sqlite3_blob_close(sqlite3_blob *pBlob){
77615   Incrblob *p = (Incrblob *)pBlob;
77616   int rc;
77617   sqlite3 *db;
77618
77619   if( p ){
77620     db = p->db;
77621     sqlite3_mutex_enter(db->mutex);
77622     rc = sqlite3_finalize(p->pStmt);
77623     sqlite3DbFree(db, p);
77624     sqlite3_mutex_leave(db->mutex);
77625   }else{
77626     rc = SQLITE_OK;
77627   }
77628   return rc;
77629 }
77630
77631 /*
77632 ** Perform a read or write operation on a blob
77633 */
77634 static int blobReadWrite(
77635   sqlite3_blob *pBlob, 
77636   void *z, 
77637   int n, 
77638   int iOffset, 
77639   int (*xCall)(BtCursor*, u32, u32, void*)
77640 ){
77641   int rc;
77642   Incrblob *p = (Incrblob *)pBlob;
77643   Vdbe *v;
77644   sqlite3 *db;
77645
77646   if( p==0 ) return SQLITE_MISUSE_BKPT;
77647   db = p->db;
77648   sqlite3_mutex_enter(db->mutex);
77649   v = (Vdbe*)p->pStmt;
77650
77651   if( n<0 || iOffset<0 || ((sqlite3_int64)iOffset+n)>p->nByte ){
77652     /* Request is out of range. Return a transient error. */
77653     rc = SQLITE_ERROR;
77654   }else if( v==0 ){
77655     /* If there is no statement handle, then the blob-handle has
77656     ** already been invalidated. Return SQLITE_ABORT in this case.
77657     */
77658     rc = SQLITE_ABORT;
77659   }else{
77660     /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
77661     ** returned, clean-up the statement handle.
77662     */
77663     assert( db == v->db );
77664     sqlite3BtreeEnterCursor(p->pCsr);
77665     rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
77666     sqlite3BtreeLeaveCursor(p->pCsr);
77667     if( rc==SQLITE_ABORT ){
77668       sqlite3VdbeFinalize(v);
77669       p->pStmt = 0;
77670     }else{
77671       v->rc = rc;
77672     }
77673   }
77674   sqlite3Error(db, rc);
77675   rc = sqlite3ApiExit(db, rc);
77676   sqlite3_mutex_leave(db->mutex);
77677   return rc;
77678 }
77679
77680 /*
77681 ** Read data from a blob handle.
77682 */
77683 SQLITE_API int SQLITE_STDCALL sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
77684   return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
77685 }
77686
77687 /*
77688 ** Write data to a blob handle.
77689 */
77690 SQLITE_API int SQLITE_STDCALL sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
77691   return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
77692 }
77693
77694 /*
77695 ** Query a blob handle for the size of the data.
77696 **
77697 ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
77698 ** so no mutex is required for access.
77699 */
77700 SQLITE_API int SQLITE_STDCALL sqlite3_blob_bytes(sqlite3_blob *pBlob){
77701   Incrblob *p = (Incrblob *)pBlob;
77702   return (p && p->pStmt) ? p->nByte : 0;
77703 }
77704
77705 /*
77706 ** Move an existing blob handle to point to a different row of the same
77707 ** database table.
77708 **
77709 ** If an error occurs, or if the specified row does not exist or does not
77710 ** contain a blob or text value, then an error code is returned and the
77711 ** database handle error code and message set. If this happens, then all 
77712 ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close()) 
77713 ** immediately return SQLITE_ABORT.
77714 */
77715 SQLITE_API int SQLITE_STDCALL sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
77716   int rc;
77717   Incrblob *p = (Incrblob *)pBlob;
77718   sqlite3 *db;
77719
77720   if( p==0 ) return SQLITE_MISUSE_BKPT;
77721   db = p->db;
77722   sqlite3_mutex_enter(db->mutex);
77723
77724   if( p->pStmt==0 ){
77725     /* If there is no statement handle, then the blob-handle has
77726     ** already been invalidated. Return SQLITE_ABORT in this case.
77727     */
77728     rc = SQLITE_ABORT;
77729   }else{
77730     char *zErr;
77731     rc = blobSeekToRow(p, iRow, &zErr);
77732     if( rc!=SQLITE_OK ){
77733       sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
77734       sqlite3DbFree(db, zErr);
77735     }
77736     assert( rc!=SQLITE_SCHEMA );
77737   }
77738
77739   rc = sqlite3ApiExit(db, rc);
77740   assert( rc==SQLITE_OK || p->pStmt==0 );
77741   sqlite3_mutex_leave(db->mutex);
77742   return rc;
77743 }
77744
77745 #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
77746
77747 /************** End of vdbeblob.c ********************************************/
77748 /************** Begin file vdbesort.c ****************************************/
77749 /*
77750 ** 2011-07-09
77751 **
77752 ** The author disclaims copyright to this source code.  In place of
77753 ** a legal notice, here is a blessing:
77754 **
77755 **    May you do good and not evil.
77756 **    May you find forgiveness for yourself and forgive others.
77757 **    May you share freely, never taking more than you give.
77758 **
77759 *************************************************************************
77760 ** This file contains code for the VdbeSorter object, used in concert with
77761 ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
77762 ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
77763 ** using indexes and without LIMIT clauses.
77764 **
77765 ** The VdbeSorter object implements a multi-threaded external merge sort
77766 ** algorithm that is efficient even if the number of elements being sorted
77767 ** exceeds the available memory.
77768 **
77769 ** Here is the (internal, non-API) interface between this module and the
77770 ** rest of the SQLite system:
77771 **
77772 **    sqlite3VdbeSorterInit()       Create a new VdbeSorter object.
77773 **
77774 **    sqlite3VdbeSorterWrite()      Add a single new row to the VdbeSorter
77775 **                                  object.  The row is a binary blob in the
77776 **                                  OP_MakeRecord format that contains both
77777 **                                  the ORDER BY key columns and result columns
77778 **                                  in the case of a SELECT w/ ORDER BY, or
77779 **                                  the complete record for an index entry
77780 **                                  in the case of a CREATE INDEX.
77781 **
77782 **    sqlite3VdbeSorterRewind()     Sort all content previously added.
77783 **                                  Position the read cursor on the
77784 **                                  first sorted element.
77785 **
77786 **    sqlite3VdbeSorterNext()       Advance the read cursor to the next sorted
77787 **                                  element.
77788 **
77789 **    sqlite3VdbeSorterRowkey()     Return the complete binary blob for the
77790 **                                  row currently under the read cursor.
77791 **
77792 **    sqlite3VdbeSorterCompare()    Compare the binary blob for the row
77793 **                                  currently under the read cursor against
77794 **                                  another binary blob X and report if
77795 **                                  X is strictly less than the read cursor.
77796 **                                  Used to enforce uniqueness in a
77797 **                                  CREATE UNIQUE INDEX statement.
77798 **
77799 **    sqlite3VdbeSorterClose()      Close the VdbeSorter object and reclaim
77800 **                                  all resources.
77801 **
77802 **    sqlite3VdbeSorterReset()      Refurbish the VdbeSorter for reuse.  This
77803 **                                  is like Close() followed by Init() only
77804 **                                  much faster.
77805 **
77806 ** The interfaces above must be called in a particular order.  Write() can 
77807 ** only occur in between Init()/Reset() and Rewind().  Next(), Rowkey(), and
77808 ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
77809 **
77810 **   Init()
77811 **   for each record: Write()
77812 **   Rewind()
77813 **     Rowkey()/Compare()
77814 **   Next() 
77815 **   Close()
77816 **
77817 ** Algorithm:
77818 **
77819 ** Records passed to the sorter via calls to Write() are initially held 
77820 ** unsorted in main memory. Assuming the amount of memory used never exceeds
77821 ** a threshold, when Rewind() is called the set of records is sorted using
77822 ** an in-memory merge sort. In this case, no temporary files are required
77823 ** and subsequent calls to Rowkey(), Next() and Compare() read records 
77824 ** directly from main memory.
77825 **
77826 ** If the amount of space used to store records in main memory exceeds the
77827 ** threshold, then the set of records currently in memory are sorted and
77828 ** written to a temporary file in "Packed Memory Array" (PMA) format.
77829 ** A PMA created at this point is known as a "level-0 PMA". Higher levels
77830 ** of PMAs may be created by merging existing PMAs together - for example
77831 ** merging two or more level-0 PMAs together creates a level-1 PMA.
77832 **
77833 ** The threshold for the amount of main memory to use before flushing 
77834 ** records to a PMA is roughly the same as the limit configured for the
77835 ** page-cache of the main database. Specifically, the threshold is set to 
77836 ** the value returned by "PRAGMA main.page_size" multipled by 
77837 ** that returned by "PRAGMA main.cache_size", in bytes.
77838 **
77839 ** If the sorter is running in single-threaded mode, then all PMAs generated
77840 ** are appended to a single temporary file. Or, if the sorter is running in
77841 ** multi-threaded mode then up to (N+1) temporary files may be opened, where
77842 ** N is the configured number of worker threads. In this case, instead of
77843 ** sorting the records and writing the PMA to a temporary file itself, the
77844 ** calling thread usually launches a worker thread to do so. Except, if
77845 ** there are already N worker threads running, the main thread does the work
77846 ** itself.
77847 **
77848 ** The sorter is running in multi-threaded mode if (a) the library was built
77849 ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
77850 ** than zero, and (b) worker threads have been enabled at runtime by calling
77851 ** "PRAGMA threads=N" with some value of N greater than 0.
77852 **
77853 ** When Rewind() is called, any data remaining in memory is flushed to a 
77854 ** final PMA. So at this point the data is stored in some number of sorted
77855 ** PMAs within temporary files on disk.
77856 **
77857 ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
77858 ** sorter is running in single-threaded mode, then these PMAs are merged
77859 ** incrementally as keys are retreived from the sorter by the VDBE.  The
77860 ** MergeEngine object, described in further detail below, performs this
77861 ** merge.
77862 **
77863 ** Or, if running in multi-threaded mode, then a background thread is
77864 ** launched to merge the existing PMAs. Once the background thread has
77865 ** merged T bytes of data into a single sorted PMA, the main thread 
77866 ** begins reading keys from that PMA while the background thread proceeds
77867 ** with merging the next T bytes of data. And so on.
77868 **
77869 ** Parameter T is set to half the value of the memory threshold used 
77870 ** by Write() above to determine when to create a new PMA.
77871 **
77872 ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when 
77873 ** Rewind() is called, then a hierarchy of incremental-merges is used. 
77874 ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on 
77875 ** disk are merged together. Then T bytes of data from the second set, and
77876 ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
77877 ** PMAs at a time. This done is to improve locality.
77878 **
77879 ** If running in multi-threaded mode and there are more than
77880 ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
77881 ** than one background thread may be created. Specifically, there may be
77882 ** one background thread for each temporary file on disk, and one background
77883 ** thread to merge the output of each of the others to a single PMA for
77884 ** the main thread to read from.
77885 */
77886
77887 /* 
77888 ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
77889 ** messages to stderr that may be helpful in understanding the performance
77890 ** characteristics of the sorter in multi-threaded mode.
77891 */
77892 #if 0
77893 # define SQLITE_DEBUG_SORTER_THREADS 1
77894 #endif
77895
77896 /*
77897 ** Hard-coded maximum amount of data to accumulate in memory before flushing
77898 ** to a level 0 PMA. The purpose of this limit is to prevent various integer
77899 ** overflows. 512MiB.
77900 */
77901 #define SQLITE_MAX_PMASZ    (1<<29)
77902
77903 /*
77904 ** Private objects used by the sorter
77905 */
77906 typedef struct MergeEngine MergeEngine;     /* Merge PMAs together */
77907 typedef struct PmaReader PmaReader;         /* Incrementally read one PMA */
77908 typedef struct PmaWriter PmaWriter;         /* Incrementally write one PMA */
77909 typedef struct SorterRecord SorterRecord;   /* A record being sorted */
77910 typedef struct SortSubtask SortSubtask;     /* A sub-task in the sort process */
77911 typedef struct SorterFile SorterFile;       /* Temporary file object wrapper */
77912 typedef struct SorterList SorterList;       /* In-memory list of records */
77913 typedef struct IncrMerger IncrMerger;       /* Read & merge multiple PMAs */
77914
77915 /*
77916 ** A container for a temp file handle and the current amount of data 
77917 ** stored in the file.
77918 */
77919 struct SorterFile {
77920   sqlite3_file *pFd;              /* File handle */
77921   i64 iEof;                       /* Bytes of data stored in pFd */
77922 };
77923
77924 /*
77925 ** An in-memory list of objects to be sorted.
77926 **
77927 ** If aMemory==0 then each object is allocated separately and the objects
77928 ** are connected using SorterRecord.u.pNext.  If aMemory!=0 then all objects
77929 ** are stored in the aMemory[] bulk memory, one right after the other, and
77930 ** are connected using SorterRecord.u.iNext.
77931 */
77932 struct SorterList {
77933   SorterRecord *pList;            /* Linked list of records */
77934   u8 *aMemory;                    /* If non-NULL, bulk memory to hold pList */
77935   int szPMA;                      /* Size of pList as PMA in bytes */
77936 };
77937
77938 /*
77939 ** The MergeEngine object is used to combine two or more smaller PMAs into
77940 ** one big PMA using a merge operation.  Separate PMAs all need to be
77941 ** combined into one big PMA in order to be able to step through the sorted
77942 ** records in order.
77943 **
77944 ** The aReadr[] array contains a PmaReader object for each of the PMAs being
77945 ** merged.  An aReadr[] object either points to a valid key or else is at EOF.
77946 ** ("EOF" means "End Of File".  When aReadr[] is at EOF there is no more data.)
77947 ** For the purposes of the paragraphs below, we assume that the array is
77948 ** actually N elements in size, where N is the smallest power of 2 greater
77949 ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
77950 ** are treated as if they are empty (always at EOF).
77951 **
77952 ** The aTree[] array is also N elements in size. The value of N is stored in
77953 ** the MergeEngine.nTree variable.
77954 **
77955 ** The final (N/2) elements of aTree[] contain the results of comparing
77956 ** pairs of PMA keys together. Element i contains the result of 
77957 ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
77958 ** aTree element is set to the index of it. 
77959 **
77960 ** For the purposes of this comparison, EOF is considered greater than any
77961 ** other key value. If the keys are equal (only possible with two EOF
77962 ** values), it doesn't matter which index is stored.
77963 **
77964 ** The (N/4) elements of aTree[] that precede the final (N/2) described 
77965 ** above contains the index of the smallest of each block of 4 PmaReaders
77966 ** And so on. So that aTree[1] contains the index of the PmaReader that 
77967 ** currently points to the smallest key value. aTree[0] is unused.
77968 **
77969 ** Example:
77970 **
77971 **     aReadr[0] -> Banana
77972 **     aReadr[1] -> Feijoa
77973 **     aReadr[2] -> Elderberry
77974 **     aReadr[3] -> Currant
77975 **     aReadr[4] -> Grapefruit
77976 **     aReadr[5] -> Apple
77977 **     aReadr[6] -> Durian
77978 **     aReadr[7] -> EOF
77979 **
77980 **     aTree[] = { X, 5   0, 5    0, 3, 5, 6 }
77981 **
77982 ** The current element is "Apple" (the value of the key indicated by 
77983 ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
77984 ** be advanced to the next key in its segment. Say the next key is
77985 ** "Eggplant":
77986 **
77987 **     aReadr[5] -> Eggplant
77988 **
77989 ** The contents of aTree[] are updated first by comparing the new PmaReader
77990 ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
77991 ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
77992 ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
77993 ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
77994 ** so the value written into element 1 of the array is 0. As follows:
77995 **
77996 **     aTree[] = { X, 0   0, 6    0, 3, 5, 6 }
77997 **
77998 ** In other words, each time we advance to the next sorter element, log2(N)
77999 ** key comparison operations are required, where N is the number of segments
78000 ** being merged (rounded up to the next power of 2).
78001 */
78002 struct MergeEngine {
78003   int nTree;                 /* Used size of aTree/aReadr (power of 2) */
78004   SortSubtask *pTask;        /* Used by this thread only */
78005   int *aTree;                /* Current state of incremental merge */
78006   PmaReader *aReadr;         /* Array of PmaReaders to merge data from */
78007 };
78008
78009 /*
78010 ** This object represents a single thread of control in a sort operation.
78011 ** Exactly VdbeSorter.nTask instances of this object are allocated
78012 ** as part of each VdbeSorter object. Instances are never allocated any
78013 ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
78014 ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread).  Thus for
78015 ** single-threaded operation, there is exactly one instance of this object
78016 ** and for multi-threaded operation there are two or more instances.
78017 **
78018 ** Essentially, this structure contains all those fields of the VdbeSorter
78019 ** structure for which each thread requires a separate instance. For example,
78020 ** each thread requries its own UnpackedRecord object to unpack records in
78021 ** as part of comparison operations.
78022 **
78023 ** Before a background thread is launched, variable bDone is set to 0. Then, 
78024 ** right before it exits, the thread itself sets bDone to 1. This is used for 
78025 ** two purposes:
78026 **
78027 **   1. When flushing the contents of memory to a level-0 PMA on disk, to
78028 **      attempt to select a SortSubtask for which there is not already an
78029 **      active background thread (since doing so causes the main thread
78030 **      to block until it finishes).
78031 **
78032 **   2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
78033 **      to sqlite3ThreadJoin() is likely to block. Cases that are likely to
78034 **      block provoke debugging output.
78035 **
78036 ** In both cases, the effects of the main thread seeing (bDone==0) even
78037 ** after the thread has finished are not dire. So we don't worry about
78038 ** memory barriers and such here.
78039 */
78040 struct SortSubtask {
78041   SQLiteThread *pThread;          /* Background thread, if any */
78042   int bDone;                      /* Set if thread is finished but not joined */
78043   VdbeSorter *pSorter;            /* Sorter that owns this sub-task */
78044   UnpackedRecord *pUnpacked;      /* Space to unpack a record */
78045   SorterList list;                /* List for thread to write to a PMA */
78046   int nPMA;                       /* Number of PMAs currently in file */
78047   SorterFile file;                /* Temp file for level-0 PMAs */
78048   SorterFile file2;               /* Space for other PMAs */
78049 };
78050
78051 /*
78052 ** Main sorter structure. A single instance of this is allocated for each 
78053 ** sorter cursor created by the VDBE.
78054 **
78055 ** mxKeysize:
78056 **   As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
78057 **   this variable is updated so as to be set to the size on disk of the
78058 **   largest record in the sorter.
78059 */
78060 struct VdbeSorter {
78061   int mnPmaSize;                  /* Minimum PMA size, in bytes */
78062   int mxPmaSize;                  /* Maximum PMA size, in bytes.  0==no limit */
78063   int mxKeysize;                  /* Largest serialized key seen so far */
78064   int pgsz;                       /* Main database page size */
78065   PmaReader *pReader;             /* Readr data from here after Rewind() */
78066   MergeEngine *pMerger;           /* Or here, if bUseThreads==0 */
78067   sqlite3 *db;                    /* Database connection */
78068   KeyInfo *pKeyInfo;              /* How to compare records */
78069   UnpackedRecord *pUnpacked;      /* Used by VdbeSorterCompare() */
78070   SorterList list;                /* List of in-memory records */
78071   int iMemory;                    /* Offset of free space in list.aMemory */
78072   int nMemory;                    /* Size of list.aMemory allocation in bytes */
78073   u8 bUsePMA;                     /* True if one or more PMAs created */
78074   u8 bUseThreads;                 /* True to use background threads */
78075   u8 iPrev;                       /* Previous thread used to flush PMA */
78076   u8 nTask;                       /* Size of aTask[] array */
78077   SortSubtask aTask[1];           /* One or more subtasks */
78078 };
78079
78080 /*
78081 ** An instance of the following object is used to read records out of a
78082 ** PMA, in sorted order.  The next key to be read is cached in nKey/aKey.
78083 ** aKey might point into aMap or into aBuffer.  If neither of those locations
78084 ** contain a contiguous representation of the key, then aAlloc is allocated
78085 ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
78086 **
78087 ** pFd==0 at EOF.
78088 */
78089 struct PmaReader {
78090   i64 iReadOff;               /* Current read offset */
78091   i64 iEof;                   /* 1 byte past EOF for this PmaReader */
78092   int nAlloc;                 /* Bytes of space at aAlloc */
78093   int nKey;                   /* Number of bytes in key */
78094   sqlite3_file *pFd;          /* File handle we are reading from */
78095   u8 *aAlloc;                 /* Space for aKey if aBuffer and pMap wont work */
78096   u8 *aKey;                   /* Pointer to current key */
78097   u8 *aBuffer;                /* Current read buffer */
78098   int nBuffer;                /* Size of read buffer in bytes */
78099   u8 *aMap;                   /* Pointer to mapping of entire file */
78100   IncrMerger *pIncr;          /* Incremental merger */
78101 };
78102
78103 /*
78104 ** Normally, a PmaReader object iterates through an existing PMA stored 
78105 ** within a temp file. However, if the PmaReader.pIncr variable points to
78106 ** an object of the following type, it may be used to iterate/merge through
78107 ** multiple PMAs simultaneously.
78108 **
78109 ** There are two types of IncrMerger object - single (bUseThread==0) and 
78110 ** multi-threaded (bUseThread==1). 
78111 **
78112 ** A multi-threaded IncrMerger object uses two temporary files - aFile[0] 
78113 ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in 
78114 ** size. When the IncrMerger is initialized, it reads enough data from 
78115 ** pMerger to populate aFile[0]. It then sets variables within the 
78116 ** corresponding PmaReader object to read from that file and kicks off 
78117 ** a background thread to populate aFile[1] with the next mxSz bytes of 
78118 ** sorted record data from pMerger. 
78119 **
78120 ** When the PmaReader reaches the end of aFile[0], it blocks until the
78121 ** background thread has finished populating aFile[1]. It then exchanges
78122 ** the contents of the aFile[0] and aFile[1] variables within this structure,
78123 ** sets the PmaReader fields to read from the new aFile[0] and kicks off
78124 ** another background thread to populate the new aFile[1]. And so on, until
78125 ** the contents of pMerger are exhausted.
78126 **
78127 ** A single-threaded IncrMerger does not open any temporary files of its
78128 ** own. Instead, it has exclusive access to mxSz bytes of space beginning
78129 ** at offset iStartOff of file pTask->file2. And instead of using a 
78130 ** background thread to prepare data for the PmaReader, with a single
78131 ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
78132 ** keys from pMerger by the calling thread whenever the PmaReader runs out
78133 ** of data.
78134 */
78135 struct IncrMerger {
78136   SortSubtask *pTask;             /* Task that owns this merger */
78137   MergeEngine *pMerger;           /* Merge engine thread reads data from */
78138   i64 iStartOff;                  /* Offset to start writing file at */
78139   int mxSz;                       /* Maximum bytes of data to store */
78140   int bEof;                       /* Set to true when merge is finished */
78141   int bUseThread;                 /* True to use a bg thread for this object */
78142   SorterFile aFile[2];            /* aFile[0] for reading, [1] for writing */
78143 };
78144
78145 /*
78146 ** An instance of this object is used for writing a PMA.
78147 **
78148 ** The PMA is written one record at a time.  Each record is of an arbitrary
78149 ** size.  But I/O is more efficient if it occurs in page-sized blocks where
78150 ** each block is aligned on a page boundary.  This object caches writes to
78151 ** the PMA so that aligned, page-size blocks are written.
78152 */
78153 struct PmaWriter {
78154   int eFWErr;                     /* Non-zero if in an error state */
78155   u8 *aBuffer;                    /* Pointer to write buffer */
78156   int nBuffer;                    /* Size of write buffer in bytes */
78157   int iBufStart;                  /* First byte of buffer to write */
78158   int iBufEnd;                    /* Last byte of buffer to write */
78159   i64 iWriteOff;                  /* Offset of start of buffer in file */
78160   sqlite3_file *pFd;              /* File handle to write to */
78161 };
78162
78163 /*
78164 ** This object is the header on a single record while that record is being
78165 ** held in memory and prior to being written out as part of a PMA.
78166 **
78167 ** How the linked list is connected depends on how memory is being managed
78168 ** by this module. If using a separate allocation for each in-memory record
78169 ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
78170 ** SorterRecord.u.pNext pointers.
78171 **
78172 ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
78173 ** then while records are being accumulated the list is linked using the
78174 ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
78175 ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
78176 ** has finished passing records to the sorter, or when the in-memory buffer
78177 ** is full, the list is sorted. As part of the sorting process, it is
78178 ** converted to use the SorterRecord.u.pNext pointers. See function
78179 ** vdbeSorterSort() for details.
78180 */
78181 struct SorterRecord {
78182   int nVal;                       /* Size of the record in bytes */
78183   union {
78184     SorterRecord *pNext;          /* Pointer to next record in list */
78185     int iNext;                    /* Offset within aMemory of next record */
78186   } u;
78187   /* The data for the record immediately follows this header */
78188 };
78189
78190 /* Return a pointer to the buffer containing the record data for SorterRecord
78191 ** object p. Should be used as if:
78192 **
78193 **   void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
78194 */
78195 #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
78196
78197
78198 /* Maximum number of PMAs that a single MergeEngine can merge */
78199 #define SORTER_MAX_MERGE_COUNT 16
78200
78201 static int vdbeIncrSwap(IncrMerger*);
78202 static void vdbeIncrFree(IncrMerger *);
78203
78204 /*
78205 ** Free all memory belonging to the PmaReader object passed as the
78206 ** argument. All structure fields are set to zero before returning.
78207 */
78208 static void vdbePmaReaderClear(PmaReader *pReadr){
78209   sqlite3_free(pReadr->aAlloc);
78210   sqlite3_free(pReadr->aBuffer);
78211   if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
78212   vdbeIncrFree(pReadr->pIncr);
78213   memset(pReadr, 0, sizeof(PmaReader));
78214 }
78215
78216 /*
78217 ** Read the next nByte bytes of data from the PMA p.
78218 ** If successful, set *ppOut to point to a buffer containing the data
78219 ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
78220 ** error code.
78221 **
78222 ** The buffer returned in *ppOut is only valid until the
78223 ** next call to this function.
78224 */
78225 static int vdbePmaReadBlob(
78226   PmaReader *p,                   /* PmaReader from which to take the blob */
78227   int nByte,                      /* Bytes of data to read */
78228   u8 **ppOut                      /* OUT: Pointer to buffer containing data */
78229 ){
78230   int iBuf;                       /* Offset within buffer to read from */
78231   int nAvail;                     /* Bytes of data available in buffer */
78232
78233   if( p->aMap ){
78234     *ppOut = &p->aMap[p->iReadOff];
78235     p->iReadOff += nByte;
78236     return SQLITE_OK;
78237   }
78238
78239   assert( p->aBuffer );
78240
78241   /* If there is no more data to be read from the buffer, read the next 
78242   ** p->nBuffer bytes of data from the file into it. Or, if there are less
78243   ** than p->nBuffer bytes remaining in the PMA, read all remaining data.  */
78244   iBuf = p->iReadOff % p->nBuffer;
78245   if( iBuf==0 ){
78246     int nRead;                    /* Bytes to read from disk */
78247     int rc;                       /* sqlite3OsRead() return code */
78248
78249     /* Determine how many bytes of data to read. */
78250     if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
78251       nRead = p->nBuffer;
78252     }else{
78253       nRead = (int)(p->iEof - p->iReadOff);
78254     }
78255     assert( nRead>0 );
78256
78257     /* Readr data from the file. Return early if an error occurs. */
78258     rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
78259     assert( rc!=SQLITE_IOERR_SHORT_READ );
78260     if( rc!=SQLITE_OK ) return rc;
78261   }
78262   nAvail = p->nBuffer - iBuf; 
78263
78264   if( nByte<=nAvail ){
78265     /* The requested data is available in the in-memory buffer. In this
78266     ** case there is no need to make a copy of the data, just return a 
78267     ** pointer into the buffer to the caller.  */
78268     *ppOut = &p->aBuffer[iBuf];
78269     p->iReadOff += nByte;
78270   }else{
78271     /* The requested data is not all available in the in-memory buffer.
78272     ** In this case, allocate space at p->aAlloc[] to copy the requested
78273     ** range into. Then return a copy of pointer p->aAlloc to the caller.  */
78274     int nRem;                     /* Bytes remaining to copy */
78275
78276     /* Extend the p->aAlloc[] allocation if required. */
78277     if( p->nAlloc<nByte ){
78278       u8 *aNew;
78279       int nNew = MAX(128, p->nAlloc*2);
78280       while( nByte>nNew ) nNew = nNew*2;
78281       aNew = sqlite3Realloc(p->aAlloc, nNew);
78282       if( !aNew ) return SQLITE_NOMEM;
78283       p->nAlloc = nNew;
78284       p->aAlloc = aNew;
78285     }
78286
78287     /* Copy as much data as is available in the buffer into the start of
78288     ** p->aAlloc[].  */
78289     memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
78290     p->iReadOff += nAvail;
78291     nRem = nByte - nAvail;
78292
78293     /* The following loop copies up to p->nBuffer bytes per iteration into
78294     ** the p->aAlloc[] buffer.  */
78295     while( nRem>0 ){
78296       int rc;                     /* vdbePmaReadBlob() return code */
78297       int nCopy;                  /* Number of bytes to copy */
78298       u8 *aNext;                  /* Pointer to buffer to copy data from */
78299
78300       nCopy = nRem;
78301       if( nRem>p->nBuffer ) nCopy = p->nBuffer;
78302       rc = vdbePmaReadBlob(p, nCopy, &aNext);
78303       if( rc!=SQLITE_OK ) return rc;
78304       assert( aNext!=p->aAlloc );
78305       memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
78306       nRem -= nCopy;
78307     }
78308
78309     *ppOut = p->aAlloc;
78310   }
78311
78312   return SQLITE_OK;
78313 }
78314
78315 /*
78316 ** Read a varint from the stream of data accessed by p. Set *pnOut to
78317 ** the value read.
78318 */
78319 static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
78320   int iBuf;
78321
78322   if( p->aMap ){
78323     p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
78324   }else{
78325     iBuf = p->iReadOff % p->nBuffer;
78326     if( iBuf && (p->nBuffer-iBuf)>=9 ){
78327       p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
78328     }else{
78329       u8 aVarint[16], *a;
78330       int i = 0, rc;
78331       do{
78332         rc = vdbePmaReadBlob(p, 1, &a);
78333         if( rc ) return rc;
78334         aVarint[(i++)&0xf] = a[0];
78335       }while( (a[0]&0x80)!=0 );
78336       sqlite3GetVarint(aVarint, pnOut);
78337     }
78338   }
78339
78340   return SQLITE_OK;
78341 }
78342
78343 /*
78344 ** Attempt to memory map file pFile. If successful, set *pp to point to the
78345 ** new mapping and return SQLITE_OK. If the mapping is not attempted 
78346 ** (because the file is too large or the VFS layer is configured not to use
78347 ** mmap), return SQLITE_OK and set *pp to NULL.
78348 **
78349 ** Or, if an error occurs, return an SQLite error code. The final value of
78350 ** *pp is undefined in this case.
78351 */
78352 static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
78353   int rc = SQLITE_OK;
78354   if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
78355     sqlite3_file *pFd = pFile->pFd;
78356     if( pFd->pMethods->iVersion>=3 ){
78357       rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
78358       testcase( rc!=SQLITE_OK );
78359     }
78360   }
78361   return rc;
78362 }
78363
78364 /*
78365 ** Attach PmaReader pReadr to file pFile (if it is not already attached to
78366 ** that file) and seek it to offset iOff within the file.  Return SQLITE_OK 
78367 ** if successful, or an SQLite error code if an error occurs.
78368 */
78369 static int vdbePmaReaderSeek(
78370   SortSubtask *pTask,             /* Task context */
78371   PmaReader *pReadr,              /* Reader whose cursor is to be moved */
78372   SorterFile *pFile,              /* Sorter file to read from */
78373   i64 iOff                        /* Offset in pFile */
78374 ){
78375   int rc = SQLITE_OK;
78376
78377   assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
78378
78379   if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
78380   if( pReadr->aMap ){
78381     sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
78382     pReadr->aMap = 0;
78383   }
78384   pReadr->iReadOff = iOff;
78385   pReadr->iEof = pFile->iEof;
78386   pReadr->pFd = pFile->pFd;
78387
78388   rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
78389   if( rc==SQLITE_OK && pReadr->aMap==0 ){
78390     int pgsz = pTask->pSorter->pgsz;
78391     int iBuf = pReadr->iReadOff % pgsz;
78392     if( pReadr->aBuffer==0 ){
78393       pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
78394       if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM;
78395       pReadr->nBuffer = pgsz;
78396     }
78397     if( rc==SQLITE_OK && iBuf ){
78398       int nRead = pgsz - iBuf;
78399       if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
78400         nRead = (int)(pReadr->iEof - pReadr->iReadOff);
78401       }
78402       rc = sqlite3OsRead(
78403           pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
78404       );
78405       testcase( rc!=SQLITE_OK );
78406     }
78407   }
78408
78409   return rc;
78410 }
78411
78412 /*
78413 ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
78414 ** no error occurs, or an SQLite error code if one does.
78415 */
78416 static int vdbePmaReaderNext(PmaReader *pReadr){
78417   int rc = SQLITE_OK;             /* Return Code */
78418   u64 nRec = 0;                   /* Size of record in bytes */
78419
78420
78421   if( pReadr->iReadOff>=pReadr->iEof ){
78422     IncrMerger *pIncr = pReadr->pIncr;
78423     int bEof = 1;
78424     if( pIncr ){
78425       rc = vdbeIncrSwap(pIncr);
78426       if( rc==SQLITE_OK && pIncr->bEof==0 ){
78427         rc = vdbePmaReaderSeek(
78428             pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
78429         );
78430         bEof = 0;
78431       }
78432     }
78433
78434     if( bEof ){
78435       /* This is an EOF condition */
78436       vdbePmaReaderClear(pReadr);
78437       testcase( rc!=SQLITE_OK );
78438       return rc;
78439     }
78440   }
78441
78442   if( rc==SQLITE_OK ){
78443     rc = vdbePmaReadVarint(pReadr, &nRec);
78444   }
78445   if( rc==SQLITE_OK ){
78446     pReadr->nKey = (int)nRec;
78447     rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
78448     testcase( rc!=SQLITE_OK );
78449   }
78450
78451   return rc;
78452 }
78453
78454 /*
78455 ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
78456 ** starting at offset iStart and ending at offset iEof-1. This function 
78457 ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the 
78458 ** PMA is empty).
78459 **
78460 ** If the pnByte parameter is NULL, then it is assumed that the file 
78461 ** contains a single PMA, and that that PMA omits the initial length varint.
78462 */
78463 static int vdbePmaReaderInit(
78464   SortSubtask *pTask,             /* Task context */
78465   SorterFile *pFile,              /* Sorter file to read from */
78466   i64 iStart,                     /* Start offset in pFile */
78467   PmaReader *pReadr,              /* PmaReader to populate */
78468   i64 *pnByte                     /* IN/OUT: Increment this value by PMA size */
78469 ){
78470   int rc;
78471
78472   assert( pFile->iEof>iStart );
78473   assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
78474   assert( pReadr->aBuffer==0 );
78475   assert( pReadr->aMap==0 );
78476
78477   rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
78478   if( rc==SQLITE_OK ){
78479     u64 nByte;                    /* Size of PMA in bytes */
78480     rc = vdbePmaReadVarint(pReadr, &nByte);
78481     pReadr->iEof = pReadr->iReadOff + nByte;
78482     *pnByte += nByte;
78483   }
78484
78485   if( rc==SQLITE_OK ){
78486     rc = vdbePmaReaderNext(pReadr);
78487   }
78488   return rc;
78489 }
78490
78491
78492 /*
78493 ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2, 
78494 ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
78495 ** used by the comparison. Return the result of the comparison.
78496 **
78497 ** Before returning, object (pTask->pUnpacked) is populated with the
78498 ** unpacked version of key2. Or, if pKey2 is passed a NULL pointer, then it 
78499 ** is assumed that the (pTask->pUnpacked) structure already contains the 
78500 ** unpacked key to use as key2.
78501 **
78502 ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
78503 ** to SQLITE_NOMEM.
78504 */
78505 static int vdbeSorterCompare(
78506   SortSubtask *pTask,             /* Subtask context (for pKeyInfo) */
78507   const void *pKey1, int nKey1,   /* Left side of comparison */
78508   const void *pKey2, int nKey2    /* Right side of comparison */
78509 ){
78510   UnpackedRecord *r2 = pTask->pUnpacked;
78511   if( pKey2 ){
78512     sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
78513   }
78514   return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
78515 }
78516
78517 /*
78518 ** Initialize the temporary index cursor just opened as a sorter cursor.
78519 **
78520 ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField)
78521 ** to determine the number of fields that should be compared from the
78522 ** records being sorted. However, if the value passed as argument nField
78523 ** is non-zero and the sorter is able to guarantee a stable sort, nField
78524 ** is used instead. This is used when sorting records for a CREATE INDEX
78525 ** statement. In this case, keys are always delivered to the sorter in
78526 ** order of the primary key, which happens to be make up the final part 
78527 ** of the records being sorted. So if the sort is stable, there is never
78528 ** any reason to compare PK fields and they can be ignored for a small
78529 ** performance boost.
78530 **
78531 ** The sorter can guarantee a stable sort when running in single-threaded
78532 ** mode, but not in multi-threaded mode.
78533 **
78534 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
78535 */
78536 SQLITE_PRIVATE int sqlite3VdbeSorterInit(
78537   sqlite3 *db,                    /* Database connection (for malloc()) */
78538   int nField,                     /* Number of key fields in each record */
78539   VdbeCursor *pCsr                /* Cursor that holds the new sorter */
78540 ){
78541   int pgsz;                       /* Page size of main database */
78542   int i;                          /* Used to iterate through aTask[] */
78543   int mxCache;                    /* Cache size */
78544   VdbeSorter *pSorter;            /* The new sorter */
78545   KeyInfo *pKeyInfo;              /* Copy of pCsr->pKeyInfo with db==0 */
78546   int szKeyInfo;                  /* Size of pCsr->pKeyInfo in bytes */
78547   int sz;                         /* Size of pSorter in bytes */
78548   int rc = SQLITE_OK;
78549 #if SQLITE_MAX_WORKER_THREADS==0
78550 # define nWorker 0
78551 #else
78552   int nWorker;
78553 #endif
78554
78555   /* Initialize the upper limit on the number of worker threads */
78556 #if SQLITE_MAX_WORKER_THREADS>0
78557   if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
78558     nWorker = 0;
78559   }else{
78560     nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
78561   }
78562 #endif
78563
78564   /* Do not allow the total number of threads (main thread + all workers)
78565   ** to exceed the maximum merge count */
78566 #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
78567   if( nWorker>=SORTER_MAX_MERGE_COUNT ){
78568     nWorker = SORTER_MAX_MERGE_COUNT-1;
78569   }
78570 #endif
78571
78572   assert( pCsr->pKeyInfo && pCsr->pBt==0 );
78573   szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
78574   sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
78575
78576   pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
78577   pCsr->pSorter = pSorter;
78578   if( pSorter==0 ){
78579     rc = SQLITE_NOMEM;
78580   }else{
78581     pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
78582     memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
78583     pKeyInfo->db = 0;
78584     if( nField && nWorker==0 ) pKeyInfo->nField = nField;
78585     pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
78586     pSorter->nTask = nWorker + 1;
78587     pSorter->bUseThreads = (pSorter->nTask>1);
78588     pSorter->db = db;
78589     for(i=0; i<pSorter->nTask; i++){
78590       SortSubtask *pTask = &pSorter->aTask[i];
78591       pTask->pSorter = pSorter;
78592     }
78593
78594     if( !sqlite3TempInMemory(db) ){
78595       u32 szPma = sqlite3GlobalConfig.szPma;
78596       pSorter->mnPmaSize = szPma * pgsz;
78597       mxCache = db->aDb[0].pSchema->cache_size;
78598       if( mxCache<(int)szPma ) mxCache = (int)szPma;
78599       pSorter->mxPmaSize = MIN((i64)mxCache*pgsz, SQLITE_MAX_PMASZ);
78600
78601       /* EVIDENCE-OF: R-26747-61719 When the application provides any amount of
78602       ** scratch memory using SQLITE_CONFIG_SCRATCH, SQLite avoids unnecessary
78603       ** large heap allocations.
78604       */
78605       if( sqlite3GlobalConfig.pScratch==0 ){
78606         assert( pSorter->iMemory==0 );
78607         pSorter->nMemory = pgsz;
78608         pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
78609         if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM;
78610       }
78611     }
78612   }
78613
78614   return rc;
78615 }
78616 #undef nWorker   /* Defined at the top of this function */
78617
78618 /*
78619 ** Free the list of sorted records starting at pRecord.
78620 */
78621 static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
78622   SorterRecord *p;
78623   SorterRecord *pNext;
78624   for(p=pRecord; p; p=pNext){
78625     pNext = p->u.pNext;
78626     sqlite3DbFree(db, p);
78627   }
78628 }
78629
78630 /*
78631 ** Free all resources owned by the object indicated by argument pTask. All 
78632 ** fields of *pTask are zeroed before returning.
78633 */
78634 static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
78635   sqlite3DbFree(db, pTask->pUnpacked);
78636   pTask->pUnpacked = 0;
78637 #if SQLITE_MAX_WORKER_THREADS>0
78638   /* pTask->list.aMemory can only be non-zero if it was handed memory
78639   ** from the main thread.  That only occurs SQLITE_MAX_WORKER_THREADS>0 */
78640   if( pTask->list.aMemory ){
78641     sqlite3_free(pTask->list.aMemory);
78642     pTask->list.aMemory = 0;
78643   }else
78644 #endif
78645   {
78646     assert( pTask->list.aMemory==0 );
78647     vdbeSorterRecordFree(0, pTask->list.pList);
78648   }
78649   pTask->list.pList = 0;
78650   if( pTask->file.pFd ){
78651     sqlite3OsCloseFree(pTask->file.pFd);
78652     pTask->file.pFd = 0;
78653     pTask->file.iEof = 0;
78654   }
78655   if( pTask->file2.pFd ){
78656     sqlite3OsCloseFree(pTask->file2.pFd);
78657     pTask->file2.pFd = 0;
78658     pTask->file2.iEof = 0;
78659   }
78660 }
78661
78662 #ifdef SQLITE_DEBUG_SORTER_THREADS
78663 static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
78664   i64 t;
78665   int iTask = (pTask - pTask->pSorter->aTask);
78666   sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
78667   fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
78668 }
78669 static void vdbeSorterRewindDebug(const char *zEvent){
78670   i64 t;
78671   sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
78672   fprintf(stderr, "%lld:X %s\n", t, zEvent);
78673 }
78674 static void vdbeSorterPopulateDebug(
78675   SortSubtask *pTask,
78676   const char *zEvent
78677 ){
78678   i64 t;
78679   int iTask = (pTask - pTask->pSorter->aTask);
78680   sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
78681   fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
78682 }
78683 static void vdbeSorterBlockDebug(
78684   SortSubtask *pTask,
78685   int bBlocked,
78686   const char *zEvent
78687 ){
78688   if( bBlocked ){
78689     i64 t;
78690     sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
78691     fprintf(stderr, "%lld:main %s\n", t, zEvent);
78692   }
78693 }
78694 #else
78695 # define vdbeSorterWorkDebug(x,y)
78696 # define vdbeSorterRewindDebug(y)
78697 # define vdbeSorterPopulateDebug(x,y)
78698 # define vdbeSorterBlockDebug(x,y,z)
78699 #endif
78700
78701 #if SQLITE_MAX_WORKER_THREADS>0
78702 /*
78703 ** Join thread pTask->thread.
78704 */
78705 static int vdbeSorterJoinThread(SortSubtask *pTask){
78706   int rc = SQLITE_OK;
78707   if( pTask->pThread ){
78708 #ifdef SQLITE_DEBUG_SORTER_THREADS
78709     int bDone = pTask->bDone;
78710 #endif
78711     void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
78712     vdbeSorterBlockDebug(pTask, !bDone, "enter");
78713     (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
78714     vdbeSorterBlockDebug(pTask, !bDone, "exit");
78715     rc = SQLITE_PTR_TO_INT(pRet);
78716     assert( pTask->bDone==1 );
78717     pTask->bDone = 0;
78718     pTask->pThread = 0;
78719   }
78720   return rc;
78721 }
78722
78723 /*
78724 ** Launch a background thread to run xTask(pIn).
78725 */
78726 static int vdbeSorterCreateThread(
78727   SortSubtask *pTask,             /* Thread will use this task object */
78728   void *(*xTask)(void*),          /* Routine to run in a separate thread */
78729   void *pIn                       /* Argument passed into xTask() */
78730 ){
78731   assert( pTask->pThread==0 && pTask->bDone==0 );
78732   return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
78733 }
78734
78735 /*
78736 ** Join all outstanding threads launched by SorterWrite() to create 
78737 ** level-0 PMAs.
78738 */
78739 static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
78740   int rc = rcin;
78741   int i;
78742
78743   /* This function is always called by the main user thread.
78744   **
78745   ** If this function is being called after SorterRewind() has been called, 
78746   ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
78747   ** is currently attempt to join one of the other threads. To avoid a race
78748   ** condition where this thread also attempts to join the same object, join 
78749   ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
78750   for(i=pSorter->nTask-1; i>=0; i--){
78751     SortSubtask *pTask = &pSorter->aTask[i];
78752     int rc2 = vdbeSorterJoinThread(pTask);
78753     if( rc==SQLITE_OK ) rc = rc2;
78754   }
78755   return rc;
78756 }
78757 #else
78758 # define vdbeSorterJoinAll(x,rcin) (rcin)
78759 # define vdbeSorterJoinThread(pTask) SQLITE_OK
78760 #endif
78761
78762 /*
78763 ** Allocate a new MergeEngine object capable of handling up to
78764 ** nReader PmaReader inputs.
78765 **
78766 ** nReader is automatically rounded up to the next power of two.
78767 ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
78768 */
78769 static MergeEngine *vdbeMergeEngineNew(int nReader){
78770   int N = 2;                      /* Smallest power of two >= nReader */
78771   int nByte;                      /* Total bytes of space to allocate */
78772   MergeEngine *pNew;              /* Pointer to allocated object to return */
78773
78774   assert( nReader<=SORTER_MAX_MERGE_COUNT );
78775
78776   while( N<nReader ) N += N;
78777   nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
78778
78779   pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
78780   if( pNew ){
78781     pNew->nTree = N;
78782     pNew->pTask = 0;
78783     pNew->aReadr = (PmaReader*)&pNew[1];
78784     pNew->aTree = (int*)&pNew->aReadr[N];
78785   }
78786   return pNew;
78787 }
78788
78789 /*
78790 ** Free the MergeEngine object passed as the only argument.
78791 */
78792 static void vdbeMergeEngineFree(MergeEngine *pMerger){
78793   int i;
78794   if( pMerger ){
78795     for(i=0; i<pMerger->nTree; i++){
78796       vdbePmaReaderClear(&pMerger->aReadr[i]);
78797     }
78798   }
78799   sqlite3_free(pMerger);
78800 }
78801
78802 /*
78803 ** Free all resources associated with the IncrMerger object indicated by
78804 ** the first argument.
78805 */
78806 static void vdbeIncrFree(IncrMerger *pIncr){
78807   if( pIncr ){
78808 #if SQLITE_MAX_WORKER_THREADS>0
78809     if( pIncr->bUseThread ){
78810       vdbeSorterJoinThread(pIncr->pTask);
78811       if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
78812       if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
78813     }
78814 #endif
78815     vdbeMergeEngineFree(pIncr->pMerger);
78816     sqlite3_free(pIncr);
78817   }
78818 }
78819
78820 /*
78821 ** Reset a sorting cursor back to its original empty state.
78822 */
78823 SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
78824   int i;
78825   (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
78826   assert( pSorter->bUseThreads || pSorter->pReader==0 );
78827 #if SQLITE_MAX_WORKER_THREADS>0
78828   if( pSorter->pReader ){
78829     vdbePmaReaderClear(pSorter->pReader);
78830     sqlite3DbFree(db, pSorter->pReader);
78831     pSorter->pReader = 0;
78832   }
78833 #endif
78834   vdbeMergeEngineFree(pSorter->pMerger);
78835   pSorter->pMerger = 0;
78836   for(i=0; i<pSorter->nTask; i++){
78837     SortSubtask *pTask = &pSorter->aTask[i];
78838     vdbeSortSubtaskCleanup(db, pTask);
78839   }
78840   if( pSorter->list.aMemory==0 ){
78841     vdbeSorterRecordFree(0, pSorter->list.pList);
78842   }
78843   pSorter->list.pList = 0;
78844   pSorter->list.szPMA = 0;
78845   pSorter->bUsePMA = 0;
78846   pSorter->iMemory = 0;
78847   pSorter->mxKeysize = 0;
78848   sqlite3DbFree(db, pSorter->pUnpacked);
78849   pSorter->pUnpacked = 0;
78850 }
78851
78852 /*
78853 ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
78854 */
78855 SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
78856   VdbeSorter *pSorter = pCsr->pSorter;
78857   if( pSorter ){
78858     sqlite3VdbeSorterReset(db, pSorter);
78859     sqlite3_free(pSorter->list.aMemory);
78860     sqlite3DbFree(db, pSorter);
78861     pCsr->pSorter = 0;
78862   }
78863 }
78864
78865 #if SQLITE_MAX_MMAP_SIZE>0
78866 /*
78867 ** The first argument is a file-handle open on a temporary file. The file
78868 ** is guaranteed to be nByte bytes or smaller in size. This function
78869 ** attempts to extend the file to nByte bytes in size and to ensure that
78870 ** the VFS has memory mapped it.
78871 **
78872 ** Whether or not the file does end up memory mapped of course depends on
78873 ** the specific VFS implementation.
78874 */
78875 static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
78876   if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
78877     void *p = 0;
78878     int chunksize = 4*1024;
78879     sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_CHUNK_SIZE, &chunksize);
78880     sqlite3OsFileControlHint(pFd, SQLITE_FCNTL_SIZE_HINT, &nByte);
78881     sqlite3OsFetch(pFd, 0, (int)nByte, &p);
78882     sqlite3OsUnfetch(pFd, 0, p);
78883   }
78884 }
78885 #else
78886 # define vdbeSorterExtendFile(x,y,z)
78887 #endif
78888
78889 /*
78890 ** Allocate space for a file-handle and open a temporary file. If successful,
78891 ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
78892 ** Otherwise, set *ppFd to 0 and return an SQLite error code.
78893 */
78894 static int vdbeSorterOpenTempFile(
78895   sqlite3 *db,                    /* Database handle doing sort */
78896   i64 nExtend,                    /* Attempt to extend file to this size */
78897   sqlite3_file **ppFd
78898 ){
78899   int rc;
78900   if( sqlite3FaultSim(202) ) return SQLITE_IOERR_ACCESS;
78901   rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
78902       SQLITE_OPEN_TEMP_JOURNAL |
78903       SQLITE_OPEN_READWRITE    | SQLITE_OPEN_CREATE |
78904       SQLITE_OPEN_EXCLUSIVE    | SQLITE_OPEN_DELETEONCLOSE, &rc
78905   );
78906   if( rc==SQLITE_OK ){
78907     i64 max = SQLITE_MAX_MMAP_SIZE;
78908     sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
78909     if( nExtend>0 ){
78910       vdbeSorterExtendFile(db, *ppFd, nExtend);
78911     }
78912   }
78913   return rc;
78914 }
78915
78916 /*
78917 ** If it has not already been allocated, allocate the UnpackedRecord 
78918 ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or 
78919 ** if no allocation was required), or SQLITE_NOMEM otherwise.
78920 */
78921 static int vdbeSortAllocUnpacked(SortSubtask *pTask){
78922   if( pTask->pUnpacked==0 ){
78923     char *pFree;
78924     pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(
78925         pTask->pSorter->pKeyInfo, 0, 0, &pFree
78926     );
78927     assert( pTask->pUnpacked==(UnpackedRecord*)pFree );
78928     if( pFree==0 ) return SQLITE_NOMEM;
78929     pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
78930     pTask->pUnpacked->errCode = 0;
78931   }
78932   return SQLITE_OK;
78933 }
78934
78935
78936 /*
78937 ** Merge the two sorted lists p1 and p2 into a single list.
78938 ** Set *ppOut to the head of the new list.
78939 */
78940 static void vdbeSorterMerge(
78941   SortSubtask *pTask,             /* Calling thread context */
78942   SorterRecord *p1,               /* First list to merge */
78943   SorterRecord *p2,               /* Second list to merge */
78944   SorterRecord **ppOut            /* OUT: Head of merged list */
78945 ){
78946   SorterRecord *pFinal = 0;
78947   SorterRecord **pp = &pFinal;
78948   void *pVal2 = p2 ? SRVAL(p2) : 0;
78949
78950   while( p1 && p2 ){
78951     int res;
78952     res = vdbeSorterCompare(pTask, SRVAL(p1), p1->nVal, pVal2, p2->nVal);
78953     if( res<=0 ){
78954       *pp = p1;
78955       pp = &p1->u.pNext;
78956       p1 = p1->u.pNext;
78957       pVal2 = 0;
78958     }else{
78959       *pp = p2;
78960        pp = &p2->u.pNext;
78961       p2 = p2->u.pNext;
78962       if( p2==0 ) break;
78963       pVal2 = SRVAL(p2);
78964     }
78965   }
78966   *pp = p1 ? p1 : p2;
78967   *ppOut = pFinal;
78968 }
78969
78970 /*
78971 ** Sort the linked list of records headed at pTask->pList. Return 
78972 ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if 
78973 ** an error occurs.
78974 */
78975 static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
78976   int i;
78977   SorterRecord **aSlot;
78978   SorterRecord *p;
78979   int rc;
78980
78981   rc = vdbeSortAllocUnpacked(pTask);
78982   if( rc!=SQLITE_OK ) return rc;
78983
78984   aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
78985   if( !aSlot ){
78986     return SQLITE_NOMEM;
78987   }
78988
78989   p = pList->pList;
78990   while( p ){
78991     SorterRecord *pNext;
78992     if( pList->aMemory ){
78993       if( (u8*)p==pList->aMemory ){
78994         pNext = 0;
78995       }else{
78996         assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
78997         pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
78998       }
78999     }else{
79000       pNext = p->u.pNext;
79001     }
79002
79003     p->u.pNext = 0;
79004     for(i=0; aSlot[i]; i++){
79005       vdbeSorterMerge(pTask, p, aSlot[i], &p);
79006       aSlot[i] = 0;
79007     }
79008     aSlot[i] = p;
79009     p = pNext;
79010   }
79011
79012   p = 0;
79013   for(i=0; i<64; i++){
79014     vdbeSorterMerge(pTask, p, aSlot[i], &p);
79015   }
79016   pList->pList = p;
79017
79018   sqlite3_free(aSlot);
79019   assert( pTask->pUnpacked->errCode==SQLITE_OK 
79020        || pTask->pUnpacked->errCode==SQLITE_NOMEM 
79021   );
79022   return pTask->pUnpacked->errCode;
79023 }
79024
79025 /*
79026 ** Initialize a PMA-writer object.
79027 */
79028 static void vdbePmaWriterInit(
79029   sqlite3_file *pFd,              /* File handle to write to */
79030   PmaWriter *p,                   /* Object to populate */
79031   int nBuf,                       /* Buffer size */
79032   i64 iStart                      /* Offset of pFd to begin writing at */
79033 ){
79034   memset(p, 0, sizeof(PmaWriter));
79035   p->aBuffer = (u8*)sqlite3Malloc(nBuf);
79036   if( !p->aBuffer ){
79037     p->eFWErr = SQLITE_NOMEM;
79038   }else{
79039     p->iBufEnd = p->iBufStart = (iStart % nBuf);
79040     p->iWriteOff = iStart - p->iBufStart;
79041     p->nBuffer = nBuf;
79042     p->pFd = pFd;
79043   }
79044 }
79045
79046 /*
79047 ** Write nData bytes of data to the PMA. Return SQLITE_OK
79048 ** if successful, or an SQLite error code if an error occurs.
79049 */
79050 static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
79051   int nRem = nData;
79052   while( nRem>0 && p->eFWErr==0 ){
79053     int nCopy = nRem;
79054     if( nCopy>(p->nBuffer - p->iBufEnd) ){
79055       nCopy = p->nBuffer - p->iBufEnd;
79056     }
79057
79058     memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
79059     p->iBufEnd += nCopy;
79060     if( p->iBufEnd==p->nBuffer ){
79061       p->eFWErr = sqlite3OsWrite(p->pFd, 
79062           &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, 
79063           p->iWriteOff + p->iBufStart
79064       );
79065       p->iBufStart = p->iBufEnd = 0;
79066       p->iWriteOff += p->nBuffer;
79067     }
79068     assert( p->iBufEnd<p->nBuffer );
79069
79070     nRem -= nCopy;
79071   }
79072 }
79073
79074 /*
79075 ** Flush any buffered data to disk and clean up the PMA-writer object.
79076 ** The results of using the PMA-writer after this call are undefined.
79077 ** Return SQLITE_OK if flushing the buffered data succeeds or is not 
79078 ** required. Otherwise, return an SQLite error code.
79079 **
79080 ** Before returning, set *piEof to the offset immediately following the
79081 ** last byte written to the file.
79082 */
79083 static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
79084   int rc;
79085   if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
79086     p->eFWErr = sqlite3OsWrite(p->pFd, 
79087         &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart, 
79088         p->iWriteOff + p->iBufStart
79089     );
79090   }
79091   *piEof = (p->iWriteOff + p->iBufEnd);
79092   sqlite3_free(p->aBuffer);
79093   rc = p->eFWErr;
79094   memset(p, 0, sizeof(PmaWriter));
79095   return rc;
79096 }
79097
79098 /*
79099 ** Write value iVal encoded as a varint to the PMA. Return 
79100 ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
79101 */
79102 static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
79103   int nByte; 
79104   u8 aByte[10];
79105   nByte = sqlite3PutVarint(aByte, iVal);
79106   vdbePmaWriteBlob(p, aByte, nByte);
79107 }
79108
79109 /*
79110 ** Write the current contents of in-memory linked-list pList to a level-0
79111 ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if 
79112 ** successful, or an SQLite error code otherwise.
79113 **
79114 ** The format of a PMA is:
79115 **
79116 **     * A varint. This varint contains the total number of bytes of content
79117 **       in the PMA (not including the varint itself).
79118 **
79119 **     * One or more records packed end-to-end in order of ascending keys. 
79120 **       Each record consists of a varint followed by a blob of data (the 
79121 **       key). The varint is the number of bytes in the blob of data.
79122 */
79123 static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
79124   sqlite3 *db = pTask->pSorter->db;
79125   int rc = SQLITE_OK;             /* Return code */
79126   PmaWriter writer;               /* Object used to write to the file */
79127
79128 #ifdef SQLITE_DEBUG
79129   /* Set iSz to the expected size of file pTask->file after writing the PMA. 
79130   ** This is used by an assert() statement at the end of this function.  */
79131   i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
79132 #endif
79133
79134   vdbeSorterWorkDebug(pTask, "enter");
79135   memset(&writer, 0, sizeof(PmaWriter));
79136   assert( pList->szPMA>0 );
79137
79138   /* If the first temporary PMA file has not been opened, open it now. */
79139   if( pTask->file.pFd==0 ){
79140     rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
79141     assert( rc!=SQLITE_OK || pTask->file.pFd );
79142     assert( pTask->file.iEof==0 );
79143     assert( pTask->nPMA==0 );
79144   }
79145
79146   /* Try to get the file to memory map */
79147   if( rc==SQLITE_OK ){
79148     vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
79149   }
79150
79151   /* Sort the list */
79152   if( rc==SQLITE_OK ){
79153     rc = vdbeSorterSort(pTask, pList);
79154   }
79155
79156   if( rc==SQLITE_OK ){
79157     SorterRecord *p;
79158     SorterRecord *pNext = 0;
79159
79160     vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
79161                       pTask->file.iEof);
79162     pTask->nPMA++;
79163     vdbePmaWriteVarint(&writer, pList->szPMA);
79164     for(p=pList->pList; p; p=pNext){
79165       pNext = p->u.pNext;
79166       vdbePmaWriteVarint(&writer, p->nVal);
79167       vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
79168       if( pList->aMemory==0 ) sqlite3_free(p);
79169     }
79170     pList->pList = p;
79171     rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
79172   }
79173
79174   vdbeSorterWorkDebug(pTask, "exit");
79175   assert( rc!=SQLITE_OK || pList->pList==0 );
79176   assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
79177   return rc;
79178 }
79179
79180 /*
79181 ** Advance the MergeEngine to its next entry.
79182 ** Set *pbEof to true there is no next entry because
79183 ** the MergeEngine has reached the end of all its inputs.
79184 **
79185 ** Return SQLITE_OK if successful or an error code if an error occurs.
79186 */
79187 static int vdbeMergeEngineStep(
79188   MergeEngine *pMerger,      /* The merge engine to advance to the next row */
79189   int *pbEof                 /* Set TRUE at EOF.  Set false for more content */
79190 ){
79191   int rc;
79192   int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
79193   SortSubtask *pTask = pMerger->pTask;
79194
79195   /* Advance the current PmaReader */
79196   rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
79197
79198   /* Update contents of aTree[] */
79199   if( rc==SQLITE_OK ){
79200     int i;                      /* Index of aTree[] to recalculate */
79201     PmaReader *pReadr1;         /* First PmaReader to compare */
79202     PmaReader *pReadr2;         /* Second PmaReader to compare */
79203     u8 *pKey2;                  /* To pReadr2->aKey, or 0 if record cached */
79204
79205     /* Find the first two PmaReaders to compare. The one that was just
79206     ** advanced (iPrev) and the one next to it in the array.  */
79207     pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
79208     pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
79209     pKey2 = pReadr2->aKey;
79210
79211     for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
79212       /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
79213       int iRes;
79214       if( pReadr1->pFd==0 ){
79215         iRes = +1;
79216       }else if( pReadr2->pFd==0 ){
79217         iRes = -1;
79218       }else{
79219         iRes = vdbeSorterCompare(pTask, 
79220             pReadr1->aKey, pReadr1->nKey, pKey2, pReadr2->nKey
79221         );
79222       }
79223
79224       /* If pReadr1 contained the smaller value, set aTree[i] to its index.
79225       ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
79226       ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
79227       ** pKey2 to point to the record belonging to pReadr2.
79228       **
79229       ** Alternatively, if pReadr2 contains the smaller of the two values,
79230       ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
79231       ** was actually called above, then pTask->pUnpacked now contains
79232       ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
79233       ** vdbeSorterCompare() from decoding pReadr2 again.
79234       **
79235       ** If the two values were equal, then the value from the oldest
79236       ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
79237       ** is sorted from oldest to newest, so pReadr1 contains older values
79238       ** than pReadr2 iff (pReadr1<pReadr2).  */
79239       if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
79240         pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
79241         pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
79242         pKey2 = pReadr2->aKey;
79243       }else{
79244         if( pReadr1->pFd ) pKey2 = 0;
79245         pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
79246         pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
79247       }
79248     }
79249     *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
79250   }
79251
79252   return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
79253 }
79254
79255 #if SQLITE_MAX_WORKER_THREADS>0
79256 /*
79257 ** The main routine for background threads that write level-0 PMAs.
79258 */
79259 static void *vdbeSorterFlushThread(void *pCtx){
79260   SortSubtask *pTask = (SortSubtask*)pCtx;
79261   int rc;                         /* Return code */
79262   assert( pTask->bDone==0 );
79263   rc = vdbeSorterListToPMA(pTask, &pTask->list);
79264   pTask->bDone = 1;
79265   return SQLITE_INT_TO_PTR(rc);
79266 }
79267 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
79268
79269 /*
79270 ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
79271 ** using a background thread.
79272 */
79273 static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
79274 #if SQLITE_MAX_WORKER_THREADS==0
79275   pSorter->bUsePMA = 1;
79276   return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
79277 #else
79278   int rc = SQLITE_OK;
79279   int i;
79280   SortSubtask *pTask = 0;    /* Thread context used to create new PMA */
79281   int nWorker = (pSorter->nTask-1);
79282
79283   /* Set the flag to indicate that at least one PMA has been written. 
79284   ** Or will be, anyhow.  */
79285   pSorter->bUsePMA = 1;
79286
79287   /* Select a sub-task to sort and flush the current list of in-memory
79288   ** records to disk. If the sorter is running in multi-threaded mode,
79289   ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
79290   ** the background thread from a sub-tasks previous turn is still running,
79291   ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
79292   ** fall back to using the final sub-task. The first (pSorter->nTask-1)
79293   ** sub-tasks are prefered as they use background threads - the final 
79294   ** sub-task uses the main thread. */
79295   for(i=0; i<nWorker; i++){
79296     int iTest = (pSorter->iPrev + i + 1) % nWorker;
79297     pTask = &pSorter->aTask[iTest];
79298     if( pTask->bDone ){
79299       rc = vdbeSorterJoinThread(pTask);
79300     }
79301     if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
79302   }
79303
79304   if( rc==SQLITE_OK ){
79305     if( i==nWorker ){
79306       /* Use the foreground thread for this operation */
79307       rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
79308     }else{
79309       /* Launch a background thread for this operation */
79310       u8 *aMem = pTask->list.aMemory;
79311       void *pCtx = (void*)pTask;
79312
79313       assert( pTask->pThread==0 && pTask->bDone==0 );
79314       assert( pTask->list.pList==0 );
79315       assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
79316
79317       pSorter->iPrev = (u8)(pTask - pSorter->aTask);
79318       pTask->list = pSorter->list;
79319       pSorter->list.pList = 0;
79320       pSorter->list.szPMA = 0;
79321       if( aMem ){
79322         pSorter->list.aMemory = aMem;
79323         pSorter->nMemory = sqlite3MallocSize(aMem);
79324       }else if( pSorter->list.aMemory ){
79325         pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
79326         if( !pSorter->list.aMemory ) return SQLITE_NOMEM;
79327       }
79328
79329       rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
79330     }
79331   }
79332
79333   return rc;
79334 #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
79335 }
79336
79337 /*
79338 ** Add a record to the sorter.
79339 */
79340 SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
79341   const VdbeCursor *pCsr,         /* Sorter cursor */
79342   Mem *pVal                       /* Memory cell containing record */
79343 ){
79344   VdbeSorter *pSorter = pCsr->pSorter;
79345   int rc = SQLITE_OK;             /* Return Code */
79346   SorterRecord *pNew;             /* New list element */
79347
79348   int bFlush;                     /* True to flush contents of memory to PMA */
79349   int nReq;                       /* Bytes of memory required */
79350   int nPMA;                       /* Bytes of PMA space required */
79351
79352   assert( pSorter );
79353
79354   /* Figure out whether or not the current contents of memory should be
79355   ** flushed to a PMA before continuing. If so, do so.
79356   **
79357   ** If using the single large allocation mode (pSorter->aMemory!=0), then
79358   ** flush the contents of memory to a new PMA if (a) at least one value is
79359   ** already in memory and (b) the new value will not fit in memory.
79360   ** 
79361   ** Or, if using separate allocations for each record, flush the contents
79362   ** of memory to a PMA if either of the following are true:
79363   **
79364   **   * The total memory allocated for the in-memory list is greater 
79365   **     than (page-size * cache-size), or
79366   **
79367   **   * The total memory allocated for the in-memory list is greater 
79368   **     than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
79369   */
79370   nReq = pVal->n + sizeof(SorterRecord);
79371   nPMA = pVal->n + sqlite3VarintLen(pVal->n);
79372   if( pSorter->mxPmaSize ){
79373     if( pSorter->list.aMemory ){
79374       bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
79375     }else{
79376       bFlush = (
79377           (pSorter->list.szPMA > pSorter->mxPmaSize)
79378        || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
79379       );
79380     }
79381     if( bFlush ){
79382       rc = vdbeSorterFlushPMA(pSorter);
79383       pSorter->list.szPMA = 0;
79384       pSorter->iMemory = 0;
79385       assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
79386     }
79387   }
79388
79389   pSorter->list.szPMA += nPMA;
79390   if( nPMA>pSorter->mxKeysize ){
79391     pSorter->mxKeysize = nPMA;
79392   }
79393
79394   if( pSorter->list.aMemory ){
79395     int nMin = pSorter->iMemory + nReq;
79396
79397     if( nMin>pSorter->nMemory ){
79398       u8 *aNew;
79399       int nNew = pSorter->nMemory * 2;
79400       while( nNew < nMin ) nNew = nNew*2;
79401       if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
79402       if( nNew < nMin ) nNew = nMin;
79403
79404       aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
79405       if( !aNew ) return SQLITE_NOMEM;
79406       pSorter->list.pList = (SorterRecord*)(
79407           aNew + ((u8*)pSorter->list.pList - pSorter->list.aMemory)
79408       );
79409       pSorter->list.aMemory = aNew;
79410       pSorter->nMemory = nNew;
79411     }
79412
79413     pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
79414     pSorter->iMemory += ROUND8(nReq);
79415     pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
79416   }else{
79417     pNew = (SorterRecord *)sqlite3Malloc(nReq);
79418     if( pNew==0 ){
79419       return SQLITE_NOMEM;
79420     }
79421     pNew->u.pNext = pSorter->list.pList;
79422   }
79423
79424   memcpy(SRVAL(pNew), pVal->z, pVal->n);
79425   pNew->nVal = pVal->n;
79426   pSorter->list.pList = pNew;
79427
79428   return rc;
79429 }
79430
79431 /*
79432 ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
79433 ** of the data stored in aFile[1] is the same as that used by regular PMAs,
79434 ** except that the number-of-bytes varint is omitted from the start.
79435 */
79436 static int vdbeIncrPopulate(IncrMerger *pIncr){
79437   int rc = SQLITE_OK;
79438   int rc2;
79439   i64 iStart = pIncr->iStartOff;
79440   SorterFile *pOut = &pIncr->aFile[1];
79441   SortSubtask *pTask = pIncr->pTask;
79442   MergeEngine *pMerger = pIncr->pMerger;
79443   PmaWriter writer;
79444   assert( pIncr->bEof==0 );
79445
79446   vdbeSorterPopulateDebug(pTask, "enter");
79447
79448   vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
79449   while( rc==SQLITE_OK ){
79450     int dummy;
79451     PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
79452     int nKey = pReader->nKey;
79453     i64 iEof = writer.iWriteOff + writer.iBufEnd;
79454
79455     /* Check if the output file is full or if the input has been exhausted.
79456     ** In either case exit the loop. */
79457     if( pReader->pFd==0 ) break;
79458     if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
79459
79460     /* Write the next key to the output. */
79461     vdbePmaWriteVarint(&writer, nKey);
79462     vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
79463     assert( pIncr->pMerger->pTask==pTask );
79464     rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
79465   }
79466
79467   rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
79468   if( rc==SQLITE_OK ) rc = rc2;
79469   vdbeSorterPopulateDebug(pTask, "exit");
79470   return rc;
79471 }
79472
79473 #if SQLITE_MAX_WORKER_THREADS>0
79474 /*
79475 ** The main routine for background threads that populate aFile[1] of
79476 ** multi-threaded IncrMerger objects.
79477 */
79478 static void *vdbeIncrPopulateThread(void *pCtx){
79479   IncrMerger *pIncr = (IncrMerger*)pCtx;
79480   void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
79481   pIncr->pTask->bDone = 1;
79482   return pRet;
79483 }
79484
79485 /*
79486 ** Launch a background thread to populate aFile[1] of pIncr.
79487 */
79488 static int vdbeIncrBgPopulate(IncrMerger *pIncr){
79489   void *p = (void*)pIncr;
79490   assert( pIncr->bUseThread );
79491   return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
79492 }
79493 #endif
79494
79495 /*
79496 ** This function is called when the PmaReader corresponding to pIncr has
79497 ** finished reading the contents of aFile[0]. Its purpose is to "refill"
79498 ** aFile[0] such that the PmaReader should start rereading it from the
79499 ** beginning.
79500 **
79501 ** For single-threaded objects, this is accomplished by literally reading 
79502 ** keys from pIncr->pMerger and repopulating aFile[0]. 
79503 **
79504 ** For multi-threaded objects, all that is required is to wait until the 
79505 ** background thread is finished (if it is not already) and then swap 
79506 ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
79507 ** been exhausted, this function also launches a new background thread
79508 ** to populate the new aFile[1].
79509 **
79510 ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
79511 */
79512 static int vdbeIncrSwap(IncrMerger *pIncr){
79513   int rc = SQLITE_OK;
79514
79515 #if SQLITE_MAX_WORKER_THREADS>0
79516   if( pIncr->bUseThread ){
79517     rc = vdbeSorterJoinThread(pIncr->pTask);
79518
79519     if( rc==SQLITE_OK ){
79520       SorterFile f0 = pIncr->aFile[0];
79521       pIncr->aFile[0] = pIncr->aFile[1];
79522       pIncr->aFile[1] = f0;
79523     }
79524
79525     if( rc==SQLITE_OK ){
79526       if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
79527         pIncr->bEof = 1;
79528       }else{
79529         rc = vdbeIncrBgPopulate(pIncr);
79530       }
79531     }
79532   }else
79533 #endif
79534   {
79535     rc = vdbeIncrPopulate(pIncr);
79536     pIncr->aFile[0] = pIncr->aFile[1];
79537     if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
79538       pIncr->bEof = 1;
79539     }
79540   }
79541
79542   return rc;
79543 }
79544
79545 /*
79546 ** Allocate and return a new IncrMerger object to read data from pMerger.
79547 **
79548 ** If an OOM condition is encountered, return NULL. In this case free the
79549 ** pMerger argument before returning.
79550 */
79551 static int vdbeIncrMergerNew(
79552   SortSubtask *pTask,     /* The thread that will be using the new IncrMerger */
79553   MergeEngine *pMerger,   /* The MergeEngine that the IncrMerger will control */
79554   IncrMerger **ppOut      /* Write the new IncrMerger here */
79555 ){
79556   int rc = SQLITE_OK;
79557   IncrMerger *pIncr = *ppOut = (IncrMerger*)
79558        (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
79559   if( pIncr ){
79560     pIncr->pMerger = pMerger;
79561     pIncr->pTask = pTask;
79562     pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
79563     pTask->file2.iEof += pIncr->mxSz;
79564   }else{
79565     vdbeMergeEngineFree(pMerger);
79566     rc = SQLITE_NOMEM;
79567   }
79568   return rc;
79569 }
79570
79571 #if SQLITE_MAX_WORKER_THREADS>0
79572 /*
79573 ** Set the "use-threads" flag on object pIncr.
79574 */
79575 static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
79576   pIncr->bUseThread = 1;
79577   pIncr->pTask->file2.iEof -= pIncr->mxSz;
79578 }
79579 #endif /* SQLITE_MAX_WORKER_THREADS>0 */
79580
79581
79582
79583 /*
79584 ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
79585 ** two PmaReaders that feed that entry.  Neither of the PmaReaders
79586 ** are advanced.  This routine merely does the comparison.
79587 */
79588 static void vdbeMergeEngineCompare(
79589   MergeEngine *pMerger,  /* Merge engine containing PmaReaders to compare */
79590   int iOut               /* Store the result in pMerger->aTree[iOut] */
79591 ){
79592   int i1;
79593   int i2;
79594   int iRes;
79595   PmaReader *p1;
79596   PmaReader *p2;
79597
79598   assert( iOut<pMerger->nTree && iOut>0 );
79599
79600   if( iOut>=(pMerger->nTree/2) ){
79601     i1 = (iOut - pMerger->nTree/2) * 2;
79602     i2 = i1 + 1;
79603   }else{
79604     i1 = pMerger->aTree[iOut*2];
79605     i2 = pMerger->aTree[iOut*2+1];
79606   }
79607
79608   p1 = &pMerger->aReadr[i1];
79609   p2 = &pMerger->aReadr[i2];
79610
79611   if( p1->pFd==0 ){
79612     iRes = i2;
79613   }else if( p2->pFd==0 ){
79614     iRes = i1;
79615   }else{
79616     int res;
79617     assert( pMerger->pTask->pUnpacked!=0 );  /* from vdbeSortSubtaskMain() */
79618     res = vdbeSorterCompare(
79619         pMerger->pTask, p1->aKey, p1->nKey, p2->aKey, p2->nKey
79620     );
79621     if( res<=0 ){
79622       iRes = i1;
79623     }else{
79624       iRes = i2;
79625     }
79626   }
79627
79628   pMerger->aTree[iOut] = iRes;
79629 }
79630
79631 /*
79632 ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
79633 ** and vdbePmaReaderIncrMergeInit().
79634 **
79635 ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
79636 ** SQLITE_MAX_WORKER_THREADS==0).  The other values are only used
79637 ** when there exists one or more separate worker threads.
79638 */
79639 #define INCRINIT_NORMAL 0
79640 #define INCRINIT_TASK   1
79641 #define INCRINIT_ROOT   2
79642
79643 /* Forward reference.
79644 ** The vdbeIncrMergeInit() and vdbePmaReaderIncrMergeInit() routines call each
79645 ** other (when building a merge tree).
79646 */
79647 static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode);
79648
79649 /*
79650 ** Initialize the MergeEngine object passed as the second argument. Once this
79651 ** function returns, the first key of merged data may be read from the 
79652 ** MergeEngine object in the usual fashion.
79653 **
79654 ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
79655 ** objects attached to the PmaReader objects that the merger reads from have
79656 ** already been populated, but that they have not yet populated aFile[0] and
79657 ** set the PmaReader objects up to read from it. In this case all that is
79658 ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
79659 ** its first key.
79660 **
79661 ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use 
79662 ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data 
79663 ** to pMerger.
79664 **
79665 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
79666 */
79667 static int vdbeMergeEngineInit(
79668   SortSubtask *pTask,             /* Thread that will run pMerger */
79669   MergeEngine *pMerger,           /* MergeEngine to initialize */
79670   int eMode                       /* One of the INCRINIT_XXX constants */
79671 ){
79672   int rc = SQLITE_OK;             /* Return code */
79673   int i;                          /* For looping over PmaReader objects */
79674   int nTree = pMerger->nTree;
79675
79676   /* eMode is always INCRINIT_NORMAL in single-threaded mode */
79677   assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
79678
79679   /* Verify that the MergeEngine is assigned to a single thread */
79680   assert( pMerger->pTask==0 );
79681   pMerger->pTask = pTask;
79682
79683   for(i=0; i<nTree; i++){
79684     if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
79685       /* PmaReaders should be normally initialized in order, as if they are
79686       ** reading from the same temp file this makes for more linear file IO.
79687       ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
79688       ** in use it will block the vdbePmaReaderNext() call while it uses
79689       ** the main thread to fill its buffer. So calling PmaReaderNext()
79690       ** on this PmaReader before any of the multi-threaded PmaReaders takes
79691       ** better advantage of multi-processor hardware. */
79692       rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
79693     }else{
79694       rc = vdbePmaReaderIncrMergeInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
79695     }
79696     if( rc!=SQLITE_OK ) return rc;
79697   }
79698
79699   for(i=pMerger->nTree-1; i>0; i--){
79700     vdbeMergeEngineCompare(pMerger, i);
79701   }
79702   return pTask->pUnpacked->errCode;
79703 }
79704
79705 /*
79706 ** Initialize the IncrMerge field of a PmaReader.
79707 **
79708 ** If the PmaReader passed as the first argument is not an incremental-reader
79709 ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it serves
79710 ** to open and/or initialize the temp file related fields of the IncrMerge
79711 ** object at (pReadr->pIncr).
79712 **
79713 ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
79714 ** in the sub-tree headed by pReadr are also initialized. Data is then loaded
79715 ** into the buffers belonging to pReadr and it is set to
79716 ** point to the first key in its range.
79717 **
79718 ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
79719 ** to be a multi-threaded PmaReader and this function is being called in a
79720 ** background thread. In this case all PmaReaders in the sub-tree are 
79721 ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
79722 ** pReadr is populated. However, pReadr itself is not set up to point
79723 ** to its first key. A call to vdbePmaReaderNext() is still required to do
79724 ** that. 
79725 **
79726 ** The reason this function does not call vdbePmaReaderNext() immediately 
79727 ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
79728 ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
79729 ** this entire function is being run by thread (pTask->thread), that will
79730 ** lead to the current background thread attempting to join itself.
79731 **
79732 ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
79733 ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
79734 ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
79735 ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
79736 ** the current PmaReader set to point to the first key in its range.
79737 **
79738 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
79739 */
79740 static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
79741   int rc = SQLITE_OK;
79742   IncrMerger *pIncr = pReadr->pIncr;
79743
79744   /* eMode is always INCRINIT_NORMAL in single-threaded mode */
79745   assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
79746
79747   if( pIncr ){
79748     SortSubtask *pTask = pIncr->pTask;
79749     sqlite3 *db = pTask->pSorter->db;
79750
79751     rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
79752
79753     /* Set up the required files for pIncr. A multi-theaded IncrMerge object
79754     ** requires two temp files to itself, whereas a single-threaded object
79755     ** only requires a region of pTask->file2. */
79756     if( rc==SQLITE_OK ){
79757       int mxSz = pIncr->mxSz;
79758 #if SQLITE_MAX_WORKER_THREADS>0
79759       if( pIncr->bUseThread ){
79760         rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
79761         if( rc==SQLITE_OK ){
79762           rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
79763         }
79764       }else
79765 #endif
79766       /*if( !pIncr->bUseThread )*/{
79767         if( pTask->file2.pFd==0 ){
79768           assert( pTask->file2.iEof>0 );
79769           rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
79770           pTask->file2.iEof = 0;
79771         }
79772         if( rc==SQLITE_OK ){
79773           pIncr->aFile[1].pFd = pTask->file2.pFd;
79774           pIncr->iStartOff = pTask->file2.iEof;
79775           pTask->file2.iEof += mxSz;
79776         }
79777       }
79778     }
79779
79780 #if SQLITE_MAX_WORKER_THREADS>0
79781     if( rc==SQLITE_OK && pIncr->bUseThread ){
79782       /* Use the current thread to populate aFile[1], even though this
79783       ** PmaReader is multi-threaded. The reason being that this function
79784       ** is already running in background thread pIncr->pTask->thread. */
79785       assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
79786       rc = vdbeIncrPopulate(pIncr);
79787     }
79788 #endif
79789
79790     if( rc==SQLITE_OK
79791      && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK)
79792     ){
79793       rc = vdbePmaReaderNext(pReadr);
79794     }
79795   }
79796   return rc;
79797 }
79798
79799 #if SQLITE_MAX_WORKER_THREADS>0
79800 /*
79801 ** The main routine for vdbePmaReaderIncrMergeInit() operations run in 
79802 ** background threads.
79803 */
79804 static void *vdbePmaReaderBgInit(void *pCtx){
79805   PmaReader *pReader = (PmaReader*)pCtx;
79806   void *pRet = SQLITE_INT_TO_PTR(
79807                   vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
79808                );
79809   pReader->pIncr->pTask->bDone = 1;
79810   return pRet;
79811 }
79812
79813 /*
79814 ** Use a background thread to invoke vdbePmaReaderIncrMergeInit(INCRINIT_TASK) 
79815 ** on the PmaReader object passed as the first argument.
79816 **
79817 ** This call will initialize the various fields of the pReadr->pIncr 
79818 ** structure and, if it is a multi-threaded IncrMerger, launch a 
79819 ** background thread to populate aFile[1].
79820 */
79821 static int vdbePmaReaderBgIncrInit(PmaReader *pReadr){
79822   void *pCtx = (void*)pReadr;
79823   return vdbeSorterCreateThread(pReadr->pIncr->pTask, vdbePmaReaderBgInit, pCtx);
79824 }
79825 #endif
79826
79827 /*
79828 ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
79829 ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
79830 ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
79831 ** to NULL and return an SQLite error code.
79832 **
79833 ** When this function is called, *piOffset is set to the offset of the
79834 ** first PMA to read from pTask->file. Assuming no error occurs, it is 
79835 ** set to the offset immediately following the last byte of the last
79836 ** PMA before returning. If an error does occur, then the final value of
79837 ** *piOffset is undefined.
79838 */
79839 static int vdbeMergeEngineLevel0(
79840   SortSubtask *pTask,             /* Sorter task to read from */
79841   int nPMA,                       /* Number of PMAs to read */
79842   i64 *piOffset,                  /* IN/OUT: Readr offset in pTask->file */
79843   MergeEngine **ppOut             /* OUT: New merge-engine */
79844 ){
79845   MergeEngine *pNew;              /* Merge engine to return */
79846   i64 iOff = *piOffset;
79847   int i;
79848   int rc = SQLITE_OK;
79849
79850   *ppOut = pNew = vdbeMergeEngineNew(nPMA);
79851   if( pNew==0 ) rc = SQLITE_NOMEM;
79852
79853   for(i=0; i<nPMA && rc==SQLITE_OK; i++){
79854     i64 nDummy;
79855     PmaReader *pReadr = &pNew->aReadr[i];
79856     rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
79857     iOff = pReadr->iEof;
79858   }
79859
79860   if( rc!=SQLITE_OK ){
79861     vdbeMergeEngineFree(pNew);
79862     *ppOut = 0;
79863   }
79864   *piOffset = iOff;
79865   return rc;
79866 }
79867
79868 /*
79869 ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
79870 ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
79871 **
79872 ** i.e.
79873 **
79874 **   nPMA<=16    -> TreeDepth() == 0
79875 **   nPMA<=256   -> TreeDepth() == 1
79876 **   nPMA<=65536 -> TreeDepth() == 2
79877 */
79878 static int vdbeSorterTreeDepth(int nPMA){
79879   int nDepth = 0;
79880   i64 nDiv = SORTER_MAX_MERGE_COUNT;
79881   while( nDiv < (i64)nPMA ){
79882     nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
79883     nDepth++;
79884   }
79885   return nDepth;
79886 }
79887
79888 /*
79889 ** pRoot is the root of an incremental merge-tree with depth nDepth (according
79890 ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
79891 ** tree, counting from zero. This function adds pLeaf to the tree.
79892 **
79893 ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
79894 ** code is returned and pLeaf is freed.
79895 */
79896 static int vdbeSorterAddToTree(
79897   SortSubtask *pTask,             /* Task context */
79898   int nDepth,                     /* Depth of tree according to TreeDepth() */
79899   int iSeq,                       /* Sequence number of leaf within tree */
79900   MergeEngine *pRoot,             /* Root of tree */
79901   MergeEngine *pLeaf              /* Leaf to add to tree */
79902 ){
79903   int rc = SQLITE_OK;
79904   int nDiv = 1;
79905   int i;
79906   MergeEngine *p = pRoot;
79907   IncrMerger *pIncr;
79908
79909   rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
79910
79911   for(i=1; i<nDepth; i++){
79912     nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
79913   }
79914
79915   for(i=1; i<nDepth && rc==SQLITE_OK; i++){
79916     int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
79917     PmaReader *pReadr = &p->aReadr[iIter];
79918
79919     if( pReadr->pIncr==0 ){
79920       MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
79921       if( pNew==0 ){
79922         rc = SQLITE_NOMEM;
79923       }else{
79924         rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
79925       }
79926     }
79927     if( rc==SQLITE_OK ){
79928       p = pReadr->pIncr->pMerger;
79929       nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
79930     }
79931   }
79932
79933   if( rc==SQLITE_OK ){
79934     p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
79935   }else{
79936     vdbeIncrFree(pIncr);
79937   }
79938   return rc;
79939 }
79940
79941 /*
79942 ** This function is called as part of a SorterRewind() operation on a sorter
79943 ** that has already written two or more level-0 PMAs to one or more temp
79944 ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that 
79945 ** can be used to incrementally merge all PMAs on disk.
79946 **
79947 ** If successful, SQLITE_OK is returned and *ppOut set to point to the
79948 ** MergeEngine object at the root of the tree before returning. Or, if an
79949 ** error occurs, an SQLite error code is returned and the final value 
79950 ** of *ppOut is undefined.
79951 */
79952 static int vdbeSorterMergeTreeBuild(
79953   VdbeSorter *pSorter,       /* The VDBE cursor that implements the sort */
79954   MergeEngine **ppOut        /* Write the MergeEngine here */
79955 ){
79956   MergeEngine *pMain = 0;
79957   int rc = SQLITE_OK;
79958   int iTask;
79959
79960 #if SQLITE_MAX_WORKER_THREADS>0
79961   /* If the sorter uses more than one task, then create the top-level 
79962   ** MergeEngine here. This MergeEngine will read data from exactly 
79963   ** one PmaReader per sub-task.  */
79964   assert( pSorter->bUseThreads || pSorter->nTask==1 );
79965   if( pSorter->nTask>1 ){
79966     pMain = vdbeMergeEngineNew(pSorter->nTask);
79967     if( pMain==0 ) rc = SQLITE_NOMEM;
79968   }
79969 #endif
79970
79971   for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
79972     SortSubtask *pTask = &pSorter->aTask[iTask];
79973     assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
79974     if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
79975       MergeEngine *pRoot = 0;     /* Root node of tree for this task */
79976       int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
79977       i64 iReadOff = 0;
79978
79979       if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
79980         rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
79981       }else{
79982         int i;
79983         int iSeq = 0;
79984         pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
79985         if( pRoot==0 ) rc = SQLITE_NOMEM;
79986         for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
79987           MergeEngine *pMerger = 0; /* New level-0 PMA merger */
79988           int nReader;              /* Number of level-0 PMAs to merge */
79989
79990           nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
79991           rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
79992           if( rc==SQLITE_OK ){
79993             rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
79994           }
79995         }
79996       }
79997
79998       if( rc==SQLITE_OK ){
79999 #if SQLITE_MAX_WORKER_THREADS>0
80000         if( pMain!=0 ){
80001           rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
80002         }else
80003 #endif
80004         {
80005           assert( pMain==0 );
80006           pMain = pRoot;
80007         }
80008       }else{
80009         vdbeMergeEngineFree(pRoot);
80010       }
80011     }
80012   }
80013
80014   if( rc!=SQLITE_OK ){
80015     vdbeMergeEngineFree(pMain);
80016     pMain = 0;
80017   }
80018   *ppOut = pMain;
80019   return rc;
80020 }
80021
80022 /*
80023 ** This function is called as part of an sqlite3VdbeSorterRewind() operation
80024 ** on a sorter that has written two or more PMAs to temporary files. It sets
80025 ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
80026 ** (for multi-threaded sorters) so that it can be used to iterate through
80027 ** all records stored in the sorter.
80028 **
80029 ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
80030 */
80031 static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
80032   int rc;                         /* Return code */
80033   SortSubtask *pTask0 = &pSorter->aTask[0];
80034   MergeEngine *pMain = 0;
80035 #if SQLITE_MAX_WORKER_THREADS
80036   sqlite3 *db = pTask0->pSorter->db;
80037 #endif
80038
80039   rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
80040   if( rc==SQLITE_OK ){
80041 #if SQLITE_MAX_WORKER_THREADS
80042     assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
80043     if( pSorter->bUseThreads ){
80044       int iTask;
80045       PmaReader *pReadr = 0;
80046       SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
80047       rc = vdbeSortAllocUnpacked(pLast);
80048       if( rc==SQLITE_OK ){
80049         pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
80050         pSorter->pReader = pReadr;
80051         if( pReadr==0 ) rc = SQLITE_NOMEM;
80052       }
80053       if( rc==SQLITE_OK ){
80054         rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
80055         if( rc==SQLITE_OK ){
80056           vdbeIncrMergerSetThreads(pReadr->pIncr);
80057           for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
80058             IncrMerger *pIncr;
80059             if( (pIncr = pMain->aReadr[iTask].pIncr) ){
80060               vdbeIncrMergerSetThreads(pIncr);
80061               assert( pIncr->pTask!=pLast );
80062             }
80063           }
80064           for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
80065             PmaReader *p = &pMain->aReadr[iTask];
80066             assert( p->pIncr==0 || p->pIncr->pTask==&pSorter->aTask[iTask] );
80067             if( p->pIncr ){ 
80068               if( iTask==pSorter->nTask-1 ){
80069                 rc = vdbePmaReaderIncrMergeInit(p, INCRINIT_TASK);
80070               }else{
80071                 rc = vdbePmaReaderBgIncrInit(p);
80072               }
80073             }
80074           }
80075         }
80076         pMain = 0;
80077       }
80078       if( rc==SQLITE_OK ){
80079         rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
80080       }
80081     }else
80082 #endif
80083     {
80084       rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
80085       pSorter->pMerger = pMain;
80086       pMain = 0;
80087     }
80088   }
80089
80090   if( rc!=SQLITE_OK ){
80091     vdbeMergeEngineFree(pMain);
80092   }
80093   return rc;
80094 }
80095
80096
80097 /*
80098 ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
80099 ** this function is called to prepare for iterating through the records
80100 ** in sorted order.
80101 */
80102 SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
80103   VdbeSorter *pSorter = pCsr->pSorter;
80104   int rc = SQLITE_OK;             /* Return code */
80105
80106   assert( pSorter );
80107
80108   /* If no data has been written to disk, then do not do so now. Instead,
80109   ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
80110   ** from the in-memory list.  */
80111   if( pSorter->bUsePMA==0 ){
80112     if( pSorter->list.pList ){
80113       *pbEof = 0;
80114       rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
80115     }else{
80116       *pbEof = 1;
80117     }
80118     return rc;
80119   }
80120
80121   /* Write the current in-memory list to a PMA. When the VdbeSorterWrite() 
80122   ** function flushes the contents of memory to disk, it immediately always
80123   ** creates a new list consisting of a single key immediately afterwards.
80124   ** So the list is never empty at this point.  */
80125   assert( pSorter->list.pList );
80126   rc = vdbeSorterFlushPMA(pSorter);
80127
80128   /* Join all threads */
80129   rc = vdbeSorterJoinAll(pSorter, rc);
80130
80131   vdbeSorterRewindDebug("rewind");
80132
80133   /* Assuming no errors have occurred, set up a merger structure to 
80134   ** incrementally read and merge all remaining PMAs.  */
80135   assert( pSorter->pReader==0 );
80136   if( rc==SQLITE_OK ){
80137     rc = vdbeSorterSetupMerge(pSorter);
80138     *pbEof = 0;
80139   }
80140
80141   vdbeSorterRewindDebug("rewinddone");
80142   return rc;
80143 }
80144
80145 /*
80146 ** Advance to the next element in the sorter.
80147 */
80148 SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
80149   VdbeSorter *pSorter = pCsr->pSorter;
80150   int rc;                         /* Return code */
80151
80152   assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
80153   if( pSorter->bUsePMA ){
80154     assert( pSorter->pReader==0 || pSorter->pMerger==0 );
80155     assert( pSorter->bUseThreads==0 || pSorter->pReader );
80156     assert( pSorter->bUseThreads==1 || pSorter->pMerger );
80157 #if SQLITE_MAX_WORKER_THREADS>0
80158     if( pSorter->bUseThreads ){
80159       rc = vdbePmaReaderNext(pSorter->pReader);
80160       *pbEof = (pSorter->pReader->pFd==0);
80161     }else
80162 #endif
80163     /*if( !pSorter->bUseThreads )*/ {
80164       assert( pSorter->pMerger!=0 );
80165       assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
80166       rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof);
80167     }
80168   }else{
80169     SorterRecord *pFree = pSorter->list.pList;
80170     pSorter->list.pList = pFree->u.pNext;
80171     pFree->u.pNext = 0;
80172     if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
80173     *pbEof = !pSorter->list.pList;
80174     rc = SQLITE_OK;
80175   }
80176   return rc;
80177 }
80178
80179 /*
80180 ** Return a pointer to a buffer owned by the sorter that contains the 
80181 ** current key.
80182 */
80183 static void *vdbeSorterRowkey(
80184   const VdbeSorter *pSorter,      /* Sorter object */
80185   int *pnKey                      /* OUT: Size of current key in bytes */
80186 ){
80187   void *pKey;
80188   if( pSorter->bUsePMA ){
80189     PmaReader *pReader;
80190 #if SQLITE_MAX_WORKER_THREADS>0
80191     if( pSorter->bUseThreads ){
80192       pReader = pSorter->pReader;
80193     }else
80194 #endif
80195     /*if( !pSorter->bUseThreads )*/{
80196       pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
80197     }
80198     *pnKey = pReader->nKey;
80199     pKey = pReader->aKey;
80200   }else{
80201     *pnKey = pSorter->list.pList->nVal;
80202     pKey = SRVAL(pSorter->list.pList);
80203   }
80204   return pKey;
80205 }
80206
80207 /*
80208 ** Copy the current sorter key into the memory cell pOut.
80209 */
80210 SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
80211   VdbeSorter *pSorter = pCsr->pSorter;
80212   void *pKey; int nKey;           /* Sorter key to copy into pOut */
80213
80214   pKey = vdbeSorterRowkey(pSorter, &nKey);
80215   if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
80216     return SQLITE_NOMEM;
80217   }
80218   pOut->n = nKey;
80219   MemSetTypeFlag(pOut, MEM_Blob);
80220   memcpy(pOut->z, pKey, nKey);
80221
80222   return SQLITE_OK;
80223 }
80224
80225 /*
80226 ** Compare the key in memory cell pVal with the key that the sorter cursor
80227 ** passed as the first argument currently points to. For the purposes of
80228 ** the comparison, ignore the rowid field at the end of each record.
80229 **
80230 ** If the sorter cursor key contains any NULL values, consider it to be
80231 ** less than pVal. Even if pVal also contains NULL values.
80232 **
80233 ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
80234 ** Otherwise, set *pRes to a negative, zero or positive value if the
80235 ** key in pVal is smaller than, equal to or larger than the current sorter
80236 ** key.
80237 **
80238 ** This routine forms the core of the OP_SorterCompare opcode, which in
80239 ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
80240 */
80241 SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
80242   const VdbeCursor *pCsr,         /* Sorter cursor */
80243   Mem *pVal,                      /* Value to compare to current sorter key */
80244   int nKeyCol,                    /* Compare this many columns */
80245   int *pRes                       /* OUT: Result of comparison */
80246 ){
80247   VdbeSorter *pSorter = pCsr->pSorter;
80248   UnpackedRecord *r2 = pSorter->pUnpacked;
80249   KeyInfo *pKeyInfo = pCsr->pKeyInfo;
80250   int i;
80251   void *pKey; int nKey;           /* Sorter key to compare pVal with */
80252
80253   if( r2==0 ){
80254     char *p;
80255     r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo,0,0,&p);
80256     assert( pSorter->pUnpacked==(UnpackedRecord*)p );
80257     if( r2==0 ) return SQLITE_NOMEM;
80258     r2->nField = nKeyCol;
80259   }
80260   assert( r2->nField==nKeyCol );
80261
80262   pKey = vdbeSorterRowkey(pSorter, &nKey);
80263   sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
80264   for(i=0; i<nKeyCol; i++){
80265     if( r2->aMem[i].flags & MEM_Null ){
80266       *pRes = -1;
80267       return SQLITE_OK;
80268     }
80269   }
80270
80271   *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
80272   return SQLITE_OK;
80273 }
80274
80275 /************** End of vdbesort.c ********************************************/
80276 /************** Begin file journal.c *****************************************/
80277 /*
80278 ** 2007 August 22
80279 **
80280 ** The author disclaims copyright to this source code.  In place of
80281 ** a legal notice, here is a blessing:
80282 **
80283 **    May you do good and not evil.
80284 **    May you find forgiveness for yourself and forgive others.
80285 **    May you share freely, never taking more than you give.
80286 **
80287 *************************************************************************
80288 **
80289 ** This file implements a special kind of sqlite3_file object used
80290 ** by SQLite to create journal files if the atomic-write optimization
80291 ** is enabled.
80292 **
80293 ** The distinctive characteristic of this sqlite3_file is that the
80294 ** actual on disk file is created lazily. When the file is created,
80295 ** the caller specifies a buffer size for an in-memory buffer to
80296 ** be used to service read() and write() requests. The actual file
80297 ** on disk is not created or populated until either:
80298 **
80299 **   1) The in-memory representation grows too large for the allocated 
80300 **      buffer, or
80301 **   2) The sqlite3JournalCreate() function is called.
80302 */
80303 #ifdef SQLITE_ENABLE_ATOMIC_WRITE
80304
80305
80306 /*
80307 ** A JournalFile object is a subclass of sqlite3_file used by
80308 ** as an open file handle for journal files.
80309 */
80310 struct JournalFile {
80311   sqlite3_io_methods *pMethod;    /* I/O methods on journal files */
80312   int nBuf;                       /* Size of zBuf[] in bytes */
80313   char *zBuf;                     /* Space to buffer journal writes */
80314   int iSize;                      /* Amount of zBuf[] currently used */
80315   int flags;                      /* xOpen flags */
80316   sqlite3_vfs *pVfs;              /* The "real" underlying VFS */
80317   sqlite3_file *pReal;            /* The "real" underlying file descriptor */
80318   const char *zJournal;           /* Name of the journal file */
80319 };
80320 typedef struct JournalFile JournalFile;
80321
80322 /*
80323 ** If it does not already exists, create and populate the on-disk file 
80324 ** for JournalFile p.
80325 */
80326 static int createFile(JournalFile *p){
80327   int rc = SQLITE_OK;
80328   if( !p->pReal ){
80329     sqlite3_file *pReal = (sqlite3_file *)&p[1];
80330     rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
80331     if( rc==SQLITE_OK ){
80332       p->pReal = pReal;
80333       if( p->iSize>0 ){
80334         assert(p->iSize<=p->nBuf);
80335         rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
80336       }
80337       if( rc!=SQLITE_OK ){
80338         /* If an error occurred while writing to the file, close it before
80339         ** returning. This way, SQLite uses the in-memory journal data to 
80340         ** roll back changes made to the internal page-cache before this
80341         ** function was called.  */
80342         sqlite3OsClose(pReal);
80343         p->pReal = 0;
80344       }
80345     }
80346   }
80347   return rc;
80348 }
80349
80350 /*
80351 ** Close the file.
80352 */
80353 static int jrnlClose(sqlite3_file *pJfd){
80354   JournalFile *p = (JournalFile *)pJfd;
80355   if( p->pReal ){
80356     sqlite3OsClose(p->pReal);
80357   }
80358   sqlite3_free(p->zBuf);
80359   return SQLITE_OK;
80360 }
80361
80362 /*
80363 ** Read data from the file.
80364 */
80365 static int jrnlRead(
80366   sqlite3_file *pJfd,    /* The journal file from which to read */
80367   void *zBuf,            /* Put the results here */
80368   int iAmt,              /* Number of bytes to read */
80369   sqlite_int64 iOfst     /* Begin reading at this offset */
80370 ){
80371   int rc = SQLITE_OK;
80372   JournalFile *p = (JournalFile *)pJfd;
80373   if( p->pReal ){
80374     rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
80375   }else if( (iAmt+iOfst)>p->iSize ){
80376     rc = SQLITE_IOERR_SHORT_READ;
80377   }else{
80378     memcpy(zBuf, &p->zBuf[iOfst], iAmt);
80379   }
80380   return rc;
80381 }
80382
80383 /*
80384 ** Write data to the file.
80385 */
80386 static int jrnlWrite(
80387   sqlite3_file *pJfd,    /* The journal file into which to write */
80388   const void *zBuf,      /* Take data to be written from here */
80389   int iAmt,              /* Number of bytes to write */
80390   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
80391 ){
80392   int rc = SQLITE_OK;
80393   JournalFile *p = (JournalFile *)pJfd;
80394   if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
80395     rc = createFile(p);
80396   }
80397   if( rc==SQLITE_OK ){
80398     if( p->pReal ){
80399       rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
80400     }else{
80401       memcpy(&p->zBuf[iOfst], zBuf, iAmt);
80402       if( p->iSize<(iOfst+iAmt) ){
80403         p->iSize = (iOfst+iAmt);
80404       }
80405     }
80406   }
80407   return rc;
80408 }
80409
80410 /*
80411 ** Truncate the file.
80412 */
80413 static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
80414   int rc = SQLITE_OK;
80415   JournalFile *p = (JournalFile *)pJfd;
80416   if( p->pReal ){
80417     rc = sqlite3OsTruncate(p->pReal, size);
80418   }else if( size<p->iSize ){
80419     p->iSize = size;
80420   }
80421   return rc;
80422 }
80423
80424 /*
80425 ** Sync the file.
80426 */
80427 static int jrnlSync(sqlite3_file *pJfd, int flags){
80428   int rc;
80429   JournalFile *p = (JournalFile *)pJfd;
80430   if( p->pReal ){
80431     rc = sqlite3OsSync(p->pReal, flags);
80432   }else{
80433     rc = SQLITE_OK;
80434   }
80435   return rc;
80436 }
80437
80438 /*
80439 ** Query the size of the file in bytes.
80440 */
80441 static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
80442   int rc = SQLITE_OK;
80443   JournalFile *p = (JournalFile *)pJfd;
80444   if( p->pReal ){
80445     rc = sqlite3OsFileSize(p->pReal, pSize);
80446   }else{
80447     *pSize = (sqlite_int64) p->iSize;
80448   }
80449   return rc;
80450 }
80451
80452 /*
80453 ** Table of methods for JournalFile sqlite3_file object.
80454 */
80455 static struct sqlite3_io_methods JournalFileMethods = {
80456   1,             /* iVersion */
80457   jrnlClose,     /* xClose */
80458   jrnlRead,      /* xRead */
80459   jrnlWrite,     /* xWrite */
80460   jrnlTruncate,  /* xTruncate */
80461   jrnlSync,      /* xSync */
80462   jrnlFileSize,  /* xFileSize */
80463   0,             /* xLock */
80464   0,             /* xUnlock */
80465   0,             /* xCheckReservedLock */
80466   0,             /* xFileControl */
80467   0,             /* xSectorSize */
80468   0,             /* xDeviceCharacteristics */
80469   0,             /* xShmMap */
80470   0,             /* xShmLock */
80471   0,             /* xShmBarrier */
80472   0              /* xShmUnmap */
80473 };
80474
80475 /* 
80476 ** Open a journal file.
80477 */
80478 SQLITE_PRIVATE int sqlite3JournalOpen(
80479   sqlite3_vfs *pVfs,         /* The VFS to use for actual file I/O */
80480   const char *zName,         /* Name of the journal file */
80481   sqlite3_file *pJfd,        /* Preallocated, blank file handle */
80482   int flags,                 /* Opening flags */
80483   int nBuf                   /* Bytes buffered before opening the file */
80484 ){
80485   JournalFile *p = (JournalFile *)pJfd;
80486   memset(p, 0, sqlite3JournalSize(pVfs));
80487   if( nBuf>0 ){
80488     p->zBuf = sqlite3MallocZero(nBuf);
80489     if( !p->zBuf ){
80490       return SQLITE_NOMEM;
80491     }
80492   }else{
80493     return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
80494   }
80495   p->pMethod = &JournalFileMethods;
80496   p->nBuf = nBuf;
80497   p->flags = flags;
80498   p->zJournal = zName;
80499   p->pVfs = pVfs;
80500   return SQLITE_OK;
80501 }
80502
80503 /*
80504 ** If the argument p points to a JournalFile structure, and the underlying
80505 ** file has not yet been created, create it now.
80506 */
80507 SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
80508   if( p->pMethods!=&JournalFileMethods ){
80509     return SQLITE_OK;
80510   }
80511   return createFile((JournalFile *)p);
80512 }
80513
80514 /*
80515 ** The file-handle passed as the only argument is guaranteed to be an open
80516 ** file. It may or may not be of class JournalFile. If the file is a
80517 ** JournalFile, and the underlying file on disk has not yet been opened,
80518 ** return 0. Otherwise, return 1.
80519 */
80520 SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
80521   return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
80522 }
80523
80524 /* 
80525 ** Return the number of bytes required to store a JournalFile that uses vfs
80526 ** pVfs to create the underlying on-disk files.
80527 */
80528 SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
80529   return (pVfs->szOsFile+sizeof(JournalFile));
80530 }
80531 #endif
80532
80533 /************** End of journal.c *********************************************/
80534 /************** Begin file memjournal.c **************************************/
80535 /*
80536 ** 2008 October 7
80537 **
80538 ** The author disclaims copyright to this source code.  In place of
80539 ** a legal notice, here is a blessing:
80540 **
80541 **    May you do good and not evil.
80542 **    May you find forgiveness for yourself and forgive others.
80543 **    May you share freely, never taking more than you give.
80544 **
80545 *************************************************************************
80546 **
80547 ** This file contains code use to implement an in-memory rollback journal.
80548 ** The in-memory rollback journal is used to journal transactions for
80549 ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
80550 */
80551
80552 /* Forward references to internal structures */
80553 typedef struct MemJournal MemJournal;
80554 typedef struct FilePoint FilePoint;
80555 typedef struct FileChunk FileChunk;
80556
80557 /* Space to hold the rollback journal is allocated in increments of
80558 ** this many bytes.
80559 **
80560 ** The size chosen is a little less than a power of two.  That way,
80561 ** the FileChunk object will have a size that almost exactly fills
80562 ** a power-of-two allocation.  This minimizes wasted space in power-of-two
80563 ** memory allocators.
80564 */
80565 #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
80566
80567 /*
80568 ** The rollback journal is composed of a linked list of these structures.
80569 */
80570 struct FileChunk {
80571   FileChunk *pNext;               /* Next chunk in the journal */
80572   u8 zChunk[JOURNAL_CHUNKSIZE];   /* Content of this chunk */
80573 };
80574
80575 /*
80576 ** An instance of this object serves as a cursor into the rollback journal.
80577 ** The cursor can be either for reading or writing.
80578 */
80579 struct FilePoint {
80580   sqlite3_int64 iOffset;          /* Offset from the beginning of the file */
80581   FileChunk *pChunk;              /* Specific chunk into which cursor points */
80582 };
80583
80584 /*
80585 ** This subclass is a subclass of sqlite3_file.  Each open memory-journal
80586 ** is an instance of this class.
80587 */
80588 struct MemJournal {
80589   sqlite3_io_methods *pMethod;    /* Parent class. MUST BE FIRST */
80590   FileChunk *pFirst;              /* Head of in-memory chunk-list */
80591   FilePoint endpoint;             /* Pointer to the end of the file */
80592   FilePoint readpoint;            /* Pointer to the end of the last xRead() */
80593 };
80594
80595 /*
80596 ** Read data from the in-memory journal file.  This is the implementation
80597 ** of the sqlite3_vfs.xRead method.
80598 */
80599 static int memjrnlRead(
80600   sqlite3_file *pJfd,    /* The journal file from which to read */
80601   void *zBuf,            /* Put the results here */
80602   int iAmt,              /* Number of bytes to read */
80603   sqlite_int64 iOfst     /* Begin reading at this offset */
80604 ){
80605   MemJournal *p = (MemJournal *)pJfd;
80606   u8 *zOut = zBuf;
80607   int nRead = iAmt;
80608   int iChunkOffset;
80609   FileChunk *pChunk;
80610
80611   /* SQLite never tries to read past the end of a rollback journal file */
80612   assert( iOfst+iAmt<=p->endpoint.iOffset );
80613
80614   if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
80615     sqlite3_int64 iOff = 0;
80616     for(pChunk=p->pFirst; 
80617         ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
80618         pChunk=pChunk->pNext
80619     ){
80620       iOff += JOURNAL_CHUNKSIZE;
80621     }
80622   }else{
80623     pChunk = p->readpoint.pChunk;
80624   }
80625
80626   iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
80627   do {
80628     int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
80629     int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
80630     memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
80631     zOut += nCopy;
80632     nRead -= iSpace;
80633     iChunkOffset = 0;
80634   } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
80635   p->readpoint.iOffset = iOfst+iAmt;
80636   p->readpoint.pChunk = pChunk;
80637
80638   return SQLITE_OK;
80639 }
80640
80641 /*
80642 ** Write data to the file.
80643 */
80644 static int memjrnlWrite(
80645   sqlite3_file *pJfd,    /* The journal file into which to write */
80646   const void *zBuf,      /* Take data to be written from here */
80647   int iAmt,              /* Number of bytes to write */
80648   sqlite_int64 iOfst     /* Begin writing at this offset into the file */
80649 ){
80650   MemJournal *p = (MemJournal *)pJfd;
80651   int nWrite = iAmt;
80652   u8 *zWrite = (u8 *)zBuf;
80653
80654   /* An in-memory journal file should only ever be appended to. Random
80655   ** access writes are not required by sqlite.
80656   */
80657   assert( iOfst==p->endpoint.iOffset );
80658   UNUSED_PARAMETER(iOfst);
80659
80660   while( nWrite>0 ){
80661     FileChunk *pChunk = p->endpoint.pChunk;
80662     int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
80663     int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
80664
80665     if( iChunkOffset==0 ){
80666       /* New chunk is required to extend the file. */
80667       FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
80668       if( !pNew ){
80669         return SQLITE_IOERR_NOMEM;
80670       }
80671       pNew->pNext = 0;
80672       if( pChunk ){
80673         assert( p->pFirst );
80674         pChunk->pNext = pNew;
80675       }else{
80676         assert( !p->pFirst );
80677         p->pFirst = pNew;
80678       }
80679       p->endpoint.pChunk = pNew;
80680     }
80681
80682     memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
80683     zWrite += iSpace;
80684     nWrite -= iSpace;
80685     p->endpoint.iOffset += iSpace;
80686   }
80687
80688   return SQLITE_OK;
80689 }
80690
80691 /*
80692 ** Truncate the file.
80693 */
80694 static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
80695   MemJournal *p = (MemJournal *)pJfd;
80696   FileChunk *pChunk;
80697   assert(size==0);
80698   UNUSED_PARAMETER(size);
80699   pChunk = p->pFirst;
80700   while( pChunk ){
80701     FileChunk *pTmp = pChunk;
80702     pChunk = pChunk->pNext;
80703     sqlite3_free(pTmp);
80704   }
80705   sqlite3MemJournalOpen(pJfd);
80706   return SQLITE_OK;
80707 }
80708
80709 /*
80710 ** Close the file.
80711 */
80712 static int memjrnlClose(sqlite3_file *pJfd){
80713   memjrnlTruncate(pJfd, 0);
80714   return SQLITE_OK;
80715 }
80716
80717
80718 /*
80719 ** Sync the file.
80720 **
80721 ** Syncing an in-memory journal is a no-op.  And, in fact, this routine
80722 ** is never called in a working implementation.  This implementation
80723 ** exists purely as a contingency, in case some malfunction in some other
80724 ** part of SQLite causes Sync to be called by mistake.
80725 */
80726 static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
80727   UNUSED_PARAMETER2(NotUsed, NotUsed2);
80728   return SQLITE_OK;
80729 }
80730
80731 /*
80732 ** Query the size of the file in bytes.
80733 */
80734 static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
80735   MemJournal *p = (MemJournal *)pJfd;
80736   *pSize = (sqlite_int64) p->endpoint.iOffset;
80737   return SQLITE_OK;
80738 }
80739
80740 /*
80741 ** Table of methods for MemJournal sqlite3_file object.
80742 */
80743 static const struct sqlite3_io_methods MemJournalMethods = {
80744   1,                /* iVersion */
80745   memjrnlClose,     /* xClose */
80746   memjrnlRead,      /* xRead */
80747   memjrnlWrite,     /* xWrite */
80748   memjrnlTruncate,  /* xTruncate */
80749   memjrnlSync,      /* xSync */
80750   memjrnlFileSize,  /* xFileSize */
80751   0,                /* xLock */
80752   0,                /* xUnlock */
80753   0,                /* xCheckReservedLock */
80754   0,                /* xFileControl */
80755   0,                /* xSectorSize */
80756   0,                /* xDeviceCharacteristics */
80757   0,                /* xShmMap */
80758   0,                /* xShmLock */
80759   0,                /* xShmBarrier */
80760   0,                /* xShmUnmap */
80761   0,                /* xFetch */
80762   0                 /* xUnfetch */
80763 };
80764
80765 /* 
80766 ** Open a journal file.
80767 */
80768 SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
80769   MemJournal *p = (MemJournal *)pJfd;
80770   assert( EIGHT_BYTE_ALIGNMENT(p) );
80771   memset(p, 0, sqlite3MemJournalSize());
80772   p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
80773 }
80774
80775 /*
80776 ** Return true if the file-handle passed as an argument is 
80777 ** an in-memory journal 
80778 */
80779 SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
80780   return pJfd->pMethods==&MemJournalMethods;
80781 }
80782
80783 /* 
80784 ** Return the number of bytes required to store a MemJournal file descriptor.
80785 */
80786 SQLITE_PRIVATE int sqlite3MemJournalSize(void){
80787   return sizeof(MemJournal);
80788 }
80789
80790 /************** End of memjournal.c ******************************************/
80791 /************** Begin file walker.c ******************************************/
80792 /*
80793 ** 2008 August 16
80794 **
80795 ** The author disclaims copyright to this source code.  In place of
80796 ** a legal notice, here is a blessing:
80797 **
80798 **    May you do good and not evil.
80799 **    May you find forgiveness for yourself and forgive others.
80800 **    May you share freely, never taking more than you give.
80801 **
80802 *************************************************************************
80803 ** This file contains routines used for walking the parser tree for
80804 ** an SQL statement.
80805 */
80806 /* #include <stdlib.h> */
80807 /* #include <string.h> */
80808
80809
80810 /*
80811 ** Walk an expression tree.  Invoke the callback once for each node
80812 ** of the expression, while descending.  (In other words, the callback
80813 ** is invoked before visiting children.)
80814 **
80815 ** The return value from the callback should be one of the WRC_*
80816 ** constants to specify how to proceed with the walk.
80817 **
80818 **    WRC_Continue      Continue descending down the tree.
80819 **
80820 **    WRC_Prune         Do not descend into child nodes.  But allow
80821 **                      the walk to continue with sibling nodes.
80822 **
80823 **    WRC_Abort         Do no more callbacks.  Unwind the stack and
80824 **                      return the top-level walk call.
80825 **
80826 ** The return value from this routine is WRC_Abort to abandon the tree walk
80827 ** and WRC_Continue to continue.
80828 */
80829 SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
80830   int rc;
80831   if( pExpr==0 ) return WRC_Continue;
80832   testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
80833   testcase( ExprHasProperty(pExpr, EP_Reduced) );
80834   rc = pWalker->xExprCallback(pWalker, pExpr);
80835   if( rc==WRC_Continue
80836               && !ExprHasProperty(pExpr,EP_TokenOnly) ){
80837     if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
80838     if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
80839     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
80840       if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
80841     }else{
80842       if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
80843     }
80844   }
80845   return rc & WRC_Abort;
80846 }
80847
80848 /*
80849 ** Call sqlite3WalkExpr() for every expression in list p or until
80850 ** an abort request is seen.
80851 */
80852 SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
80853   int i;
80854   struct ExprList_item *pItem;
80855   if( p ){
80856     for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
80857       if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
80858     }
80859   }
80860   return WRC_Continue;
80861 }
80862
80863 /*
80864 ** Walk all expressions associated with SELECT statement p.  Do
80865 ** not invoke the SELECT callback on p, but do (of course) invoke
80866 ** any expr callbacks and SELECT callbacks that come from subqueries.
80867 ** Return WRC_Abort or WRC_Continue.
80868 */
80869 SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
80870   if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
80871   if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
80872   if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
80873   if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
80874   if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
80875   if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
80876   if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
80877   return WRC_Continue;
80878 }
80879
80880 /*
80881 ** Walk the parse trees associated with all subqueries in the
80882 ** FROM clause of SELECT statement p.  Do not invoke the select
80883 ** callback on p, but do invoke it on each FROM clause subquery
80884 ** and on any subqueries further down in the tree.  Return 
80885 ** WRC_Abort or WRC_Continue;
80886 */
80887 SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
80888   SrcList *pSrc;
80889   int i;
80890   struct SrcList_item *pItem;
80891
80892   pSrc = p->pSrc;
80893   if( ALWAYS(pSrc) ){
80894     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
80895       if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
80896         return WRC_Abort;
80897       }
80898     }
80899   }
80900   return WRC_Continue;
80901
80902
80903 /*
80904 ** Call sqlite3WalkExpr() for every expression in Select statement p.
80905 ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
80906 ** on the compound select chain, p->pPrior. 
80907 **
80908 ** If it is not NULL, the xSelectCallback() callback is invoked before
80909 ** the walk of the expressions and FROM clause. The xSelectCallback2()
80910 ** method, if it is not NULL, is invoked following the walk of the 
80911 ** expressions and FROM clause.
80912 **
80913 ** Return WRC_Continue under normal conditions.  Return WRC_Abort if
80914 ** there is an abort request.
80915 **
80916 ** If the Walker does not have an xSelectCallback() then this routine
80917 ** is a no-op returning WRC_Continue.
80918 */
80919 SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
80920   int rc;
80921   if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
80922     return WRC_Continue;
80923   }
80924   rc = WRC_Continue;
80925   pWalker->walkerDepth++;
80926   while( p ){
80927     if( pWalker->xSelectCallback ){
80928        rc = pWalker->xSelectCallback(pWalker, p);
80929        if( rc ) break;
80930     }
80931     if( sqlite3WalkSelectExpr(pWalker, p)
80932      || sqlite3WalkSelectFrom(pWalker, p)
80933     ){
80934       pWalker->walkerDepth--;
80935       return WRC_Abort;
80936     }
80937     if( pWalker->xSelectCallback2 ){
80938       pWalker->xSelectCallback2(pWalker, p);
80939     }
80940     p = p->pPrior;
80941   }
80942   pWalker->walkerDepth--;
80943   return rc & WRC_Abort;
80944 }
80945
80946 /************** End of walker.c **********************************************/
80947 /************** Begin file resolve.c *****************************************/
80948 /*
80949 ** 2008 August 18
80950 **
80951 ** The author disclaims copyright to this source code.  In place of
80952 ** a legal notice, here is a blessing:
80953 **
80954 **    May you do good and not evil.
80955 **    May you find forgiveness for yourself and forgive others.
80956 **    May you share freely, never taking more than you give.
80957 **
80958 *************************************************************************
80959 **
80960 ** This file contains routines used for walking the parser tree and
80961 ** resolve all identifiers by associating them with a particular
80962 ** table and column.
80963 */
80964 /* #include <stdlib.h> */
80965 /* #include <string.h> */
80966
80967 /*
80968 ** Walk the expression tree pExpr and increase the aggregate function
80969 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
80970 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
80971 ** outer query into an inner subquery.
80972 **
80973 ** incrAggFunctionDepth(pExpr,n) is the main routine.  incrAggDepth(..)
80974 ** is a helper function - a callback for the tree walker.
80975 */
80976 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
80977   if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
80978   return WRC_Continue;
80979 }
80980 static void incrAggFunctionDepth(Expr *pExpr, int N){
80981   if( N>0 ){
80982     Walker w;
80983     memset(&w, 0, sizeof(w));
80984     w.xExprCallback = incrAggDepth;
80985     w.u.n = N;
80986     sqlite3WalkExpr(&w, pExpr);
80987   }
80988 }
80989
80990 /*
80991 ** Turn the pExpr expression into an alias for the iCol-th column of the
80992 ** result set in pEList.
80993 **
80994 ** If the result set column is a simple column reference, then this routine
80995 ** makes an exact copy.  But for any other kind of expression, this
80996 ** routine make a copy of the result set column as the argument to the
80997 ** TK_AS operator.  The TK_AS operator causes the expression to be
80998 ** evaluated just once and then reused for each alias.
80999 **
81000 ** The reason for suppressing the TK_AS term when the expression is a simple
81001 ** column reference is so that the column reference will be recognized as
81002 ** usable by indices within the WHERE clause processing logic. 
81003 **
81004 ** The TK_AS operator is inhibited if zType[0]=='G'.  This means
81005 ** that in a GROUP BY clause, the expression is evaluated twice.  Hence:
81006 **
81007 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
81008 **
81009 ** Is equivalent to:
81010 **
81011 **     SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
81012 **
81013 ** The result of random()%5 in the GROUP BY clause is probably different
81014 ** from the result in the result-set.  On the other hand Standard SQL does
81015 ** not allow the GROUP BY clause to contain references to result-set columns.
81016 ** So this should never come up in well-formed queries.
81017 **
81018 ** If the reference is followed by a COLLATE operator, then make sure
81019 ** the COLLATE operator is preserved.  For example:
81020 **
81021 **     SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
81022 **
81023 ** Should be transformed into:
81024 **
81025 **     SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
81026 **
81027 ** The nSubquery parameter specifies how many levels of subquery the
81028 ** alias is removed from the original expression.  The usually value is
81029 ** zero but it might be more if the alias is contained within a subquery
81030 ** of the original expression.  The Expr.op2 field of TK_AGG_FUNCTION
81031 ** structures must be increased by the nSubquery amount.
81032 */
81033 static void resolveAlias(
81034   Parse *pParse,         /* Parsing context */
81035   ExprList *pEList,      /* A result set */
81036   int iCol,              /* A column in the result set.  0..pEList->nExpr-1 */
81037   Expr *pExpr,           /* Transform this into an alias to the result set */
81038   const char *zType,     /* "GROUP" or "ORDER" or "" */
81039   int nSubquery          /* Number of subqueries that the label is moving */
81040 ){
81041   Expr *pOrig;           /* The iCol-th column of the result set */
81042   Expr *pDup;            /* Copy of pOrig */
81043   sqlite3 *db;           /* The database connection */
81044
81045   assert( iCol>=0 && iCol<pEList->nExpr );
81046   pOrig = pEList->a[iCol].pExpr;
81047   assert( pOrig!=0 );
81048   assert( pOrig->flags & EP_Resolved );
81049   db = pParse->db;
81050   pDup = sqlite3ExprDup(db, pOrig, 0);
81051   if( pDup==0 ) return;
81052   if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
81053     incrAggFunctionDepth(pDup, nSubquery);
81054     pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
81055     if( pDup==0 ) return;
81056     ExprSetProperty(pDup, EP_Skip);
81057     if( pEList->a[iCol].u.x.iAlias==0 ){
81058       pEList->a[iCol].u.x.iAlias = (u16)(++pParse->nAlias);
81059     }
81060     pDup->iTable = pEList->a[iCol].u.x.iAlias;
81061   }
81062   if( pExpr->op==TK_COLLATE ){
81063     pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
81064   }
81065
81066   /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This 
81067   ** prevents ExprDelete() from deleting the Expr structure itself,
81068   ** allowing it to be repopulated by the memcpy() on the following line.
81069   ** The pExpr->u.zToken might point into memory that will be freed by the
81070   ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
81071   ** make a copy of the token before doing the sqlite3DbFree().
81072   */
81073   ExprSetProperty(pExpr, EP_Static);
81074   sqlite3ExprDelete(db, pExpr);
81075   memcpy(pExpr, pDup, sizeof(*pExpr));
81076   if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
81077     assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
81078     pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
81079     pExpr->flags |= EP_MemToken;
81080   }
81081   sqlite3DbFree(db, pDup);
81082 }
81083
81084
81085 /*
81086 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
81087 **
81088 ** Return FALSE if the USING clause is NULL or if it does not contain
81089 ** zCol.
81090 */
81091 static int nameInUsingClause(IdList *pUsing, const char *zCol){
81092   if( pUsing ){
81093     int k;
81094     for(k=0; k<pUsing->nId; k++){
81095       if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
81096     }
81097   }
81098   return 0;
81099 }
81100
81101 /*
81102 ** Subqueries stores the original database, table and column names for their
81103 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
81104 ** Check to see if the zSpan given to this routine matches the zDb, zTab,
81105 ** and zCol.  If any of zDb, zTab, and zCol are NULL then those fields will
81106 ** match anything.
81107 */
81108 SQLITE_PRIVATE int sqlite3MatchSpanName(
81109   const char *zSpan,
81110   const char *zCol,
81111   const char *zTab,
81112   const char *zDb
81113 ){
81114   int n;
81115   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
81116   if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
81117     return 0;
81118   }
81119   zSpan += n+1;
81120   for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
81121   if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
81122     return 0;
81123   }
81124   zSpan += n+1;
81125   if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
81126     return 0;
81127   }
81128   return 1;
81129 }
81130
81131 /*
81132 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
81133 ** that name in the set of source tables in pSrcList and make the pExpr 
81134 ** expression node refer back to that source column.  The following changes
81135 ** are made to pExpr:
81136 **
81137 **    pExpr->iDb           Set the index in db->aDb[] of the database X
81138 **                         (even if X is implied).
81139 **    pExpr->iTable        Set to the cursor number for the table obtained
81140 **                         from pSrcList.
81141 **    pExpr->pTab          Points to the Table structure of X.Y (even if
81142 **                         X and/or Y are implied.)
81143 **    pExpr->iColumn       Set to the column number within the table.
81144 **    pExpr->op            Set to TK_COLUMN.
81145 **    pExpr->pLeft         Any expression this points to is deleted
81146 **    pExpr->pRight        Any expression this points to is deleted.
81147 **
81148 ** The zDb variable is the name of the database (the "X").  This value may be
81149 ** NULL meaning that name is of the form Y.Z or Z.  Any available database
81150 ** can be used.  The zTable variable is the name of the table (the "Y").  This
81151 ** value can be NULL if zDb is also NULL.  If zTable is NULL it
81152 ** means that the form of the name is Z and that columns from any table
81153 ** can be used.
81154 **
81155 ** If the name cannot be resolved unambiguously, leave an error message
81156 ** in pParse and return WRC_Abort.  Return WRC_Prune on success.
81157 */
81158 static int lookupName(
81159   Parse *pParse,       /* The parsing context */
81160   const char *zDb,     /* Name of the database containing table, or NULL */
81161   const char *zTab,    /* Name of table containing column, or NULL */
81162   const char *zCol,    /* Name of the column. */
81163   NameContext *pNC,    /* The name context used to resolve the name */
81164   Expr *pExpr          /* Make this EXPR node point to the selected column */
81165 ){
81166   int i, j;                         /* Loop counters */
81167   int cnt = 0;                      /* Number of matching column names */
81168   int cntTab = 0;                   /* Number of matching table names */
81169   int nSubquery = 0;                /* How many levels of subquery */
81170   sqlite3 *db = pParse->db;         /* The database connection */
81171   struct SrcList_item *pItem;       /* Use for looping over pSrcList items */
81172   struct SrcList_item *pMatch = 0;  /* The matching pSrcList item */
81173   NameContext *pTopNC = pNC;        /* First namecontext in the list */
81174   Schema *pSchema = 0;              /* Schema of the expression */
81175   int isTrigger = 0;                /* True if resolved to a trigger column */
81176   Table *pTab = 0;                  /* Table hold the row */
81177   Column *pCol;                     /* A column of pTab */
81178
81179   assert( pNC );     /* the name context cannot be NULL. */
81180   assert( zCol );    /* The Z in X.Y.Z cannot be NULL */
81181   assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
81182
81183   /* Initialize the node to no-match */
81184   pExpr->iTable = -1;
81185   pExpr->pTab = 0;
81186   ExprSetVVAProperty(pExpr, EP_NoReduce);
81187
81188   /* Translate the schema name in zDb into a pointer to the corresponding
81189   ** schema.  If not found, pSchema will remain NULL and nothing will match
81190   ** resulting in an appropriate error message toward the end of this routine
81191   */
81192   if( zDb ){
81193     testcase( pNC->ncFlags & NC_PartIdx );
81194     testcase( pNC->ncFlags & NC_IsCheck );
81195     if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
81196       /* Silently ignore database qualifiers inside CHECK constraints and
81197       ** partial indices.  Do not raise errors because that might break
81198       ** legacy and because it does not hurt anything to just ignore the
81199       ** database name. */
81200       zDb = 0;
81201     }else{
81202       for(i=0; i<db->nDb; i++){
81203         assert( db->aDb[i].zName );
81204         if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
81205           pSchema = db->aDb[i].pSchema;
81206           break;
81207         }
81208       }
81209     }
81210   }
81211
81212   /* Start at the inner-most context and move outward until a match is found */
81213   while( pNC && cnt==0 ){
81214     ExprList *pEList;
81215     SrcList *pSrcList = pNC->pSrcList;
81216
81217     if( pSrcList ){
81218       for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
81219         pTab = pItem->pTab;
81220         assert( pTab!=0 && pTab->zName!=0 );
81221         assert( pTab->nCol>0 );
81222         if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
81223           int hit = 0;
81224           pEList = pItem->pSelect->pEList;
81225           for(j=0; j<pEList->nExpr; j++){
81226             if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
81227               cnt++;
81228               cntTab = 2;
81229               pMatch = pItem;
81230               pExpr->iColumn = j;
81231               hit = 1;
81232             }
81233           }
81234           if( hit || zTab==0 ) continue;
81235         }
81236         if( zDb && pTab->pSchema!=pSchema ){
81237           continue;
81238         }
81239         if( zTab ){
81240           const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
81241           assert( zTabName!=0 );
81242           if( sqlite3StrICmp(zTabName, zTab)!=0 ){
81243             continue;
81244           }
81245         }
81246         if( 0==(cntTab++) ){
81247           pMatch = pItem;
81248         }
81249         for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
81250           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
81251             /* If there has been exactly one prior match and this match
81252             ** is for the right-hand table of a NATURAL JOIN or is in a 
81253             ** USING clause, then skip this match.
81254             */
81255             if( cnt==1 ){
81256               if( pItem->jointype & JT_NATURAL ) continue;
81257               if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
81258             }
81259             cnt++;
81260             pMatch = pItem;
81261             /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
81262             pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
81263             break;
81264           }
81265         }
81266       }
81267       if( pMatch ){
81268         pExpr->iTable = pMatch->iCursor;
81269         pExpr->pTab = pMatch->pTab;
81270         /* RIGHT JOIN not (yet) supported */
81271         assert( (pMatch->jointype & JT_RIGHT)==0 );
81272         if( (pMatch->jointype & JT_LEFT)!=0 ){
81273           ExprSetProperty(pExpr, EP_CanBeNull);
81274         }
81275         pSchema = pExpr->pTab->pSchema;
81276       }
81277     } /* if( pSrcList ) */
81278
81279 #ifndef SQLITE_OMIT_TRIGGER
81280     /* If we have not already resolved the name, then maybe 
81281     ** it is a new.* or old.* trigger argument reference
81282     */
81283     if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
81284       int op = pParse->eTriggerOp;
81285       assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
81286       if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
81287         pExpr->iTable = 1;
81288         pTab = pParse->pTriggerTab;
81289       }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
81290         pExpr->iTable = 0;
81291         pTab = pParse->pTriggerTab;
81292       }else{
81293         pTab = 0;
81294       }
81295
81296       if( pTab ){ 
81297         int iCol;
81298         pSchema = pTab->pSchema;
81299         cntTab++;
81300         for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
81301           if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
81302             if( iCol==pTab->iPKey ){
81303               iCol = -1;
81304             }
81305             break;
81306           }
81307         }
81308         if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && HasRowid(pTab) ){
81309           /* IMP: R-51414-32910 */
81310           /* IMP: R-44911-55124 */
81311           iCol = -1;
81312         }
81313         if( iCol<pTab->nCol ){
81314           cnt++;
81315           if( iCol<0 ){
81316             pExpr->affinity = SQLITE_AFF_INTEGER;
81317           }else if( pExpr->iTable==0 ){
81318             testcase( iCol==31 );
81319             testcase( iCol==32 );
81320             pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
81321           }else{
81322             testcase( iCol==31 );
81323             testcase( iCol==32 );
81324             pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
81325           }
81326           pExpr->iColumn = (i16)iCol;
81327           pExpr->pTab = pTab;
81328           isTrigger = 1;
81329         }
81330       }
81331     }
81332 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
81333
81334     /*
81335     ** Perhaps the name is a reference to the ROWID
81336     */
81337     if( cnt==0 && cntTab==1 && pMatch && sqlite3IsRowid(zCol)
81338      && HasRowid(pMatch->pTab) ){
81339       cnt = 1;
81340       pExpr->iColumn = -1;     /* IMP: R-44911-55124 */
81341       pExpr->affinity = SQLITE_AFF_INTEGER;
81342     }
81343
81344     /*
81345     ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
81346     ** might refer to an result-set alias.  This happens, for example, when
81347     ** we are resolving names in the WHERE clause of the following command:
81348     **
81349     **     SELECT a+b AS x FROM table WHERE x<10;
81350     **
81351     ** In cases like this, replace pExpr with a copy of the expression that
81352     ** forms the result set entry ("a+b" in the example) and return immediately.
81353     ** Note that the expression in the result set should have already been
81354     ** resolved by the time the WHERE clause is resolved.
81355     **
81356     ** The ability to use an output result-set column in the WHERE, GROUP BY,
81357     ** or HAVING clauses, or as part of a larger expression in the ORDRE BY
81358     ** clause is not standard SQL.  This is a (goofy) SQLite extension, that
81359     ** is supported for backwards compatibility only.  TO DO: Issue a warning
81360     ** on sqlite3_log() whenever the capability is used.
81361     */
81362     if( (pEList = pNC->pEList)!=0
81363      && zTab==0
81364      && cnt==0
81365     ){
81366       for(j=0; j<pEList->nExpr; j++){
81367         char *zAs = pEList->a[j].zName;
81368         if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
81369           Expr *pOrig;
81370           assert( pExpr->pLeft==0 && pExpr->pRight==0 );
81371           assert( pExpr->x.pList==0 );
81372           assert( pExpr->x.pSelect==0 );
81373           pOrig = pEList->a[j].pExpr;
81374           if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
81375             sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
81376             return WRC_Abort;
81377           }
81378           resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
81379           cnt = 1;
81380           pMatch = 0;
81381           assert( zTab==0 && zDb==0 );
81382           goto lookupname_end;
81383         }
81384       } 
81385     }
81386
81387     /* Advance to the next name context.  The loop will exit when either
81388     ** we have a match (cnt>0) or when we run out of name contexts.
81389     */
81390     if( cnt==0 ){
81391       pNC = pNC->pNext;
81392       nSubquery++;
81393     }
81394   }
81395
81396   /*
81397   ** If X and Y are NULL (in other words if only the column name Z is
81398   ** supplied) and the value of Z is enclosed in double-quotes, then
81399   ** Z is a string literal if it doesn't match any column names.  In that
81400   ** case, we need to return right away and not make any changes to
81401   ** pExpr.
81402   **
81403   ** Because no reference was made to outer contexts, the pNC->nRef
81404   ** fields are not changed in any context.
81405   */
81406   if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
81407     pExpr->op = TK_STRING;
81408     pExpr->pTab = 0;
81409     return WRC_Prune;
81410   }
81411
81412   /*
81413   ** cnt==0 means there was not match.  cnt>1 means there were two or
81414   ** more matches.  Either way, we have an error.
81415   */
81416   if( cnt!=1 ){
81417     const char *zErr;
81418     zErr = cnt==0 ? "no such column" : "ambiguous column name";
81419     if( zDb ){
81420       sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
81421     }else if( zTab ){
81422       sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
81423     }else{
81424       sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
81425     }
81426     pParse->checkSchema = 1;
81427     pTopNC->nErr++;
81428   }
81429
81430   /* If a column from a table in pSrcList is referenced, then record
81431   ** this fact in the pSrcList.a[].colUsed bitmask.  Column 0 causes
81432   ** bit 0 to be set.  Column 1 sets bit 1.  And so forth.  If the
81433   ** column number is greater than the number of bits in the bitmask
81434   ** then set the high-order bit of the bitmask.
81435   */
81436   if( pExpr->iColumn>=0 && pMatch!=0 ){
81437     int n = pExpr->iColumn;
81438     testcase( n==BMS-1 );
81439     if( n>=BMS ){
81440       n = BMS-1;
81441     }
81442     assert( pMatch->iCursor==pExpr->iTable );
81443     pMatch->colUsed |= ((Bitmask)1)<<n;
81444   }
81445
81446   /* Clean up and return
81447   */
81448   sqlite3ExprDelete(db, pExpr->pLeft);
81449   pExpr->pLeft = 0;
81450   sqlite3ExprDelete(db, pExpr->pRight);
81451   pExpr->pRight = 0;
81452   pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
81453 lookupname_end:
81454   if( cnt==1 ){
81455     assert( pNC!=0 );
81456     if( pExpr->op!=TK_AS ){
81457       sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
81458     }
81459     /* Increment the nRef value on all name contexts from TopNC up to
81460     ** the point where the name matched. */
81461     for(;;){
81462       assert( pTopNC!=0 );
81463       pTopNC->nRef++;
81464       if( pTopNC==pNC ) break;
81465       pTopNC = pTopNC->pNext;
81466     }
81467     return WRC_Prune;
81468   } else {
81469     return WRC_Abort;
81470   }
81471 }
81472
81473 /*
81474 ** Allocate and return a pointer to an expression to load the column iCol
81475 ** from datasource iSrc in SrcList pSrc.
81476 */
81477 SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
81478   Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
81479   if( p ){
81480     struct SrcList_item *pItem = &pSrc->a[iSrc];
81481     p->pTab = pItem->pTab;
81482     p->iTable = pItem->iCursor;
81483     if( p->pTab->iPKey==iCol ){
81484       p->iColumn = -1;
81485     }else{
81486       p->iColumn = (ynVar)iCol;
81487       testcase( iCol==BMS );
81488       testcase( iCol==BMS-1 );
81489       pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
81490     }
81491     ExprSetProperty(p, EP_Resolved);
81492   }
81493   return p;
81494 }
81495
81496 /*
81497 ** Report an error that an expression is not valid for a partial index WHERE
81498 ** clause.
81499 */
81500 static void notValidPartIdxWhere(
81501   Parse *pParse,       /* Leave error message here */
81502   NameContext *pNC,    /* The name context */
81503   const char *zMsg     /* Type of error */
81504 ){
81505   if( (pNC->ncFlags & NC_PartIdx)!=0 ){
81506     sqlite3ErrorMsg(pParse, "%s prohibited in partial index WHERE clauses",
81507                     zMsg);
81508   }
81509 }
81510
81511 #ifndef SQLITE_OMIT_CHECK
81512 /*
81513 ** Report an error that an expression is not valid for a CHECK constraint.
81514 */
81515 static void notValidCheckConstraint(
81516   Parse *pParse,       /* Leave error message here */
81517   NameContext *pNC,    /* The name context */
81518   const char *zMsg     /* Type of error */
81519 ){
81520   if( (pNC->ncFlags & NC_IsCheck)!=0 ){
81521     sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg);
81522   }
81523 }
81524 #else
81525 # define notValidCheckConstraint(P,N,M)
81526 #endif
81527
81528 /*
81529 ** Expression p should encode a floating point value between 1.0 and 0.0.
81530 ** Return 1024 times this value.  Or return -1 if p is not a floating point
81531 ** value between 1.0 and 0.0.
81532 */
81533 static int exprProbability(Expr *p){
81534   double r = -1.0;
81535   if( p->op!=TK_FLOAT ) return -1;
81536   sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
81537   assert( r>=0.0 );
81538   if( r>1.0 ) return -1;
81539   return (int)(r*134217728.0);
81540 }
81541
81542 /*
81543 ** This routine is callback for sqlite3WalkExpr().
81544 **
81545 ** Resolve symbolic names into TK_COLUMN operators for the current
81546 ** node in the expression tree.  Return 0 to continue the search down
81547 ** the tree or 2 to abort the tree walk.
81548 **
81549 ** This routine also does error checking and name resolution for
81550 ** function names.  The operator for aggregate functions is changed
81551 ** to TK_AGG_FUNCTION.
81552 */
81553 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
81554   NameContext *pNC;
81555   Parse *pParse;
81556
81557   pNC = pWalker->u.pNC;
81558   assert( pNC!=0 );
81559   pParse = pNC->pParse;
81560   assert( pParse==pWalker->pParse );
81561
81562   if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
81563   ExprSetProperty(pExpr, EP_Resolved);
81564 #ifndef NDEBUG
81565   if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
81566     SrcList *pSrcList = pNC->pSrcList;
81567     int i;
81568     for(i=0; i<pNC->pSrcList->nSrc; i++){
81569       assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
81570     }
81571   }
81572 #endif
81573   switch( pExpr->op ){
81574
81575 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
81576     /* The special operator TK_ROW means use the rowid for the first
81577     ** column in the FROM clause.  This is used by the LIMIT and ORDER BY
81578     ** clause processing on UPDATE and DELETE statements.
81579     */
81580     case TK_ROW: {
81581       SrcList *pSrcList = pNC->pSrcList;
81582       struct SrcList_item *pItem;
81583       assert( pSrcList && pSrcList->nSrc==1 );
81584       pItem = pSrcList->a; 
81585       pExpr->op = TK_COLUMN;
81586       pExpr->pTab = pItem->pTab;
81587       pExpr->iTable = pItem->iCursor;
81588       pExpr->iColumn = -1;
81589       pExpr->affinity = SQLITE_AFF_INTEGER;
81590       break;
81591     }
81592 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT)
81593           && !defined(SQLITE_OMIT_SUBQUERY) */
81594
81595     /* A lone identifier is the name of a column.
81596     */
81597     case TK_ID: {
81598       return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
81599     }
81600   
81601     /* A table name and column name:     ID.ID
81602     ** Or a database, table and column:  ID.ID.ID
81603     */
81604     case TK_DOT: {
81605       const char *zColumn;
81606       const char *zTable;
81607       const char *zDb;
81608       Expr *pRight;
81609
81610       /* if( pSrcList==0 ) break; */
81611       pRight = pExpr->pRight;
81612       if( pRight->op==TK_ID ){
81613         zDb = 0;
81614         zTable = pExpr->pLeft->u.zToken;
81615         zColumn = pRight->u.zToken;
81616       }else{
81617         assert( pRight->op==TK_DOT );
81618         zDb = pExpr->pLeft->u.zToken;
81619         zTable = pRight->pLeft->u.zToken;
81620         zColumn = pRight->pRight->u.zToken;
81621       }
81622       return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
81623     }
81624
81625     /* Resolve function names
81626     */
81627     case TK_FUNCTION: {
81628       ExprList *pList = pExpr->x.pList;    /* The argument list */
81629       int n = pList ? pList->nExpr : 0;    /* Number of arguments */
81630       int no_such_func = 0;       /* True if no such function exists */
81631       int wrong_num_args = 0;     /* True if wrong number of arguments */
81632       int is_agg = 0;             /* True if is an aggregate function */
81633       int auth;                   /* Authorization to use the function */
81634       int nId;                    /* Number of characters in function name */
81635       const char *zId;            /* The function name. */
81636       FuncDef *pDef;              /* Information about the function */
81637       u8 enc = ENC(pParse->db);   /* The database encoding */
81638
81639       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
81640       notValidPartIdxWhere(pParse, pNC, "functions");
81641       zId = pExpr->u.zToken;
81642       nId = sqlite3Strlen30(zId);
81643       pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
81644       if( pDef==0 ){
81645         pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
81646         if( pDef==0 ){
81647           no_such_func = 1;
81648         }else{
81649           wrong_num_args = 1;
81650         }
81651       }else{
81652         is_agg = pDef->xFunc==0;
81653         if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
81654           ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
81655           if( n==2 ){
81656             pExpr->iTable = exprProbability(pList->a[1].pExpr);
81657             if( pExpr->iTable<0 ){
81658               sqlite3ErrorMsg(pParse,
81659                 "second argument to likelihood() must be a "
81660                 "constant between 0.0 and 1.0");
81661               pNC->nErr++;
81662             }
81663           }else{
81664             /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
81665             ** equivalent to likelihood(X, 0.0625).
81666             ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
81667             ** short-hand for likelihood(X,0.0625).
81668             ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
81669             ** for likelihood(X,0.9375).
81670             ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
81671             ** to likelihood(X,0.9375). */
81672             /* TUNING: unlikely() probability is 0.0625.  likely() is 0.9375 */
81673             pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
81674           }             
81675         }
81676 #ifndef SQLITE_OMIT_AUTHORIZATION
81677         auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
81678         if( auth!=SQLITE_OK ){
81679           if( auth==SQLITE_DENY ){
81680             sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
81681                                     pDef->zName);
81682             pNC->nErr++;
81683           }
81684           pExpr->op = TK_NULL;
81685           return WRC_Prune;
81686         }
81687 #endif
81688         if( pDef->funcFlags & SQLITE_FUNC_CONSTANT ){
81689           ExprSetProperty(pExpr,EP_ConstFunc);
81690         }
81691       }
81692       if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
81693         sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
81694         pNC->nErr++;
81695         is_agg = 0;
81696       }else if( no_such_func && pParse->db->init.busy==0 ){
81697         sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
81698         pNC->nErr++;
81699       }else if( wrong_num_args ){
81700         sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
81701              nId, zId);
81702         pNC->nErr++;
81703       }
81704       if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
81705       sqlite3WalkExprList(pWalker, pList);
81706       if( is_agg ){
81707         NameContext *pNC2 = pNC;
81708         pExpr->op = TK_AGG_FUNCTION;
81709         pExpr->op2 = 0;
81710         while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
81711           pExpr->op2++;
81712           pNC2 = pNC2->pNext;
81713         }
81714         assert( pDef!=0 );
81715         if( pNC2 ){
81716           assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
81717           testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
81718           pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
81719
81720         }
81721         pNC->ncFlags |= NC_AllowAgg;
81722       }
81723       /* FIX ME:  Compute pExpr->affinity based on the expected return
81724       ** type of the function 
81725       */
81726       return WRC_Prune;
81727     }
81728 #ifndef SQLITE_OMIT_SUBQUERY
81729     case TK_SELECT:
81730     case TK_EXISTS:  testcase( pExpr->op==TK_EXISTS );
81731 #endif
81732     case TK_IN: {
81733       testcase( pExpr->op==TK_IN );
81734       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
81735         int nRef = pNC->nRef;
81736         notValidCheckConstraint(pParse, pNC, "subqueries");
81737         notValidPartIdxWhere(pParse, pNC, "subqueries");
81738         sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
81739         assert( pNC->nRef>=nRef );
81740         if( nRef!=pNC->nRef ){
81741           ExprSetProperty(pExpr, EP_VarSelect);
81742         }
81743       }
81744       break;
81745     }
81746     case TK_VARIABLE: {
81747       notValidCheckConstraint(pParse, pNC, "parameters");
81748       notValidPartIdxWhere(pParse, pNC, "parameters");
81749       break;
81750     }
81751   }
81752   return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
81753 }
81754
81755 /*
81756 ** pEList is a list of expressions which are really the result set of the
81757 ** a SELECT statement.  pE is a term in an ORDER BY or GROUP BY clause.
81758 ** This routine checks to see if pE is a simple identifier which corresponds
81759 ** to the AS-name of one of the terms of the expression list.  If it is,
81760 ** this routine return an integer between 1 and N where N is the number of
81761 ** elements in pEList, corresponding to the matching entry.  If there is
81762 ** no match, or if pE is not a simple identifier, then this routine
81763 ** return 0.
81764 **
81765 ** pEList has been resolved.  pE has not.
81766 */
81767 static int resolveAsName(
81768   Parse *pParse,     /* Parsing context for error messages */
81769   ExprList *pEList,  /* List of expressions to scan */
81770   Expr *pE           /* Expression we are trying to match */
81771 ){
81772   int i;             /* Loop counter */
81773
81774   UNUSED_PARAMETER(pParse);
81775
81776   if( pE->op==TK_ID ){
81777     char *zCol = pE->u.zToken;
81778     for(i=0; i<pEList->nExpr; i++){
81779       char *zAs = pEList->a[i].zName;
81780       if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
81781         return i+1;
81782       }
81783     }
81784   }
81785   return 0;
81786 }
81787
81788 /*
81789 ** pE is a pointer to an expression which is a single term in the
81790 ** ORDER BY of a compound SELECT.  The expression has not been
81791 ** name resolved.
81792 **
81793 ** At the point this routine is called, we already know that the
81794 ** ORDER BY term is not an integer index into the result set.  That
81795 ** case is handled by the calling routine.
81796 **
81797 ** Attempt to match pE against result set columns in the left-most
81798 ** SELECT statement.  Return the index i of the matching column,
81799 ** as an indication to the caller that it should sort by the i-th column.
81800 ** The left-most column is 1.  In other words, the value returned is the
81801 ** same integer value that would be used in the SQL statement to indicate
81802 ** the column.
81803 **
81804 ** If there is no match, return 0.  Return -1 if an error occurs.
81805 */
81806 static int resolveOrderByTermToExprList(
81807   Parse *pParse,     /* Parsing context for error messages */
81808   Select *pSelect,   /* The SELECT statement with the ORDER BY clause */
81809   Expr *pE           /* The specific ORDER BY term */
81810 ){
81811   int i;             /* Loop counter */
81812   ExprList *pEList;  /* The columns of the result set */
81813   NameContext nc;    /* Name context for resolving pE */
81814   sqlite3 *db;       /* Database connection */
81815   int rc;            /* Return code from subprocedures */
81816   u8 savedSuppErr;   /* Saved value of db->suppressErr */
81817
81818   assert( sqlite3ExprIsInteger(pE, &i)==0 );
81819   pEList = pSelect->pEList;
81820
81821   /* Resolve all names in the ORDER BY term expression
81822   */
81823   memset(&nc, 0, sizeof(nc));
81824   nc.pParse = pParse;
81825   nc.pSrcList = pSelect->pSrc;
81826   nc.pEList = pEList;
81827   nc.ncFlags = NC_AllowAgg;
81828   nc.nErr = 0;
81829   db = pParse->db;
81830   savedSuppErr = db->suppressErr;
81831   db->suppressErr = 1;
81832   rc = sqlite3ResolveExprNames(&nc, pE);
81833   db->suppressErr = savedSuppErr;
81834   if( rc ) return 0;
81835
81836   /* Try to match the ORDER BY expression against an expression
81837   ** in the result set.  Return an 1-based index of the matching
81838   ** result-set entry.
81839   */
81840   for(i=0; i<pEList->nExpr; i++){
81841     if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
81842       return i+1;
81843     }
81844   }
81845
81846   /* If no match, return 0. */
81847   return 0;
81848 }
81849
81850 /*
81851 ** Generate an ORDER BY or GROUP BY term out-of-range error.
81852 */
81853 static void resolveOutOfRangeError(
81854   Parse *pParse,         /* The error context into which to write the error */
81855   const char *zType,     /* "ORDER" or "GROUP" */
81856   int i,                 /* The index (1-based) of the term out of range */
81857   int mx                 /* Largest permissible value of i */
81858 ){
81859   sqlite3ErrorMsg(pParse, 
81860     "%r %s BY term out of range - should be "
81861     "between 1 and %d", i, zType, mx);
81862 }
81863
81864 /*
81865 ** Analyze the ORDER BY clause in a compound SELECT statement.   Modify
81866 ** each term of the ORDER BY clause is a constant integer between 1
81867 ** and N where N is the number of columns in the compound SELECT.
81868 **
81869 ** ORDER BY terms that are already an integer between 1 and N are
81870 ** unmodified.  ORDER BY terms that are integers outside the range of
81871 ** 1 through N generate an error.  ORDER BY terms that are expressions
81872 ** are matched against result set expressions of compound SELECT
81873 ** beginning with the left-most SELECT and working toward the right.
81874 ** At the first match, the ORDER BY expression is transformed into
81875 ** the integer column number.
81876 **
81877 ** Return the number of errors seen.
81878 */
81879 static int resolveCompoundOrderBy(
81880   Parse *pParse,        /* Parsing context.  Leave error messages here */
81881   Select *pSelect       /* The SELECT statement containing the ORDER BY */
81882 ){
81883   int i;
81884   ExprList *pOrderBy;
81885   ExprList *pEList;
81886   sqlite3 *db;
81887   int moreToDo = 1;
81888
81889   pOrderBy = pSelect->pOrderBy;
81890   if( pOrderBy==0 ) return 0;
81891   db = pParse->db;
81892 #if SQLITE_MAX_COLUMN
81893   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
81894     sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
81895     return 1;
81896   }
81897 #endif
81898   for(i=0; i<pOrderBy->nExpr; i++){
81899     pOrderBy->a[i].done = 0;
81900   }
81901   pSelect->pNext = 0;
81902   while( pSelect->pPrior ){
81903     pSelect->pPrior->pNext = pSelect;
81904     pSelect = pSelect->pPrior;
81905   }
81906   while( pSelect && moreToDo ){
81907     struct ExprList_item *pItem;
81908     moreToDo = 0;
81909     pEList = pSelect->pEList;
81910     assert( pEList!=0 );
81911     for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
81912       int iCol = -1;
81913       Expr *pE, *pDup;
81914       if( pItem->done ) continue;
81915       pE = sqlite3ExprSkipCollate(pItem->pExpr);
81916       if( sqlite3ExprIsInteger(pE, &iCol) ){
81917         if( iCol<=0 || iCol>pEList->nExpr ){
81918           resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
81919           return 1;
81920         }
81921       }else{
81922         iCol = resolveAsName(pParse, pEList, pE);
81923         if( iCol==0 ){
81924           pDup = sqlite3ExprDup(db, pE, 0);
81925           if( !db->mallocFailed ){
81926             assert(pDup);
81927             iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
81928           }
81929           sqlite3ExprDelete(db, pDup);
81930         }
81931       }
81932       if( iCol>0 ){
81933         /* Convert the ORDER BY term into an integer column number iCol,
81934         ** taking care to preserve the COLLATE clause if it exists */
81935         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
81936         if( pNew==0 ) return 1;
81937         pNew->flags |= EP_IntValue;
81938         pNew->u.iValue = iCol;
81939         if( pItem->pExpr==pE ){
81940           pItem->pExpr = pNew;
81941         }else{
81942           assert( pItem->pExpr->op==TK_COLLATE );
81943           assert( pItem->pExpr->pLeft==pE );
81944           pItem->pExpr->pLeft = pNew;
81945         }
81946         sqlite3ExprDelete(db, pE);
81947         pItem->u.x.iOrderByCol = (u16)iCol;
81948         pItem->done = 1;
81949       }else{
81950         moreToDo = 1;
81951       }
81952     }
81953     pSelect = pSelect->pNext;
81954   }
81955   for(i=0; i<pOrderBy->nExpr; i++){
81956     if( pOrderBy->a[i].done==0 ){
81957       sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
81958             "column in the result set", i+1);
81959       return 1;
81960     }
81961   }
81962   return 0;
81963 }
81964
81965 /*
81966 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
81967 ** the SELECT statement pSelect.  If any term is reference to a
81968 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
81969 ** field) then convert that term into a copy of the corresponding result set
81970 ** column.
81971 **
81972 ** If any errors are detected, add an error message to pParse and
81973 ** return non-zero.  Return zero if no errors are seen.
81974 */
81975 SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
81976   Parse *pParse,        /* Parsing context.  Leave error messages here */
81977   Select *pSelect,      /* The SELECT statement containing the clause */
81978   ExprList *pOrderBy,   /* The ORDER BY or GROUP BY clause to be processed */
81979   const char *zType     /* "ORDER" or "GROUP" */
81980 ){
81981   int i;
81982   sqlite3 *db = pParse->db;
81983   ExprList *pEList;
81984   struct ExprList_item *pItem;
81985
81986   if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
81987 #if SQLITE_MAX_COLUMN
81988   if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
81989     sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
81990     return 1;
81991   }
81992 #endif
81993   pEList = pSelect->pEList;
81994   assert( pEList!=0 );  /* sqlite3SelectNew() guarantees this */
81995   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
81996     if( pItem->u.x.iOrderByCol ){
81997       if( pItem->u.x.iOrderByCol>pEList->nExpr ){
81998         resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
81999         return 1;
82000       }
82001       resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,
82002                    zType,0);
82003     }
82004   }
82005   return 0;
82006 }
82007
82008 /*
82009 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
82010 ** The Name context of the SELECT statement is pNC.  zType is either
82011 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
82012 **
82013 ** This routine resolves each term of the clause into an expression.
82014 ** If the order-by term is an integer I between 1 and N (where N is the
82015 ** number of columns in the result set of the SELECT) then the expression
82016 ** in the resolution is a copy of the I-th result-set expression.  If
82017 ** the order-by term is an identifier that corresponds to the AS-name of
82018 ** a result-set expression, then the term resolves to a copy of the
82019 ** result-set expression.  Otherwise, the expression is resolved in
82020 ** the usual way - using sqlite3ResolveExprNames().
82021 **
82022 ** This routine returns the number of errors.  If errors occur, then
82023 ** an appropriate error message might be left in pParse.  (OOM errors
82024 ** excepted.)
82025 */
82026 static int resolveOrderGroupBy(
82027   NameContext *pNC,     /* The name context of the SELECT statement */
82028   Select *pSelect,      /* The SELECT statement holding pOrderBy */
82029   ExprList *pOrderBy,   /* An ORDER BY or GROUP BY clause to resolve */
82030   const char *zType     /* Either "ORDER" or "GROUP", as appropriate */
82031 ){
82032   int i, j;                      /* Loop counters */
82033   int iCol;                      /* Column number */
82034   struct ExprList_item *pItem;   /* A term of the ORDER BY clause */
82035   Parse *pParse;                 /* Parsing context */
82036   int nResult;                   /* Number of terms in the result set */
82037
82038   if( pOrderBy==0 ) return 0;
82039   nResult = pSelect->pEList->nExpr;
82040   pParse = pNC->pParse;
82041   for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
82042     Expr *pE = pItem->pExpr;
82043     Expr *pE2 = sqlite3ExprSkipCollate(pE);
82044     if( zType[0]!='G' ){
82045       iCol = resolveAsName(pParse, pSelect->pEList, pE2);
82046       if( iCol>0 ){
82047         /* If an AS-name match is found, mark this ORDER BY column as being
82048         ** a copy of the iCol-th result-set column.  The subsequent call to
82049         ** sqlite3ResolveOrderGroupBy() will convert the expression to a
82050         ** copy of the iCol-th result-set expression. */
82051         pItem->u.x.iOrderByCol = (u16)iCol;
82052         continue;
82053       }
82054     }
82055     if( sqlite3ExprIsInteger(pE2, &iCol) ){
82056       /* The ORDER BY term is an integer constant.  Again, set the column
82057       ** number so that sqlite3ResolveOrderGroupBy() will convert the
82058       ** order-by term to a copy of the result-set expression */
82059       if( iCol<1 || iCol>0xffff ){
82060         resolveOutOfRangeError(pParse, zType, i+1, nResult);
82061         return 1;
82062       }
82063       pItem->u.x.iOrderByCol = (u16)iCol;
82064       continue;
82065     }
82066
82067     /* Otherwise, treat the ORDER BY term as an ordinary expression */
82068     pItem->u.x.iOrderByCol = 0;
82069     if( sqlite3ResolveExprNames(pNC, pE) ){
82070       return 1;
82071     }
82072     for(j=0; j<pSelect->pEList->nExpr; j++){
82073       if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
82074         pItem->u.x.iOrderByCol = j+1;
82075       }
82076     }
82077   }
82078   return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
82079 }
82080
82081 /*
82082 ** Resolve names in the SELECT statement p and all of its descendants.
82083 */
82084 static int resolveSelectStep(Walker *pWalker, Select *p){
82085   NameContext *pOuterNC;  /* Context that contains this SELECT */
82086   NameContext sNC;        /* Name context of this SELECT */
82087   int isCompound;         /* True if p is a compound select */
82088   int nCompound;          /* Number of compound terms processed so far */
82089   Parse *pParse;          /* Parsing context */
82090   ExprList *pEList;       /* Result set expression list */
82091   int i;                  /* Loop counter */
82092   ExprList *pGroupBy;     /* The GROUP BY clause */
82093   Select *pLeftmost;      /* Left-most of SELECT of a compound */
82094   sqlite3 *db;            /* Database connection */
82095   
82096
82097   assert( p!=0 );
82098   if( p->selFlags & SF_Resolved ){
82099     return WRC_Prune;
82100   }
82101   pOuterNC = pWalker->u.pNC;
82102   pParse = pWalker->pParse;
82103   db = pParse->db;
82104
82105   /* Normally sqlite3SelectExpand() will be called first and will have
82106   ** already expanded this SELECT.  However, if this is a subquery within
82107   ** an expression, sqlite3ResolveExprNames() will be called without a
82108   ** prior call to sqlite3SelectExpand().  When that happens, let
82109   ** sqlite3SelectPrep() do all of the processing for this SELECT.
82110   ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
82111   ** this routine in the correct order.
82112   */
82113   if( (p->selFlags & SF_Expanded)==0 ){
82114     sqlite3SelectPrep(pParse, p, pOuterNC);
82115     return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
82116   }
82117
82118   isCompound = p->pPrior!=0;
82119   nCompound = 0;
82120   pLeftmost = p;
82121   while( p ){
82122     assert( (p->selFlags & SF_Expanded)!=0 );
82123     assert( (p->selFlags & SF_Resolved)==0 );
82124     p->selFlags |= SF_Resolved;
82125
82126     /* Resolve the expressions in the LIMIT and OFFSET clauses. These
82127     ** are not allowed to refer to any names, so pass an empty NameContext.
82128     */
82129     memset(&sNC, 0, sizeof(sNC));
82130     sNC.pParse = pParse;
82131     if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
82132         sqlite3ResolveExprNames(&sNC, p->pOffset) ){
82133       return WRC_Abort;
82134     }
82135
82136     /* If the SF_Converted flags is set, then this Select object was
82137     ** was created by the convertCompoundSelectToSubquery() function.
82138     ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
82139     ** as if it were part of the sub-query, not the parent. This block
82140     ** moves the pOrderBy down to the sub-query. It will be moved back
82141     ** after the names have been resolved.  */
82142     if( p->selFlags & SF_Converted ){
82143       Select *pSub = p->pSrc->a[0].pSelect;
82144       assert( p->pSrc->nSrc==1 && isCompound==0 && p->pOrderBy );
82145       assert( pSub->pPrior && pSub->pOrderBy==0 );
82146       pSub->pOrderBy = p->pOrderBy;
82147       p->pOrderBy = 0;
82148     }
82149   
82150     /* Recursively resolve names in all subqueries
82151     */
82152     for(i=0; i<p->pSrc->nSrc; i++){
82153       struct SrcList_item *pItem = &p->pSrc->a[i];
82154       if( pItem->pSelect ){
82155         NameContext *pNC;         /* Used to iterate name contexts */
82156         int nRef = 0;             /* Refcount for pOuterNC and outer contexts */
82157         const char *zSavedContext = pParse->zAuthContext;
82158
82159         /* Count the total number of references to pOuterNC and all of its
82160         ** parent contexts. After resolving references to expressions in
82161         ** pItem->pSelect, check if this value has changed. If so, then
82162         ** SELECT statement pItem->pSelect must be correlated. Set the
82163         ** pItem->isCorrelated flag if this is the case. */
82164         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
82165
82166         if( pItem->zName ) pParse->zAuthContext = pItem->zName;
82167         sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
82168         pParse->zAuthContext = zSavedContext;
82169         if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
82170
82171         for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
82172         assert( pItem->isCorrelated==0 && nRef<=0 );
82173         pItem->isCorrelated = (nRef!=0);
82174       }
82175     }
82176   
82177     /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
82178     ** resolve the result-set expression list.
82179     */
82180     sNC.ncFlags = NC_AllowAgg;
82181     sNC.pSrcList = p->pSrc;
82182     sNC.pNext = pOuterNC;
82183   
82184     /* Resolve names in the result set. */
82185     pEList = p->pEList;
82186     assert( pEList!=0 );
82187     for(i=0; i<pEList->nExpr; i++){
82188       Expr *pX = pEList->a[i].pExpr;
82189       if( sqlite3ResolveExprNames(&sNC, pX) ){
82190         return WRC_Abort;
82191       }
82192     }
82193   
82194     /* If there are no aggregate functions in the result-set, and no GROUP BY 
82195     ** expression, do not allow aggregates in any of the other expressions.
82196     */
82197     assert( (p->selFlags & SF_Aggregate)==0 );
82198     pGroupBy = p->pGroupBy;
82199     if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
82200       assert( NC_MinMaxAgg==SF_MinMaxAgg );
82201       p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
82202     }else{
82203       sNC.ncFlags &= ~NC_AllowAgg;
82204     }
82205   
82206     /* If a HAVING clause is present, then there must be a GROUP BY clause.
82207     */
82208     if( p->pHaving && !pGroupBy ){
82209       sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
82210       return WRC_Abort;
82211     }
82212   
82213     /* Add the output column list to the name-context before parsing the
82214     ** other expressions in the SELECT statement. This is so that
82215     ** expressions in the WHERE clause (etc.) can refer to expressions by
82216     ** aliases in the result set.
82217     **
82218     ** Minor point: If this is the case, then the expression will be
82219     ** re-evaluated for each reference to it.
82220     */
82221     sNC.pEList = p->pEList;
82222     if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
82223     if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
82224
82225     /* The ORDER BY and GROUP BY clauses may not refer to terms in
82226     ** outer queries 
82227     */
82228     sNC.pNext = 0;
82229     sNC.ncFlags |= NC_AllowAgg;
82230
82231     /* If this is a converted compound query, move the ORDER BY clause from 
82232     ** the sub-query back to the parent query. At this point each term
82233     ** within the ORDER BY clause has been transformed to an integer value.
82234     ** These integers will be replaced by copies of the corresponding result
82235     ** set expressions by the call to resolveOrderGroupBy() below.  */
82236     if( p->selFlags & SF_Converted ){
82237       Select *pSub = p->pSrc->a[0].pSelect;
82238       p->pOrderBy = pSub->pOrderBy;
82239       pSub->pOrderBy = 0;
82240     }
82241
82242     /* Process the ORDER BY clause for singleton SELECT statements.
82243     ** The ORDER BY clause for compounds SELECT statements is handled
82244     ** below, after all of the result-sets for all of the elements of
82245     ** the compound have been resolved.
82246     */
82247     if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
82248       return WRC_Abort;
82249     }
82250     if( db->mallocFailed ){
82251       return WRC_Abort;
82252     }
82253   
82254     /* Resolve the GROUP BY clause.  At the same time, make sure 
82255     ** the GROUP BY clause does not contain aggregate functions.
82256     */
82257     if( pGroupBy ){
82258       struct ExprList_item *pItem;
82259     
82260       if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
82261         return WRC_Abort;
82262       }
82263       for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
82264         if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
82265           sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
82266               "the GROUP BY clause");
82267           return WRC_Abort;
82268         }
82269       }
82270     }
82271
82272     /* Advance to the next term of the compound
82273     */
82274     p = p->pPrior;
82275     nCompound++;
82276   }
82277
82278   /* Resolve the ORDER BY on a compound SELECT after all terms of
82279   ** the compound have been resolved.
82280   */
82281   if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
82282     return WRC_Abort;
82283   }
82284
82285   return WRC_Prune;
82286 }
82287
82288 /*
82289 ** This routine walks an expression tree and resolves references to
82290 ** table columns and result-set columns.  At the same time, do error
82291 ** checking on function usage and set a flag if any aggregate functions
82292 ** are seen.
82293 **
82294 ** To resolve table columns references we look for nodes (or subtrees) of the 
82295 ** form X.Y.Z or Y.Z or just Z where
82296 **
82297 **      X:   The name of a database.  Ex:  "main" or "temp" or
82298 **           the symbolic name assigned to an ATTACH-ed database.
82299 **
82300 **      Y:   The name of a table in a FROM clause.  Or in a trigger
82301 **           one of the special names "old" or "new".
82302 **
82303 **      Z:   The name of a column in table Y.
82304 **
82305 ** The node at the root of the subtree is modified as follows:
82306 **
82307 **    Expr.op        Changed to TK_COLUMN
82308 **    Expr.pTab      Points to the Table object for X.Y
82309 **    Expr.iColumn   The column index in X.Y.  -1 for the rowid.
82310 **    Expr.iTable    The VDBE cursor number for X.Y
82311 **
82312 **
82313 ** To resolve result-set references, look for expression nodes of the
82314 ** form Z (with no X and Y prefix) where the Z matches the right-hand
82315 ** size of an AS clause in the result-set of a SELECT.  The Z expression
82316 ** is replaced by a copy of the left-hand side of the result-set expression.
82317 ** Table-name and function resolution occurs on the substituted expression
82318 ** tree.  For example, in:
82319 **
82320 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
82321 **
82322 ** The "x" term of the order by is replaced by "a+b" to render:
82323 **
82324 **      SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
82325 **
82326 ** Function calls are checked to make sure that the function is 
82327 ** defined and that the correct number of arguments are specified.
82328 ** If the function is an aggregate function, then the NC_HasAgg flag is
82329 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
82330 ** If an expression contains aggregate functions then the EP_Agg
82331 ** property on the expression is set.
82332 **
82333 ** An error message is left in pParse if anything is amiss.  The number
82334 ** if errors is returned.
82335 */
82336 SQLITE_PRIVATE int sqlite3ResolveExprNames( 
82337   NameContext *pNC,       /* Namespace to resolve expressions in. */
82338   Expr *pExpr             /* The expression to be analyzed. */
82339 ){
82340   u16 savedHasAgg;
82341   Walker w;
82342
82343   if( pExpr==0 ) return 0;
82344 #if SQLITE_MAX_EXPR_DEPTH>0
82345   {
82346     Parse *pParse = pNC->pParse;
82347     if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
82348       return 1;
82349     }
82350     pParse->nHeight += pExpr->nHeight;
82351   }
82352 #endif
82353   savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
82354   pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
82355   memset(&w, 0, sizeof(w));
82356   w.xExprCallback = resolveExprStep;
82357   w.xSelectCallback = resolveSelectStep;
82358   w.pParse = pNC->pParse;
82359   w.u.pNC = pNC;
82360   sqlite3WalkExpr(&w, pExpr);
82361 #if SQLITE_MAX_EXPR_DEPTH>0
82362   pNC->pParse->nHeight -= pExpr->nHeight;
82363 #endif
82364   if( pNC->nErr>0 || w.pParse->nErr>0 ){
82365     ExprSetProperty(pExpr, EP_Error);
82366   }
82367   if( pNC->ncFlags & NC_HasAgg ){
82368     ExprSetProperty(pExpr, EP_Agg);
82369   }
82370   pNC->ncFlags |= savedHasAgg;
82371   return ExprHasProperty(pExpr, EP_Error);
82372 }
82373
82374
82375 /*
82376 ** Resolve all names in all expressions of a SELECT and in all
82377 ** decendents of the SELECT, including compounds off of p->pPrior,
82378 ** subqueries in expressions, and subqueries used as FROM clause
82379 ** terms.
82380 **
82381 ** See sqlite3ResolveExprNames() for a description of the kinds of
82382 ** transformations that occur.
82383 **
82384 ** All SELECT statements should have been expanded using
82385 ** sqlite3SelectExpand() prior to invoking this routine.
82386 */
82387 SQLITE_PRIVATE void sqlite3ResolveSelectNames(
82388   Parse *pParse,         /* The parser context */
82389   Select *p,             /* The SELECT statement being coded. */
82390   NameContext *pOuterNC  /* Name context for parent SELECT statement */
82391 ){
82392   Walker w;
82393
82394   assert( p!=0 );
82395   memset(&w, 0, sizeof(w));
82396   w.xExprCallback = resolveExprStep;
82397   w.xSelectCallback = resolveSelectStep;
82398   w.pParse = pParse;
82399   w.u.pNC = pOuterNC;
82400   sqlite3WalkSelect(&w, p);
82401 }
82402
82403 /*
82404 ** Resolve names in expressions that can only reference a single table:
82405 **
82406 **    *   CHECK constraints
82407 **    *   WHERE clauses on partial indices
82408 **
82409 ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
82410 ** is set to -1 and the Expr.iColumn value is set to the column number.
82411 **
82412 ** Any errors cause an error message to be set in pParse.
82413 */
82414 SQLITE_PRIVATE void sqlite3ResolveSelfReference(
82415   Parse *pParse,      /* Parsing context */
82416   Table *pTab,        /* The table being referenced */
82417   int type,           /* NC_IsCheck or NC_PartIdx */
82418   Expr *pExpr,        /* Expression to resolve.  May be NULL. */
82419   ExprList *pList     /* Expression list to resolve.  May be NUL. */
82420 ){
82421   SrcList sSrc;                   /* Fake SrcList for pParse->pNewTable */
82422   NameContext sNC;                /* Name context for pParse->pNewTable */
82423   int i;                          /* Loop counter */
82424
82425   assert( type==NC_IsCheck || type==NC_PartIdx );
82426   memset(&sNC, 0, sizeof(sNC));
82427   memset(&sSrc, 0, sizeof(sSrc));
82428   sSrc.nSrc = 1;
82429   sSrc.a[0].zName = pTab->zName;
82430   sSrc.a[0].pTab = pTab;
82431   sSrc.a[0].iCursor = -1;
82432   sNC.pParse = pParse;
82433   sNC.pSrcList = &sSrc;
82434   sNC.ncFlags = type;
82435   if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
82436   if( pList ){
82437     for(i=0; i<pList->nExpr; i++){
82438       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
82439         return;
82440       }
82441     }
82442   }
82443 }
82444
82445 /************** End of resolve.c *********************************************/
82446 /************** Begin file expr.c ********************************************/
82447 /*
82448 ** 2001 September 15
82449 **
82450 ** The author disclaims copyright to this source code.  In place of
82451 ** a legal notice, here is a blessing:
82452 **
82453 **    May you do good and not evil.
82454 **    May you find forgiveness for yourself and forgive others.
82455 **    May you share freely, never taking more than you give.
82456 **
82457 *************************************************************************
82458 ** This file contains routines used for analyzing expressions and
82459 ** for generating VDBE code that evaluates expressions in SQLite.
82460 */
82461
82462 /*
82463 ** Return the 'affinity' of the expression pExpr if any.
82464 **
82465 ** If pExpr is a column, a reference to a column via an 'AS' alias,
82466 ** or a sub-select with a column as the return value, then the 
82467 ** affinity of that column is returned. Otherwise, 0x00 is returned,
82468 ** indicating no affinity for the expression.
82469 **
82470 ** i.e. the WHERE clause expressions in the following statements all
82471 ** have an affinity:
82472 **
82473 ** CREATE TABLE t1(a);
82474 ** SELECT * FROM t1 WHERE a;
82475 ** SELECT a AS b FROM t1 WHERE b;
82476 ** SELECT * FROM t1 WHERE (select a from t1);
82477 */
82478 SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
82479   int op;
82480   pExpr = sqlite3ExprSkipCollate(pExpr);
82481   if( pExpr->flags & EP_Generic ) return 0;
82482   op = pExpr->op;
82483   if( op==TK_SELECT ){
82484     assert( pExpr->flags&EP_xIsSelect );
82485     return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
82486   }
82487 #ifndef SQLITE_OMIT_CAST
82488   if( op==TK_CAST ){
82489     assert( !ExprHasProperty(pExpr, EP_IntValue) );
82490     return sqlite3AffinityType(pExpr->u.zToken, 0);
82491   }
82492 #endif
82493   if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER) 
82494    && pExpr->pTab!=0
82495   ){
82496     /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
82497     ** a TK_COLUMN but was previously evaluated and cached in a register */
82498     int j = pExpr->iColumn;
82499     if( j<0 ) return SQLITE_AFF_INTEGER;
82500     assert( pExpr->pTab && j<pExpr->pTab->nCol );
82501     return pExpr->pTab->aCol[j].affinity;
82502   }
82503   return pExpr->affinity;
82504 }
82505
82506 /*
82507 ** Set the collating sequence for expression pExpr to be the collating
82508 ** sequence named by pToken.   Return a pointer to a new Expr node that
82509 ** implements the COLLATE operator.
82510 **
82511 ** If a memory allocation error occurs, that fact is recorded in pParse->db
82512 ** and the pExpr parameter is returned unchanged.
82513 */
82514 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
82515   Parse *pParse,           /* Parsing context */
82516   Expr *pExpr,             /* Add the "COLLATE" clause to this expression */
82517   const Token *pCollName,  /* Name of collating sequence */
82518   int dequote              /* True to dequote pCollName */
82519 ){
82520   if( pCollName->n>0 ){
82521     Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
82522     if( pNew ){
82523       pNew->pLeft = pExpr;
82524       pNew->flags |= EP_Collate|EP_Skip;
82525       pExpr = pNew;
82526     }
82527   }
82528   return pExpr;
82529 }
82530 SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
82531   Token s;
82532   assert( zC!=0 );
82533   s.z = zC;
82534   s.n = sqlite3Strlen30(s.z);
82535   return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
82536 }
82537
82538 /*
82539 ** Skip over any TK_COLLATE or TK_AS operators and any unlikely()
82540 ** or likelihood() function at the root of an expression.
82541 */
82542 SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
82543   while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
82544     if( ExprHasProperty(pExpr, EP_Unlikely) ){
82545       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
82546       assert( pExpr->x.pList->nExpr>0 );
82547       assert( pExpr->op==TK_FUNCTION );
82548       pExpr = pExpr->x.pList->a[0].pExpr;
82549     }else{
82550       assert( pExpr->op==TK_COLLATE || pExpr->op==TK_AS );
82551       pExpr = pExpr->pLeft;
82552     }
82553   }   
82554   return pExpr;
82555 }
82556
82557 /*
82558 ** Return the collation sequence for the expression pExpr. If
82559 ** there is no defined collating sequence, return NULL.
82560 **
82561 ** The collating sequence might be determined by a COLLATE operator
82562 ** or by the presence of a column with a defined collating sequence.
82563 ** COLLATE operators take first precedence.  Left operands take
82564 ** precedence over right operands.
82565 */
82566 SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
82567   sqlite3 *db = pParse->db;
82568   CollSeq *pColl = 0;
82569   Expr *p = pExpr;
82570   while( p ){
82571     int op = p->op;
82572     if( p->flags & EP_Generic ) break;
82573     if( op==TK_CAST || op==TK_UPLUS ){
82574       p = p->pLeft;
82575       continue;
82576     }
82577     if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
82578       pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
82579       break;
82580     }
82581     if( (op==TK_AGG_COLUMN || op==TK_COLUMN
82582           || op==TK_REGISTER || op==TK_TRIGGER)
82583      && p->pTab!=0
82584     ){
82585       /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
82586       ** a TK_COLUMN but was previously evaluated and cached in a register */
82587       int j = p->iColumn;
82588       if( j>=0 ){
82589         const char *zColl = p->pTab->aCol[j].zColl;
82590         pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
82591       }
82592       break;
82593     }
82594     if( p->flags & EP_Collate ){
82595       if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
82596         p = p->pLeft;
82597       }else{
82598         Expr *pNext  = p->pRight;
82599         /* The Expr.x union is never used at the same time as Expr.pRight */
82600         assert( p->x.pList==0 || p->pRight==0 );
82601         /* p->flags holds EP_Collate and p->pLeft->flags does not.  And
82602         ** p->x.pSelect cannot.  So if p->x.pLeft exists, it must hold at
82603         ** least one EP_Collate. Thus the following two ALWAYS. */
82604         if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
82605           int i;
82606           for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
82607             if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
82608               pNext = p->x.pList->a[i].pExpr;
82609               break;
82610             }
82611           }
82612         }
82613         p = pNext;
82614       }
82615     }else{
82616       break;
82617     }
82618   }
82619   if( sqlite3CheckCollSeq(pParse, pColl) ){ 
82620     pColl = 0;
82621   }
82622   return pColl;
82623 }
82624
82625 /*
82626 ** pExpr is an operand of a comparison operator.  aff2 is the
82627 ** type affinity of the other operand.  This routine returns the
82628 ** type affinity that should be used for the comparison operator.
82629 */
82630 SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
82631   char aff1 = sqlite3ExprAffinity(pExpr);
82632   if( aff1 && aff2 ){
82633     /* Both sides of the comparison are columns. If one has numeric
82634     ** affinity, use that. Otherwise use no affinity.
82635     */
82636     if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
82637       return SQLITE_AFF_NUMERIC;
82638     }else{
82639       return SQLITE_AFF_NONE;
82640     }
82641   }else if( !aff1 && !aff2 ){
82642     /* Neither side of the comparison is a column.  Compare the
82643     ** results directly.
82644     */
82645     return SQLITE_AFF_NONE;
82646   }else{
82647     /* One side is a column, the other is not. Use the columns affinity. */
82648     assert( aff1==0 || aff2==0 );
82649     return (aff1 + aff2);
82650   }
82651 }
82652
82653 /*
82654 ** pExpr is a comparison operator.  Return the type affinity that should
82655 ** be applied to both operands prior to doing the comparison.
82656 */
82657 static char comparisonAffinity(Expr *pExpr){
82658   char aff;
82659   assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
82660           pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
82661           pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
82662   assert( pExpr->pLeft );
82663   aff = sqlite3ExprAffinity(pExpr->pLeft);
82664   if( pExpr->pRight ){
82665     aff = sqlite3CompareAffinity(pExpr->pRight, aff);
82666   }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
82667     aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
82668   }else if( !aff ){
82669     aff = SQLITE_AFF_NONE;
82670   }
82671   return aff;
82672 }
82673
82674 /*
82675 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
82676 ** idx_affinity is the affinity of an indexed column. Return true
82677 ** if the index with affinity idx_affinity may be used to implement
82678 ** the comparison in pExpr.
82679 */
82680 SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
82681   char aff = comparisonAffinity(pExpr);
82682   switch( aff ){
82683     case SQLITE_AFF_NONE:
82684       return 1;
82685     case SQLITE_AFF_TEXT:
82686       return idx_affinity==SQLITE_AFF_TEXT;
82687     default:
82688       return sqlite3IsNumericAffinity(idx_affinity);
82689   }
82690 }
82691
82692 /*
82693 ** Return the P5 value that should be used for a binary comparison
82694 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
82695 */
82696 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
82697   u8 aff = (char)sqlite3ExprAffinity(pExpr2);
82698   aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
82699   return aff;
82700 }
82701
82702 /*
82703 ** Return a pointer to the collation sequence that should be used by
82704 ** a binary comparison operator comparing pLeft and pRight.
82705 **
82706 ** If the left hand expression has a collating sequence type, then it is
82707 ** used. Otherwise the collation sequence for the right hand expression
82708 ** is used, or the default (BINARY) if neither expression has a collating
82709 ** type.
82710 **
82711 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
82712 ** it is not considered.
82713 */
82714 SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
82715   Parse *pParse, 
82716   Expr *pLeft, 
82717   Expr *pRight
82718 ){
82719   CollSeq *pColl;
82720   assert( pLeft );
82721   if( pLeft->flags & EP_Collate ){
82722     pColl = sqlite3ExprCollSeq(pParse, pLeft);
82723   }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
82724     pColl = sqlite3ExprCollSeq(pParse, pRight);
82725   }else{
82726     pColl = sqlite3ExprCollSeq(pParse, pLeft);
82727     if( !pColl ){
82728       pColl = sqlite3ExprCollSeq(pParse, pRight);
82729     }
82730   }
82731   return pColl;
82732 }
82733
82734 /*
82735 ** Generate code for a comparison operator.
82736 */
82737 static int codeCompare(
82738   Parse *pParse,    /* The parsing (and code generating) context */
82739   Expr *pLeft,      /* The left operand */
82740   Expr *pRight,     /* The right operand */
82741   int opcode,       /* The comparison opcode */
82742   int in1, int in2, /* Register holding operands */
82743   int dest,         /* Jump here if true.  */
82744   int jumpIfNull    /* If true, jump if either operand is NULL */
82745 ){
82746   int p5;
82747   int addr;
82748   CollSeq *p4;
82749
82750   p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
82751   p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
82752   addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
82753                            (void*)p4, P4_COLLSEQ);
82754   sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
82755   return addr;
82756 }
82757
82758 #if SQLITE_MAX_EXPR_DEPTH>0
82759 /*
82760 ** Check that argument nHeight is less than or equal to the maximum
82761 ** expression depth allowed. If it is not, leave an error message in
82762 ** pParse.
82763 */
82764 SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
82765   int rc = SQLITE_OK;
82766   int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
82767   if( nHeight>mxHeight ){
82768     sqlite3ErrorMsg(pParse, 
82769        "Expression tree is too large (maximum depth %d)", mxHeight
82770     );
82771     rc = SQLITE_ERROR;
82772   }
82773   return rc;
82774 }
82775
82776 /* The following three functions, heightOfExpr(), heightOfExprList()
82777 ** and heightOfSelect(), are used to determine the maximum height
82778 ** of any expression tree referenced by the structure passed as the
82779 ** first argument.
82780 **
82781 ** If this maximum height is greater than the current value pointed
82782 ** to by pnHeight, the second parameter, then set *pnHeight to that
82783 ** value.
82784 */
82785 static void heightOfExpr(Expr *p, int *pnHeight){
82786   if( p ){
82787     if( p->nHeight>*pnHeight ){
82788       *pnHeight = p->nHeight;
82789     }
82790   }
82791 }
82792 static void heightOfExprList(ExprList *p, int *pnHeight){
82793   if( p ){
82794     int i;
82795     for(i=0; i<p->nExpr; i++){
82796       heightOfExpr(p->a[i].pExpr, pnHeight);
82797     }
82798   }
82799 }
82800 static void heightOfSelect(Select *p, int *pnHeight){
82801   if( p ){
82802     heightOfExpr(p->pWhere, pnHeight);
82803     heightOfExpr(p->pHaving, pnHeight);
82804     heightOfExpr(p->pLimit, pnHeight);
82805     heightOfExpr(p->pOffset, pnHeight);
82806     heightOfExprList(p->pEList, pnHeight);
82807     heightOfExprList(p->pGroupBy, pnHeight);
82808     heightOfExprList(p->pOrderBy, pnHeight);
82809     heightOfSelect(p->pPrior, pnHeight);
82810   }
82811 }
82812
82813 /*
82814 ** Set the Expr.nHeight variable in the structure passed as an 
82815 ** argument. An expression with no children, Expr.pList or 
82816 ** Expr.pSelect member has a height of 1. Any other expression
82817 ** has a height equal to the maximum height of any other 
82818 ** referenced Expr plus one.
82819 **
82820 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
82821 ** if appropriate.
82822 */
82823 static void exprSetHeight(Expr *p){
82824   int nHeight = 0;
82825   heightOfExpr(p->pLeft, &nHeight);
82826   heightOfExpr(p->pRight, &nHeight);
82827   if( ExprHasProperty(p, EP_xIsSelect) ){
82828     heightOfSelect(p->x.pSelect, &nHeight);
82829   }else if( p->x.pList ){
82830     heightOfExprList(p->x.pList, &nHeight);
82831     p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
82832   }
82833   p->nHeight = nHeight + 1;
82834 }
82835
82836 /*
82837 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
82838 ** the height is greater than the maximum allowed expression depth,
82839 ** leave an error in pParse.
82840 **
82841 ** Also propagate all EP_Propagate flags from the Expr.x.pList into
82842 ** Expr.flags. 
82843 */
82844 SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
82845   if( pParse->nErr ) return;
82846   exprSetHeight(p);
82847   sqlite3ExprCheckHeight(pParse, p->nHeight);
82848 }
82849
82850 /*
82851 ** Return the maximum height of any expression tree referenced
82852 ** by the select statement passed as an argument.
82853 */
82854 SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
82855   int nHeight = 0;
82856   heightOfSelect(p, &nHeight);
82857   return nHeight;
82858 }
82859 #else /* ABOVE:  Height enforcement enabled.  BELOW: Height enforcement off */
82860 /*
82861 ** Propagate all EP_Propagate flags from the Expr.x.pList into
82862 ** Expr.flags. 
82863 */
82864 SQLITE_PRIVATE void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
82865   if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
82866     p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
82867   }
82868 }
82869 #define exprSetHeight(y)
82870 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
82871
82872 /*
82873 ** This routine is the core allocator for Expr nodes.
82874 **
82875 ** Construct a new expression node and return a pointer to it.  Memory
82876 ** for this node and for the pToken argument is a single allocation
82877 ** obtained from sqlite3DbMalloc().  The calling function
82878 ** is responsible for making sure the node eventually gets freed.
82879 **
82880 ** If dequote is true, then the token (if it exists) is dequoted.
82881 ** If dequote is false, no dequoting is performance.  The deQuote
82882 ** parameter is ignored if pToken is NULL or if the token does not
82883 ** appear to be quoted.  If the quotes were of the form "..." (double-quotes)
82884 ** then the EP_DblQuoted flag is set on the expression node.
82885 **
82886 ** Special case:  If op==TK_INTEGER and pToken points to a string that
82887 ** can be translated into a 32-bit integer, then the token is not
82888 ** stored in u.zToken.  Instead, the integer values is written
82889 ** into u.iValue and the EP_IntValue flag is set.  No extra storage
82890 ** is allocated to hold the integer text and the dequote flag is ignored.
82891 */
82892 SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
82893   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
82894   int op,                 /* Expression opcode */
82895   const Token *pToken,    /* Token argument.  Might be NULL */
82896   int dequote             /* True to dequote */
82897 ){
82898   Expr *pNew;
82899   int nExtra = 0;
82900   int iValue = 0;
82901
82902   if( pToken ){
82903     if( op!=TK_INTEGER || pToken->z==0
82904           || sqlite3GetInt32(pToken->z, &iValue)==0 ){
82905       nExtra = pToken->n+1;
82906       assert( iValue>=0 );
82907     }
82908   }
82909   pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
82910   if( pNew ){
82911     pNew->op = (u8)op;
82912     pNew->iAgg = -1;
82913     if( pToken ){
82914       if( nExtra==0 ){
82915         pNew->flags |= EP_IntValue;
82916         pNew->u.iValue = iValue;
82917       }else{
82918         int c;
82919         pNew->u.zToken = (char*)&pNew[1];
82920         assert( pToken->z!=0 || pToken->n==0 );
82921         if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
82922         pNew->u.zToken[pToken->n] = 0;
82923         if( dequote && nExtra>=3 
82924              && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
82925           sqlite3Dequote(pNew->u.zToken);
82926           if( c=='"' ) pNew->flags |= EP_DblQuoted;
82927         }
82928       }
82929     }
82930 #if SQLITE_MAX_EXPR_DEPTH>0
82931     pNew->nHeight = 1;
82932 #endif  
82933   }
82934   return pNew;
82935 }
82936
82937 /*
82938 ** Allocate a new expression node from a zero-terminated token that has
82939 ** already been dequoted.
82940 */
82941 SQLITE_PRIVATE Expr *sqlite3Expr(
82942   sqlite3 *db,            /* Handle for sqlite3DbMallocZero() (may be null) */
82943   int op,                 /* Expression opcode */
82944   const char *zToken      /* Token argument.  Might be NULL */
82945 ){
82946   Token x;
82947   x.z = zToken;
82948   x.n = zToken ? sqlite3Strlen30(zToken) : 0;
82949   return sqlite3ExprAlloc(db, op, &x, 0);
82950 }
82951
82952 /*
82953 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
82954 **
82955 ** If pRoot==NULL that means that a memory allocation error has occurred.
82956 ** In that case, delete the subtrees pLeft and pRight.
82957 */
82958 SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
82959   sqlite3 *db,
82960   Expr *pRoot,
82961   Expr *pLeft,
82962   Expr *pRight
82963 ){
82964   if( pRoot==0 ){
82965     assert( db->mallocFailed );
82966     sqlite3ExprDelete(db, pLeft);
82967     sqlite3ExprDelete(db, pRight);
82968   }else{
82969     if( pRight ){
82970       pRoot->pRight = pRight;
82971       pRoot->flags |= EP_Propagate & pRight->flags;
82972     }
82973     if( pLeft ){
82974       pRoot->pLeft = pLeft;
82975       pRoot->flags |= EP_Propagate & pLeft->flags;
82976     }
82977     exprSetHeight(pRoot);
82978   }
82979 }
82980
82981 /*
82982 ** Allocate an Expr node which joins as many as two subtrees.
82983 **
82984 ** One or both of the subtrees can be NULL.  Return a pointer to the new
82985 ** Expr node.  Or, if an OOM error occurs, set pParse->db->mallocFailed,
82986 ** free the subtrees and return NULL.
82987 */
82988 SQLITE_PRIVATE Expr *sqlite3PExpr(
82989   Parse *pParse,          /* Parsing context */
82990   int op,                 /* Expression opcode */
82991   Expr *pLeft,            /* Left operand */
82992   Expr *pRight,           /* Right operand */
82993   const Token *pToken     /* Argument token */
82994 ){
82995   Expr *p;
82996   if( op==TK_AND && pLeft && pRight && pParse->nErr==0 ){
82997     /* Take advantage of short-circuit false optimization for AND */
82998     p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
82999   }else{
83000     p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
83001     sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
83002   }
83003   if( p ) {
83004     sqlite3ExprCheckHeight(pParse, p->nHeight);
83005   }
83006   return p;
83007 }
83008
83009 /*
83010 ** If the expression is always either TRUE or FALSE (respectively),
83011 ** then return 1.  If one cannot determine the truth value of the
83012 ** expression at compile-time return 0.
83013 **
83014 ** This is an optimization.  If is OK to return 0 here even if
83015 ** the expression really is always false or false (a false negative).
83016 ** But it is a bug to return 1 if the expression might have different
83017 ** boolean values in different circumstances (a false positive.)
83018 **
83019 ** Note that if the expression is part of conditional for a
83020 ** LEFT JOIN, then we cannot determine at compile-time whether or not
83021 ** is it true or false, so always return 0.
83022 */
83023 static int exprAlwaysTrue(Expr *p){
83024   int v = 0;
83025   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
83026   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
83027   return v!=0;
83028 }
83029 static int exprAlwaysFalse(Expr *p){
83030   int v = 0;
83031   if( ExprHasProperty(p, EP_FromJoin) ) return 0;
83032   if( !sqlite3ExprIsInteger(p, &v) ) return 0;
83033   return v==0;
83034 }
83035
83036 /*
83037 ** Join two expressions using an AND operator.  If either expression is
83038 ** NULL, then just return the other expression.
83039 **
83040 ** If one side or the other of the AND is known to be false, then instead
83041 ** of returning an AND expression, just return a constant expression with
83042 ** a value of false.
83043 */
83044 SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
83045   if( pLeft==0 ){
83046     return pRight;
83047   }else if( pRight==0 ){
83048     return pLeft;
83049   }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
83050     sqlite3ExprDelete(db, pLeft);
83051     sqlite3ExprDelete(db, pRight);
83052     return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
83053   }else{
83054     Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
83055     sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
83056     return pNew;
83057   }
83058 }
83059
83060 /*
83061 ** Construct a new expression node for a function with multiple
83062 ** arguments.
83063 */
83064 SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
83065   Expr *pNew;
83066   sqlite3 *db = pParse->db;
83067   assert( pToken );
83068   pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
83069   if( pNew==0 ){
83070     sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
83071     return 0;
83072   }
83073   pNew->x.pList = pList;
83074   assert( !ExprHasProperty(pNew, EP_xIsSelect) );
83075   sqlite3ExprSetHeightAndFlags(pParse, pNew);
83076   return pNew;
83077 }
83078
83079 /*
83080 ** Assign a variable number to an expression that encodes a wildcard
83081 ** in the original SQL statement.  
83082 **
83083 ** Wildcards consisting of a single "?" are assigned the next sequential
83084 ** variable number.
83085 **
83086 ** Wildcards of the form "?nnn" are assigned the number "nnn".  We make
83087 ** sure "nnn" is not too be to avoid a denial of service attack when
83088 ** the SQL statement comes from an external source.
83089 **
83090 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
83091 ** as the previous instance of the same wildcard.  Or if this is the first
83092 ** instance of the wildcard, the next sequential variable number is
83093 ** assigned.
83094 */
83095 SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
83096   sqlite3 *db = pParse->db;
83097   const char *z;
83098
83099   if( pExpr==0 ) return;
83100   assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
83101   z = pExpr->u.zToken;
83102   assert( z!=0 );
83103   assert( z[0]!=0 );
83104   if( z[1]==0 ){
83105     /* Wildcard of the form "?".  Assign the next variable number */
83106     assert( z[0]=='?' );
83107     pExpr->iColumn = (ynVar)(++pParse->nVar);
83108   }else{
83109     ynVar x = 0;
83110     u32 n = sqlite3Strlen30(z);
83111     if( z[0]=='?' ){
83112       /* Wildcard of the form "?nnn".  Convert "nnn" to an integer and
83113       ** use it as the variable number */
83114       i64 i;
83115       int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
83116       pExpr->iColumn = x = (ynVar)i;
83117       testcase( i==0 );
83118       testcase( i==1 );
83119       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
83120       testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
83121       if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
83122         sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
83123             db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
83124         x = 0;
83125       }
83126       if( i>pParse->nVar ){
83127         pParse->nVar = (int)i;
83128       }
83129     }else{
83130       /* Wildcards like ":aaa", "$aaa" or "@aaa".  Reuse the same variable
83131       ** number as the prior appearance of the same name, or if the name
83132       ** has never appeared before, reuse the same variable number
83133       */
83134       ynVar i;
83135       for(i=0; i<pParse->nzVar; i++){
83136         if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
83137           pExpr->iColumn = x = (ynVar)i+1;
83138           break;
83139         }
83140       }
83141       if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
83142     }
83143     if( x>0 ){
83144       if( x>pParse->nzVar ){
83145         char **a;
83146         a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
83147         if( a==0 ) return;  /* Error reported through db->mallocFailed */
83148         pParse->azVar = a;
83149         memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
83150         pParse->nzVar = x;
83151       }
83152       if( z[0]!='?' || pParse->azVar[x-1]==0 ){
83153         sqlite3DbFree(db, pParse->azVar[x-1]);
83154         pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
83155       }
83156     }
83157   } 
83158   if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
83159     sqlite3ErrorMsg(pParse, "too many SQL variables");
83160   }
83161 }
83162
83163 /*
83164 ** Recursively delete an expression tree.
83165 */
83166 SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
83167   if( p==0 ) return;
83168   /* Sanity check: Assert that the IntValue is non-negative if it exists */
83169   assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
83170   if( !ExprHasProperty(p, EP_TokenOnly) ){
83171     /* The Expr.x union is never used at the same time as Expr.pRight */
83172     assert( p->x.pList==0 || p->pRight==0 );
83173     sqlite3ExprDelete(db, p->pLeft);
83174     sqlite3ExprDelete(db, p->pRight);
83175     if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
83176     if( ExprHasProperty(p, EP_xIsSelect) ){
83177       sqlite3SelectDelete(db, p->x.pSelect);
83178     }else{
83179       sqlite3ExprListDelete(db, p->x.pList);
83180     }
83181   }
83182   if( !ExprHasProperty(p, EP_Static) ){
83183     sqlite3DbFree(db, p);
83184   }
83185 }
83186
83187 /*
83188 ** Return the number of bytes allocated for the expression structure 
83189 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
83190 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
83191 */
83192 static int exprStructSize(Expr *p){
83193   if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
83194   if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
83195   return EXPR_FULLSIZE;
83196 }
83197
83198 /*
83199 ** The dupedExpr*Size() routines each return the number of bytes required
83200 ** to store a copy of an expression or expression tree.  They differ in
83201 ** how much of the tree is measured.
83202 **
83203 **     dupedExprStructSize()     Size of only the Expr structure 
83204 **     dupedExprNodeSize()       Size of Expr + space for token
83205 **     dupedExprSize()           Expr + token + subtree components
83206 **
83207 ***************************************************************************
83208 **
83209 ** The dupedExprStructSize() function returns two values OR-ed together:  
83210 ** (1) the space required for a copy of the Expr structure only and 
83211 ** (2) the EP_xxx flags that indicate what the structure size should be.
83212 ** The return values is always one of:
83213 **
83214 **      EXPR_FULLSIZE
83215 **      EXPR_REDUCEDSIZE   | EP_Reduced
83216 **      EXPR_TOKENONLYSIZE | EP_TokenOnly
83217 **
83218 ** The size of the structure can be found by masking the return value
83219 ** of this routine with 0xfff.  The flags can be found by masking the
83220 ** return value with EP_Reduced|EP_TokenOnly.
83221 **
83222 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
83223 ** (unreduced) Expr objects as they or originally constructed by the parser.
83224 ** During expression analysis, extra information is computed and moved into
83225 ** later parts of teh Expr object and that extra information might get chopped
83226 ** off if the expression is reduced.  Note also that it does not work to
83227 ** make an EXPRDUP_REDUCE copy of a reduced expression.  It is only legal
83228 ** to reduce a pristine expression tree from the parser.  The implementation
83229 ** of dupedExprStructSize() contain multiple assert() statements that attempt
83230 ** to enforce this constraint.
83231 */
83232 static int dupedExprStructSize(Expr *p, int flags){
83233   int nSize;
83234   assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
83235   assert( EXPR_FULLSIZE<=0xfff );
83236   assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
83237   if( 0==(flags&EXPRDUP_REDUCE) ){
83238     nSize = EXPR_FULLSIZE;
83239   }else{
83240     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
83241     assert( !ExprHasProperty(p, EP_FromJoin) ); 
83242     assert( !ExprHasProperty(p, EP_MemToken) );
83243     assert( !ExprHasProperty(p, EP_NoReduce) );
83244     if( p->pLeft || p->x.pList ){
83245       nSize = EXPR_REDUCEDSIZE | EP_Reduced;
83246     }else{
83247       assert( p->pRight==0 );
83248       nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
83249     }
83250   }
83251   return nSize;
83252 }
83253
83254 /*
83255 ** This function returns the space in bytes required to store the copy 
83256 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
83257 ** string is defined.)
83258 */
83259 static int dupedExprNodeSize(Expr *p, int flags){
83260   int nByte = dupedExprStructSize(p, flags) & 0xfff;
83261   if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
83262     nByte += sqlite3Strlen30(p->u.zToken)+1;
83263   }
83264   return ROUND8(nByte);
83265 }
83266
83267 /*
83268 ** Return the number of bytes required to create a duplicate of the 
83269 ** expression passed as the first argument. The second argument is a
83270 ** mask containing EXPRDUP_XXX flags.
83271 **
83272 ** The value returned includes space to create a copy of the Expr struct
83273 ** itself and the buffer referred to by Expr.u.zToken, if any.
83274 **
83275 ** If the EXPRDUP_REDUCE flag is set, then the return value includes 
83276 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft 
83277 ** and Expr.pRight variables (but not for any structures pointed to or 
83278 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
83279 */
83280 static int dupedExprSize(Expr *p, int flags){
83281   int nByte = 0;
83282   if( p ){
83283     nByte = dupedExprNodeSize(p, flags);
83284     if( flags&EXPRDUP_REDUCE ){
83285       nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
83286     }
83287   }
83288   return nByte;
83289 }
83290
83291 /*
83292 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer 
83293 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough 
83294 ** to store the copy of expression p, the copies of p->u.zToken
83295 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
83296 ** if any. Before returning, *pzBuffer is set to the first byte past the
83297 ** portion of the buffer copied into by this function.
83298 */
83299 static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
83300   Expr *pNew = 0;                      /* Value to return */
83301   if( p ){
83302     const int isReduced = (flags&EXPRDUP_REDUCE);
83303     u8 *zAlloc;
83304     u32 staticFlag = 0;
83305
83306     assert( pzBuffer==0 || isReduced );
83307
83308     /* Figure out where to write the new Expr structure. */
83309     if( pzBuffer ){
83310       zAlloc = *pzBuffer;
83311       staticFlag = EP_Static;
83312     }else{
83313       zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
83314     }
83315     pNew = (Expr *)zAlloc;
83316
83317     if( pNew ){
83318       /* Set nNewSize to the size allocated for the structure pointed to
83319       ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
83320       ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
83321       ** by the copy of the p->u.zToken string (if any).
83322       */
83323       const unsigned nStructSize = dupedExprStructSize(p, flags);
83324       const int nNewSize = nStructSize & 0xfff;
83325       int nToken;
83326       if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
83327         nToken = sqlite3Strlen30(p->u.zToken) + 1;
83328       }else{
83329         nToken = 0;
83330       }
83331       if( isReduced ){
83332         assert( ExprHasProperty(p, EP_Reduced)==0 );
83333         memcpy(zAlloc, p, nNewSize);
83334       }else{
83335         int nSize = exprStructSize(p);
83336         memcpy(zAlloc, p, nSize);
83337         memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
83338       }
83339
83340       /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
83341       pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
83342       pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
83343       pNew->flags |= staticFlag;
83344
83345       /* Copy the p->u.zToken string, if any. */
83346       if( nToken ){
83347         char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
83348         memcpy(zToken, p->u.zToken, nToken);
83349       }
83350
83351       if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
83352         /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
83353         if( ExprHasProperty(p, EP_xIsSelect) ){
83354           pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
83355         }else{
83356           pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
83357         }
83358       }
83359
83360       /* Fill in pNew->pLeft and pNew->pRight. */
83361       if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
83362         zAlloc += dupedExprNodeSize(p, flags);
83363         if( ExprHasProperty(pNew, EP_Reduced) ){
83364           pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
83365           pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
83366         }
83367         if( pzBuffer ){
83368           *pzBuffer = zAlloc;
83369         }
83370       }else{
83371         if( !ExprHasProperty(p, EP_TokenOnly) ){
83372           pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
83373           pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
83374         }
83375       }
83376
83377     }
83378   }
83379   return pNew;
83380 }
83381
83382 /*
83383 ** Create and return a deep copy of the object passed as the second 
83384 ** argument. If an OOM condition is encountered, NULL is returned
83385 ** and the db->mallocFailed flag set.
83386 */
83387 #ifndef SQLITE_OMIT_CTE
83388 static With *withDup(sqlite3 *db, With *p){
83389   With *pRet = 0;
83390   if( p ){
83391     int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
83392     pRet = sqlite3DbMallocZero(db, nByte);
83393     if( pRet ){
83394       int i;
83395       pRet->nCte = p->nCte;
83396       for(i=0; i<p->nCte; i++){
83397         pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
83398         pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
83399         pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
83400       }
83401     }
83402   }
83403   return pRet;
83404 }
83405 #else
83406 # define withDup(x,y) 0
83407 #endif
83408
83409 /*
83410 ** The following group of routines make deep copies of expressions,
83411 ** expression lists, ID lists, and select statements.  The copies can
83412 ** be deleted (by being passed to their respective ...Delete() routines)
83413 ** without effecting the originals.
83414 **
83415 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
83416 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded 
83417 ** by subsequent calls to sqlite*ListAppend() routines.
83418 **
83419 ** Any tables that the SrcList might point to are not duplicated.
83420 **
83421 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
83422 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
83423 ** truncated version of the usual Expr structure that will be stored as
83424 ** part of the in-memory representation of the database schema.
83425 */
83426 SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
83427   return exprDup(db, p, flags, 0);
83428 }
83429 SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
83430   ExprList *pNew;
83431   struct ExprList_item *pItem, *pOldItem;
83432   int i;
83433   if( p==0 ) return 0;
83434   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
83435   if( pNew==0 ) return 0;
83436   pNew->nExpr = i = p->nExpr;
83437   if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
83438   pNew->a = pItem = sqlite3DbMallocRaw(db,  i*sizeof(p->a[0]) );
83439   if( pItem==0 ){
83440     sqlite3DbFree(db, pNew);
83441     return 0;
83442   } 
83443   pOldItem = p->a;
83444   for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
83445     Expr *pOldExpr = pOldItem->pExpr;
83446     pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
83447     pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
83448     pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
83449     pItem->sortOrder = pOldItem->sortOrder;
83450     pItem->done = 0;
83451     pItem->bSpanIsTab = pOldItem->bSpanIsTab;
83452     pItem->u = pOldItem->u;
83453   }
83454   return pNew;
83455 }
83456
83457 /*
83458 ** If cursors, triggers, views and subqueries are all omitted from
83459 ** the build, then none of the following routines, except for 
83460 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
83461 ** called with a NULL argument.
83462 */
83463 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
83464  || !defined(SQLITE_OMIT_SUBQUERY)
83465 SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
83466   SrcList *pNew;
83467   int i;
83468   int nByte;
83469   if( p==0 ) return 0;
83470   nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
83471   pNew = sqlite3DbMallocRaw(db, nByte );
83472   if( pNew==0 ) return 0;
83473   pNew->nSrc = pNew->nAlloc = p->nSrc;
83474   for(i=0; i<p->nSrc; i++){
83475     struct SrcList_item *pNewItem = &pNew->a[i];
83476     struct SrcList_item *pOldItem = &p->a[i];
83477     Table *pTab;
83478     pNewItem->pSchema = pOldItem->pSchema;
83479     pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
83480     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
83481     pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
83482     pNewItem->jointype = pOldItem->jointype;
83483     pNewItem->iCursor = pOldItem->iCursor;
83484     pNewItem->addrFillSub = pOldItem->addrFillSub;
83485     pNewItem->regReturn = pOldItem->regReturn;
83486     pNewItem->isCorrelated = pOldItem->isCorrelated;
83487     pNewItem->viaCoroutine = pOldItem->viaCoroutine;
83488     pNewItem->isRecursive = pOldItem->isRecursive;
83489     pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
83490     pNewItem->notIndexed = pOldItem->notIndexed;
83491     pNewItem->pIndex = pOldItem->pIndex;
83492     pTab = pNewItem->pTab = pOldItem->pTab;
83493     if( pTab ){
83494       pTab->nRef++;
83495     }
83496     pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
83497     pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
83498     pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
83499     pNewItem->colUsed = pOldItem->colUsed;
83500   }
83501   return pNew;
83502 }
83503 SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
83504   IdList *pNew;
83505   int i;
83506   if( p==0 ) return 0;
83507   pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
83508   if( pNew==0 ) return 0;
83509   pNew->nId = p->nId;
83510   pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
83511   if( pNew->a==0 ){
83512     sqlite3DbFree(db, pNew);
83513     return 0;
83514   }
83515   /* Note that because the size of the allocation for p->a[] is not
83516   ** necessarily a power of two, sqlite3IdListAppend() may not be called
83517   ** on the duplicate created by this function. */
83518   for(i=0; i<p->nId; i++){
83519     struct IdList_item *pNewItem = &pNew->a[i];
83520     struct IdList_item *pOldItem = &p->a[i];
83521     pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
83522     pNewItem->idx = pOldItem->idx;
83523   }
83524   return pNew;
83525 }
83526 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
83527   Select *pNew, *pPrior;
83528   if( p==0 ) return 0;
83529   pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
83530   if( pNew==0 ) return 0;
83531   pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
83532   pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
83533   pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
83534   pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
83535   pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
83536   pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
83537   pNew->op = p->op;
83538   pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
83539   if( pPrior ) pPrior->pNext = pNew;
83540   pNew->pNext = 0;
83541   pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
83542   pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
83543   pNew->iLimit = 0;
83544   pNew->iOffset = 0;
83545   pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
83546   pNew->addrOpenEphm[0] = -1;
83547   pNew->addrOpenEphm[1] = -1;
83548   pNew->nSelectRow = p->nSelectRow;
83549   pNew->pWith = withDup(db, p->pWith);
83550   sqlite3SelectSetName(pNew, p->zSelName);
83551   return pNew;
83552 }
83553 #else
83554 SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
83555   assert( p==0 );
83556   return 0;
83557 }
83558 #endif
83559
83560
83561 /*
83562 ** Add a new element to the end of an expression list.  If pList is
83563 ** initially NULL, then create a new expression list.
83564 **
83565 ** If a memory allocation error occurs, the entire list is freed and
83566 ** NULL is returned.  If non-NULL is returned, then it is guaranteed
83567 ** that the new entry was successfully appended.
83568 */
83569 SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
83570   Parse *pParse,          /* Parsing context */
83571   ExprList *pList,        /* List to which to append. Might be NULL */
83572   Expr *pExpr             /* Expression to be appended. Might be NULL */
83573 ){
83574   sqlite3 *db = pParse->db;
83575   if( pList==0 ){
83576     pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
83577     if( pList==0 ){
83578       goto no_mem;
83579     }
83580     pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
83581     if( pList->a==0 ) goto no_mem;
83582   }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
83583     struct ExprList_item *a;
83584     assert( pList->nExpr>0 );
83585     a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
83586     if( a==0 ){
83587       goto no_mem;
83588     }
83589     pList->a = a;
83590   }
83591   assert( pList->a!=0 );
83592   if( 1 ){
83593     struct ExprList_item *pItem = &pList->a[pList->nExpr++];
83594     memset(pItem, 0, sizeof(*pItem));
83595     pItem->pExpr = pExpr;
83596   }
83597   return pList;
83598
83599 no_mem:     
83600   /* Avoid leaking memory if malloc has failed. */
83601   sqlite3ExprDelete(db, pExpr);
83602   sqlite3ExprListDelete(db, pList);
83603   return 0;
83604 }
83605
83606 /*
83607 ** Set the ExprList.a[].zName element of the most recently added item
83608 ** on the expression list.
83609 **
83610 ** pList might be NULL following an OOM error.  But pName should never be
83611 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
83612 ** is set.
83613 */
83614 SQLITE_PRIVATE void sqlite3ExprListSetName(
83615   Parse *pParse,          /* Parsing context */
83616   ExprList *pList,        /* List to which to add the span. */
83617   Token *pName,           /* Name to be added */
83618   int dequote             /* True to cause the name to be dequoted */
83619 ){
83620   assert( pList!=0 || pParse->db->mallocFailed!=0 );
83621   if( pList ){
83622     struct ExprList_item *pItem;
83623     assert( pList->nExpr>0 );
83624     pItem = &pList->a[pList->nExpr-1];
83625     assert( pItem->zName==0 );
83626     pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
83627     if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
83628   }
83629 }
83630
83631 /*
83632 ** Set the ExprList.a[].zSpan element of the most recently added item
83633 ** on the expression list.
83634 **
83635 ** pList might be NULL following an OOM error.  But pSpan should never be
83636 ** NULL.  If a memory allocation fails, the pParse->db->mallocFailed flag
83637 ** is set.
83638 */
83639 SQLITE_PRIVATE void sqlite3ExprListSetSpan(
83640   Parse *pParse,          /* Parsing context */
83641   ExprList *pList,        /* List to which to add the span. */
83642   ExprSpan *pSpan         /* The span to be added */
83643 ){
83644   sqlite3 *db = pParse->db;
83645   assert( pList!=0 || db->mallocFailed!=0 );
83646   if( pList ){
83647     struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
83648     assert( pList->nExpr>0 );
83649     assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
83650     sqlite3DbFree(db, pItem->zSpan);
83651     pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
83652                                     (int)(pSpan->zEnd - pSpan->zStart));
83653   }
83654 }
83655
83656 /*
83657 ** If the expression list pEList contains more than iLimit elements,
83658 ** leave an error message in pParse.
83659 */
83660 SQLITE_PRIVATE void sqlite3ExprListCheckLength(
83661   Parse *pParse,
83662   ExprList *pEList,
83663   const char *zObject
83664 ){
83665   int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
83666   testcase( pEList && pEList->nExpr==mx );
83667   testcase( pEList && pEList->nExpr==mx+1 );
83668   if( pEList && pEList->nExpr>mx ){
83669     sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
83670   }
83671 }
83672
83673 /*
83674 ** Delete an entire expression list.
83675 */
83676 SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
83677   int i;
83678   struct ExprList_item *pItem;
83679   if( pList==0 ) return;
83680   assert( pList->a!=0 || pList->nExpr==0 );
83681   for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
83682     sqlite3ExprDelete(db, pItem->pExpr);
83683     sqlite3DbFree(db, pItem->zName);
83684     sqlite3DbFree(db, pItem->zSpan);
83685   }
83686   sqlite3DbFree(db, pList->a);
83687   sqlite3DbFree(db, pList);
83688 }
83689
83690 /*
83691 ** Return the bitwise-OR of all Expr.flags fields in the given
83692 ** ExprList.
83693 */
83694 SQLITE_PRIVATE u32 sqlite3ExprListFlags(const ExprList *pList){
83695   int i;
83696   u32 m = 0;
83697   if( pList ){
83698     for(i=0; i<pList->nExpr; i++){
83699        m |= pList->a[i].pExpr->flags;
83700     }
83701   }
83702   return m;
83703 }
83704
83705 /*
83706 ** These routines are Walker callbacks used to check expressions to
83707 ** see if they are "constant" for some definition of constant.  The
83708 ** Walker.eCode value determines the type of "constant" we are looking
83709 ** for.
83710 **
83711 ** These callback routines are used to implement the following:
83712 **
83713 **     sqlite3ExprIsConstant()                  pWalker->eCode==1
83714 **     sqlite3ExprIsConstantNotJoin()           pWalker->eCode==2
83715 **     sqlite3ExprRefOneTableOnly()             pWalker->eCode==3
83716 **     sqlite3ExprIsConstantOrFunction()        pWalker->eCode==4 or 5
83717 **
83718 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
83719 ** is found to not be a constant.
83720 **
83721 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
83722 ** in a CREATE TABLE statement.  The Walker.eCode value is 5 when parsing
83723 ** an existing schema and 4 when processing a new statement.  A bound
83724 ** parameter raises an error for new statements, but is silently converted
83725 ** to NULL for existing schemas.  This allows sqlite_master tables that 
83726 ** contain a bound parameter because they were generated by older versions
83727 ** of SQLite to be parsed by newer versions of SQLite without raising a
83728 ** malformed schema error.
83729 */
83730 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
83731
83732   /* If pWalker->eCode is 2 then any term of the expression that comes from
83733   ** the ON or USING clauses of a left join disqualifies the expression
83734   ** from being considered constant. */
83735   if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
83736     pWalker->eCode = 0;
83737     return WRC_Abort;
83738   }
83739
83740   switch( pExpr->op ){
83741     /* Consider functions to be constant if all their arguments are constant
83742     ** and either pWalker->eCode==4 or 5 or the function has the
83743     ** SQLITE_FUNC_CONST flag. */
83744     case TK_FUNCTION:
83745       if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
83746         return WRC_Continue;
83747       }else{
83748         pWalker->eCode = 0;
83749         return WRC_Abort;
83750       }
83751     case TK_ID:
83752     case TK_COLUMN:
83753     case TK_AGG_FUNCTION:
83754     case TK_AGG_COLUMN:
83755       testcase( pExpr->op==TK_ID );
83756       testcase( pExpr->op==TK_COLUMN );
83757       testcase( pExpr->op==TK_AGG_FUNCTION );
83758       testcase( pExpr->op==TK_AGG_COLUMN );
83759       if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
83760         return WRC_Continue;
83761       }else{
83762         pWalker->eCode = 0;
83763         return WRC_Abort;
83764       }
83765     case TK_VARIABLE:
83766       if( pWalker->eCode==5 ){
83767         /* Silently convert bound parameters that appear inside of CREATE
83768         ** statements into a NULL when parsing the CREATE statement text out
83769         ** of the sqlite_master table */
83770         pExpr->op = TK_NULL;
83771       }else if( pWalker->eCode==4 ){
83772         /* A bound parameter in a CREATE statement that originates from
83773         ** sqlite3_prepare() causes an error */
83774         pWalker->eCode = 0;
83775         return WRC_Abort;
83776       }
83777       /* Fall through */
83778     default:
83779       testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
83780       testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
83781       return WRC_Continue;
83782   }
83783 }
83784 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
83785   UNUSED_PARAMETER(NotUsed);
83786   pWalker->eCode = 0;
83787   return WRC_Abort;
83788 }
83789 static int exprIsConst(Expr *p, int initFlag, int iCur){
83790   Walker w;
83791   memset(&w, 0, sizeof(w));
83792   w.eCode = initFlag;
83793   w.xExprCallback = exprNodeIsConstant;
83794   w.xSelectCallback = selectNodeIsConstant;
83795   w.u.iCur = iCur;
83796   sqlite3WalkExpr(&w, p);
83797   return w.eCode;
83798 }
83799
83800 /*
83801 ** Walk an expression tree.  Return non-zero if the expression is constant
83802 ** and 0 if it involves variables or function calls.
83803 **
83804 ** For the purposes of this function, a double-quoted string (ex: "abc")
83805 ** is considered a variable but a single-quoted string (ex: 'abc') is
83806 ** a constant.
83807 */
83808 SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
83809   return exprIsConst(p, 1, 0);
83810 }
83811
83812 /*
83813 ** Walk an expression tree.  Return non-zero if the expression is constant
83814 ** that does no originate from the ON or USING clauses of a join.
83815 ** Return 0 if it involves variables or function calls or terms from
83816 ** an ON or USING clause.
83817 */
83818 SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
83819   return exprIsConst(p, 2, 0);
83820 }
83821
83822 /*
83823 ** Walk an expression tree.  Return non-zero if the expression constant
83824 ** for any single row of the table with cursor iCur.  In other words, the
83825 ** expression must not refer to any non-deterministic function nor any
83826 ** table other than iCur.
83827 */
83828 SQLITE_PRIVATE int sqlite3ExprIsTableConstant(Expr *p, int iCur){
83829   return exprIsConst(p, 3, iCur);
83830 }
83831
83832 /*
83833 ** Walk an expression tree.  Return non-zero if the expression is constant
83834 ** or a function call with constant arguments.  Return and 0 if there
83835 ** are any variables.
83836 **
83837 ** For the purposes of this function, a double-quoted string (ex: "abc")
83838 ** is considered a variable but a single-quoted string (ex: 'abc') is
83839 ** a constant.
83840 */
83841 SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
83842   assert( isInit==0 || isInit==1 );
83843   return exprIsConst(p, 4+isInit, 0);
83844 }
83845
83846 /*
83847 ** If the expression p codes a constant integer that is small enough
83848 ** to fit in a 32-bit integer, return 1 and put the value of the integer
83849 ** in *pValue.  If the expression is not an integer or if it is too big
83850 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
83851 */
83852 SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
83853   int rc = 0;
83854
83855   /* If an expression is an integer literal that fits in a signed 32-bit
83856   ** integer, then the EP_IntValue flag will have already been set */
83857   assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
83858            || sqlite3GetInt32(p->u.zToken, &rc)==0 );
83859
83860   if( p->flags & EP_IntValue ){
83861     *pValue = p->u.iValue;
83862     return 1;
83863   }
83864   switch( p->op ){
83865     case TK_UPLUS: {
83866       rc = sqlite3ExprIsInteger(p->pLeft, pValue);
83867       break;
83868     }
83869     case TK_UMINUS: {
83870       int v;
83871       if( sqlite3ExprIsInteger(p->pLeft, &v) ){
83872         assert( v!=(-2147483647-1) );
83873         *pValue = -v;
83874         rc = 1;
83875       }
83876       break;
83877     }
83878     default: break;
83879   }
83880   return rc;
83881 }
83882
83883 /*
83884 ** Return FALSE if there is no chance that the expression can be NULL.
83885 **
83886 ** If the expression might be NULL or if the expression is too complex
83887 ** to tell return TRUE.  
83888 **
83889 ** This routine is used as an optimization, to skip OP_IsNull opcodes
83890 ** when we know that a value cannot be NULL.  Hence, a false positive
83891 ** (returning TRUE when in fact the expression can never be NULL) might
83892 ** be a small performance hit but is otherwise harmless.  On the other
83893 ** hand, a false negative (returning FALSE when the result could be NULL)
83894 ** will likely result in an incorrect answer.  So when in doubt, return
83895 ** TRUE.
83896 */
83897 SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
83898   u8 op;
83899   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
83900   op = p->op;
83901   if( op==TK_REGISTER ) op = p->op2;
83902   switch( op ){
83903     case TK_INTEGER:
83904     case TK_STRING:
83905     case TK_FLOAT:
83906     case TK_BLOB:
83907       return 0;
83908     case TK_COLUMN:
83909       assert( p->pTab!=0 );
83910       return ExprHasProperty(p, EP_CanBeNull) ||
83911              (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
83912     default:
83913       return 1;
83914   }
83915 }
83916
83917 /*
83918 ** Return TRUE if the given expression is a constant which would be
83919 ** unchanged by OP_Affinity with the affinity given in the second
83920 ** argument.
83921 **
83922 ** This routine is used to determine if the OP_Affinity operation
83923 ** can be omitted.  When in doubt return FALSE.  A false negative
83924 ** is harmless.  A false positive, however, can result in the wrong
83925 ** answer.
83926 */
83927 SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
83928   u8 op;
83929   if( aff==SQLITE_AFF_NONE ) return 1;
83930   while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
83931   op = p->op;
83932   if( op==TK_REGISTER ) op = p->op2;
83933   switch( op ){
83934     case TK_INTEGER: {
83935       return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
83936     }
83937     case TK_FLOAT: {
83938       return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
83939     }
83940     case TK_STRING: {
83941       return aff==SQLITE_AFF_TEXT;
83942     }
83943     case TK_BLOB: {
83944       return 1;
83945     }
83946     case TK_COLUMN: {
83947       assert( p->iTable>=0 );  /* p cannot be part of a CHECK constraint */
83948       return p->iColumn<0
83949           && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
83950     }
83951     default: {
83952       return 0;
83953     }
83954   }
83955 }
83956
83957 /*
83958 ** Return TRUE if the given string is a row-id column name.
83959 */
83960 SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
83961   if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
83962   if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
83963   if( sqlite3StrICmp(z, "OID")==0 ) return 1;
83964   return 0;
83965 }
83966
83967 /*
83968 ** Return true if we are able to the IN operator optimization on a
83969 ** query of the form
83970 **
83971 **       x IN (SELECT ...)
83972 **
83973 ** Where the SELECT... clause is as specified by the parameter to this
83974 ** routine.
83975 **
83976 ** The Select object passed in has already been preprocessed and no
83977 ** errors have been found.
83978 */
83979 #ifndef SQLITE_OMIT_SUBQUERY
83980 static int isCandidateForInOpt(Select *p){
83981   SrcList *pSrc;
83982   ExprList *pEList;
83983   Table *pTab;
83984   if( p==0 ) return 0;                   /* right-hand side of IN is SELECT */
83985   if( p->pPrior ) return 0;              /* Not a compound SELECT */
83986   if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
83987     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
83988     testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
83989     return 0; /* No DISTINCT keyword and no aggregate functions */
83990   }
83991   assert( p->pGroupBy==0 );              /* Has no GROUP BY clause */
83992   if( p->pLimit ) return 0;              /* Has no LIMIT clause */
83993   assert( p->pOffset==0 );               /* No LIMIT means no OFFSET */
83994   if( p->pWhere ) return 0;              /* Has no WHERE clause */
83995   pSrc = p->pSrc;
83996   assert( pSrc!=0 );
83997   if( pSrc->nSrc!=1 ) return 0;          /* Single term in FROM clause */
83998   if( pSrc->a[0].pSelect ) return 0;     /* FROM is not a subquery or view */
83999   pTab = pSrc->a[0].pTab;
84000   if( NEVER(pTab==0) ) return 0;
84001   assert( pTab->pSelect==0 );            /* FROM clause is not a view */
84002   if( IsVirtual(pTab) ) return 0;        /* FROM clause not a virtual table */
84003   pEList = p->pEList;
84004   if( pEList->nExpr!=1 ) return 0;       /* One column in the result set */
84005   if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
84006   return 1;
84007 }
84008 #endif /* SQLITE_OMIT_SUBQUERY */
84009
84010 /*
84011 ** Code an OP_Once instruction and allocate space for its flag. Return the 
84012 ** address of the new instruction.
84013 */
84014 SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
84015   Vdbe *v = sqlite3GetVdbe(pParse);      /* Virtual machine being coded */
84016   return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
84017 }
84018
84019 /*
84020 ** Generate code that checks the left-most column of index table iCur to see if
84021 ** it contains any NULL entries.  Cause the register at regHasNull to be set
84022 ** to a non-NULL value if iCur contains no NULLs.  Cause register regHasNull
84023 ** to be set to NULL if iCur contains one or more NULL values.
84024 */
84025 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
84026   int j1;
84027   sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
84028   j1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
84029   sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
84030   sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
84031   VdbeComment((v, "first_entry_in(%d)", iCur));
84032   sqlite3VdbeJumpHere(v, j1);
84033 }
84034
84035
84036 #ifndef SQLITE_OMIT_SUBQUERY
84037 /*
84038 ** The argument is an IN operator with a list (not a subquery) on the 
84039 ** right-hand side.  Return TRUE if that list is constant.
84040 */
84041 static int sqlite3InRhsIsConstant(Expr *pIn){
84042   Expr *pLHS;
84043   int res;
84044   assert( !ExprHasProperty(pIn, EP_xIsSelect) );
84045   pLHS = pIn->pLeft;
84046   pIn->pLeft = 0;
84047   res = sqlite3ExprIsConstant(pIn);
84048   pIn->pLeft = pLHS;
84049   return res;
84050 }
84051 #endif
84052
84053 /*
84054 ** This function is used by the implementation of the IN (...) operator.
84055 ** The pX parameter is the expression on the RHS of the IN operator, which
84056 ** might be either a list of expressions or a subquery.
84057 **
84058 ** The job of this routine is to find or create a b-tree object that can
84059 ** be used either to test for membership in the RHS set or to iterate through
84060 ** all members of the RHS set, skipping duplicates.
84061 **
84062 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
84063 ** and pX->iTable is set to the index of that cursor.
84064 **
84065 ** The returned value of this function indicates the b-tree type, as follows:
84066 **
84067 **   IN_INDEX_ROWID      - The cursor was opened on a database table.
84068 **   IN_INDEX_INDEX_ASC  - The cursor was opened on an ascending index.
84069 **   IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
84070 **   IN_INDEX_EPH        - The cursor was opened on a specially created and
84071 **                         populated epheremal table.
84072 **   IN_INDEX_NOOP       - No cursor was allocated.  The IN operator must be
84073 **                         implemented as a sequence of comparisons.
84074 **
84075 ** An existing b-tree might be used if the RHS expression pX is a simple
84076 ** subquery such as:
84077 **
84078 **     SELECT <column> FROM <table>
84079 **
84080 ** If the RHS of the IN operator is a list or a more complex subquery, then
84081 ** an ephemeral table might need to be generated from the RHS and then
84082 ** pX->iTable made to point to the ephemeral table instead of an
84083 ** existing table.
84084 **
84085 ** The inFlags parameter must contain exactly one of the bits
84086 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP.  If inFlags contains
84087 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
84088 ** fast membership test.  When the IN_INDEX_LOOP bit is set, the
84089 ** IN index will be used to loop over all values of the RHS of the
84090 ** IN operator.
84091 **
84092 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
84093 ** through the set members) then the b-tree must not contain duplicates.
84094 ** An epheremal table must be used unless the selected <column> is guaranteed
84095 ** to be unique - either because it is an INTEGER PRIMARY KEY or it
84096 ** has a UNIQUE constraint or UNIQUE index.
84097 **
84098 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used 
84099 ** for fast set membership tests) then an epheremal table must 
84100 ** be used unless <column> is an INTEGER PRIMARY KEY or an index can 
84101 ** be found with <column> as its left-most column.
84102 **
84103 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
84104 ** if the RHS of the IN operator is a list (not a subquery) then this
84105 ** routine might decide that creating an ephemeral b-tree for membership
84106 ** testing is too expensive and return IN_INDEX_NOOP.  In that case, the
84107 ** calling routine should implement the IN operator using a sequence
84108 ** of Eq or Ne comparison operations.
84109 **
84110 ** When the b-tree is being used for membership tests, the calling function
84111 ** might need to know whether or not the RHS side of the IN operator
84112 ** contains a NULL.  If prRhsHasNull is not a NULL pointer and 
84113 ** if there is any chance that the (...) might contain a NULL value at
84114 ** runtime, then a register is allocated and the register number written
84115 ** to *prRhsHasNull. If there is no chance that the (...) contains a
84116 ** NULL value, then *prRhsHasNull is left unchanged.
84117 **
84118 ** If a register is allocated and its location stored in *prRhsHasNull, then
84119 ** the value in that register will be NULL if the b-tree contains one or more
84120 ** NULL values, and it will be some non-NULL value if the b-tree contains no
84121 ** NULL values.
84122 */
84123 #ifndef SQLITE_OMIT_SUBQUERY
84124 SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, u32 inFlags, int *prRhsHasNull){
84125   Select *p;                            /* SELECT to the right of IN operator */
84126   int eType = 0;                        /* Type of RHS table. IN_INDEX_* */
84127   int iTab = pParse->nTab++;            /* Cursor of the RHS table */
84128   int mustBeUnique;                     /* True if RHS must be unique */
84129   Vdbe *v = sqlite3GetVdbe(pParse);     /* Virtual machine being coded */
84130
84131   assert( pX->op==TK_IN );
84132   mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
84133
84134   /* Check to see if an existing table or index can be used to
84135   ** satisfy the query.  This is preferable to generating a new 
84136   ** ephemeral table.
84137   */
84138   p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
84139   if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
84140     sqlite3 *db = pParse->db;              /* Database connection */
84141     Table *pTab;                           /* Table <table>. */
84142     Expr *pExpr;                           /* Expression <column> */
84143     i16 iCol;                              /* Index of column <column> */
84144     i16 iDb;                               /* Database idx for pTab */
84145
84146     assert( p );                        /* Because of isCandidateForInOpt(p) */
84147     assert( p->pEList!=0 );             /* Because of isCandidateForInOpt(p) */
84148     assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
84149     assert( p->pSrc!=0 );               /* Because of isCandidateForInOpt(p) */
84150     pTab = p->pSrc->a[0].pTab;
84151     pExpr = p->pEList->a[0].pExpr;
84152     iCol = (i16)pExpr->iColumn;
84153    
84154     /* Code an OP_Transaction and OP_TableLock for <table>. */
84155     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
84156     sqlite3CodeVerifySchema(pParse, iDb);
84157     sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
84158
84159     /* This function is only called from two places. In both cases the vdbe
84160     ** has already been allocated. So assume sqlite3GetVdbe() is always
84161     ** successful here.
84162     */
84163     assert(v);
84164     if( iCol<0 ){
84165       int iAddr = sqlite3CodeOnce(pParse);
84166       VdbeCoverage(v);
84167
84168       sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
84169       eType = IN_INDEX_ROWID;
84170
84171       sqlite3VdbeJumpHere(v, iAddr);
84172     }else{
84173       Index *pIdx;                         /* Iterator variable */
84174
84175       /* The collation sequence used by the comparison. If an index is to
84176       ** be used in place of a temp-table, it must be ordered according
84177       ** to this collation sequence.  */
84178       CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
84179
84180       /* Check that the affinity that will be used to perform the 
84181       ** comparison is the same as the affinity of the column. If
84182       ** it is not, it is not possible to use any index.
84183       */
84184       int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
84185
84186       for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
84187         if( (pIdx->aiColumn[0]==iCol)
84188          && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
84189          && (!mustBeUnique || (pIdx->nKeyCol==1 && IsUniqueIndex(pIdx)))
84190         ){
84191           int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
84192           sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
84193           sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
84194           VdbeComment((v, "%s", pIdx->zName));
84195           assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
84196           eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
84197
84198           if( prRhsHasNull && !pTab->aCol[iCol].notNull ){
84199             *prRhsHasNull = ++pParse->nMem;
84200             sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
84201           }
84202           sqlite3VdbeJumpHere(v, iAddr);
84203         }
84204       }
84205     }
84206   }
84207
84208   /* If no preexisting index is available for the IN clause
84209   ** and IN_INDEX_NOOP is an allowed reply
84210   ** and the RHS of the IN operator is a list, not a subquery
84211   ** and the RHS is not contant or has two or fewer terms,
84212   ** then it is not worth creating an ephemeral table to evaluate
84213   ** the IN operator so return IN_INDEX_NOOP.
84214   */
84215   if( eType==0
84216    && (inFlags & IN_INDEX_NOOP_OK)
84217    && !ExprHasProperty(pX, EP_xIsSelect)
84218    && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
84219   ){
84220     eType = IN_INDEX_NOOP;
84221   }
84222      
84223
84224   if( eType==0 ){
84225     /* Could not find an existing table or index to use as the RHS b-tree.
84226     ** We will have to generate an ephemeral table to do the job.
84227     */
84228     u32 savedNQueryLoop = pParse->nQueryLoop;
84229     int rMayHaveNull = 0;
84230     eType = IN_INDEX_EPH;
84231     if( inFlags & IN_INDEX_LOOP ){
84232       pParse->nQueryLoop = 0;
84233       if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
84234         eType = IN_INDEX_ROWID;
84235       }
84236     }else if( prRhsHasNull ){
84237       *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
84238     }
84239     sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
84240     pParse->nQueryLoop = savedNQueryLoop;
84241   }else{
84242     pX->iTable = iTab;
84243   }
84244   return eType;
84245 }
84246 #endif
84247
84248 /*
84249 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
84250 ** or IN operators.  Examples:
84251 **
84252 **     (SELECT a FROM b)          -- subquery
84253 **     EXISTS (SELECT a FROM b)   -- EXISTS subquery
84254 **     x IN (4,5,11)              -- IN operator with list on right-hand side
84255 **     x IN (SELECT a FROM b)     -- IN operator with subquery on the right
84256 **
84257 ** The pExpr parameter describes the expression that contains the IN
84258 ** operator or subquery.
84259 **
84260 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
84261 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
84262 ** to some integer key column of a table B-Tree. In this case, use an
84263 ** intkey B-Tree to store the set of IN(...) values instead of the usual
84264 ** (slower) variable length keys B-Tree.
84265 **
84266 ** If rMayHaveNull is non-zero, that means that the operation is an IN
84267 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
84268 ** All this routine does is initialize the register given by rMayHaveNull
84269 ** to NULL.  Calling routines will take care of changing this register
84270 ** value to non-NULL if the RHS is NULL-free.
84271 **
84272 ** For a SELECT or EXISTS operator, return the register that holds the
84273 ** result.  For IN operators or if an error occurs, the return value is 0.
84274 */
84275 #ifndef SQLITE_OMIT_SUBQUERY
84276 SQLITE_PRIVATE int sqlite3CodeSubselect(
84277   Parse *pParse,          /* Parsing context */
84278   Expr *pExpr,            /* The IN, SELECT, or EXISTS operator */
84279   int rHasNullFlag,       /* Register that records whether NULLs exist in RHS */
84280   int isRowid             /* If true, LHS of IN operator is a rowid */
84281 ){
84282   int jmpIfDynamic = -1;                      /* One-time test address */
84283   int rReg = 0;                           /* Register storing resulting */
84284   Vdbe *v = sqlite3GetVdbe(pParse);
84285   if( NEVER(v==0) ) return 0;
84286   sqlite3ExprCachePush(pParse);
84287
84288   /* This code must be run in its entirety every time it is encountered
84289   ** if any of the following is true:
84290   **
84291   **    *  The right-hand side is a correlated subquery
84292   **    *  The right-hand side is an expression list containing variables
84293   **    *  We are inside a trigger
84294   **
84295   ** If all of the above are false, then we can run this code just once
84296   ** save the results, and reuse the same result on subsequent invocations.
84297   */
84298   if( !ExprHasProperty(pExpr, EP_VarSelect) ){
84299     jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
84300   }
84301
84302 #ifndef SQLITE_OMIT_EXPLAIN
84303   if( pParse->explain==2 ){
84304     char *zMsg = sqlite3MPrintf(
84305         pParse->db, "EXECUTE %s%s SUBQUERY %d", jmpIfDynamic>=0?"":"CORRELATED ",
84306         pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
84307     );
84308     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
84309   }
84310 #endif
84311
84312   switch( pExpr->op ){
84313     case TK_IN: {
84314       char affinity;              /* Affinity of the LHS of the IN */
84315       int addr;                   /* Address of OP_OpenEphemeral instruction */
84316       Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
84317       KeyInfo *pKeyInfo = 0;      /* Key information */
84318
84319       affinity = sqlite3ExprAffinity(pLeft);
84320
84321       /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
84322       ** expression it is handled the same way.  An ephemeral table is 
84323       ** filled with single-field index keys representing the results
84324       ** from the SELECT or the <exprlist>.
84325       **
84326       ** If the 'x' expression is a column value, or the SELECT...
84327       ** statement returns a column value, then the affinity of that
84328       ** column is used to build the index keys. If both 'x' and the
84329       ** SELECT... statement are columns, then numeric affinity is used
84330       ** if either column has NUMERIC or INTEGER affinity. If neither
84331       ** 'x' nor the SELECT... statement are columns, then numeric affinity
84332       ** is used.
84333       */
84334       pExpr->iTable = pParse->nTab++;
84335       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
84336       pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
84337
84338       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
84339         /* Case 1:     expr IN (SELECT ...)
84340         **
84341         ** Generate code to write the results of the select into the temporary
84342         ** table allocated and opened above.
84343         */
84344         Select *pSelect = pExpr->x.pSelect;
84345         SelectDest dest;
84346         ExprList *pEList;
84347
84348         assert( !isRowid );
84349         sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
84350         dest.affSdst = (u8)affinity;
84351         assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
84352         pSelect->iLimit = 0;
84353         testcase( pSelect->selFlags & SF_Distinct );
84354         testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
84355         if( sqlite3Select(pParse, pSelect, &dest) ){
84356           sqlite3KeyInfoUnref(pKeyInfo);
84357           return 0;
84358         }
84359         pEList = pSelect->pEList;
84360         assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
84361         assert( pEList!=0 );
84362         assert( pEList->nExpr>0 );
84363         assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
84364         pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
84365                                                          pEList->a[0].pExpr);
84366       }else if( ALWAYS(pExpr->x.pList!=0) ){
84367         /* Case 2:     expr IN (exprlist)
84368         **
84369         ** For each expression, build an index key from the evaluation and
84370         ** store it in the temporary table. If <expr> is a column, then use
84371         ** that columns affinity when building index keys. If <expr> is not
84372         ** a column, use numeric affinity.
84373         */
84374         int i;
84375         ExprList *pList = pExpr->x.pList;
84376         struct ExprList_item *pItem;
84377         int r1, r2, r3;
84378
84379         if( !affinity ){
84380           affinity = SQLITE_AFF_NONE;
84381         }
84382         if( pKeyInfo ){
84383           assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
84384           pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
84385         }
84386
84387         /* Loop through each expression in <exprlist>. */
84388         r1 = sqlite3GetTempReg(pParse);
84389         r2 = sqlite3GetTempReg(pParse);
84390         if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
84391         for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
84392           Expr *pE2 = pItem->pExpr;
84393           int iValToIns;
84394
84395           /* If the expression is not constant then we will need to
84396           ** disable the test that was generated above that makes sure
84397           ** this code only executes once.  Because for a non-constant
84398           ** expression we need to rerun this code each time.
84399           */
84400           if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
84401             sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
84402             jmpIfDynamic = -1;
84403           }
84404
84405           /* Evaluate the expression and insert it into the temp table */
84406           if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
84407             sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
84408           }else{
84409             r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
84410             if( isRowid ){
84411               sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
84412                                 sqlite3VdbeCurrentAddr(v)+2);
84413               VdbeCoverage(v);
84414               sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
84415             }else{
84416               sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
84417               sqlite3ExprCacheAffinityChange(pParse, r3, 1);
84418               sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
84419             }
84420           }
84421         }
84422         sqlite3ReleaseTempReg(pParse, r1);
84423         sqlite3ReleaseTempReg(pParse, r2);
84424       }
84425       if( pKeyInfo ){
84426         sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
84427       }
84428       break;
84429     }
84430
84431     case TK_EXISTS:
84432     case TK_SELECT:
84433     default: {
84434       /* If this has to be a scalar SELECT.  Generate code to put the
84435       ** value of this select in a memory cell and record the number
84436       ** of the memory cell in iColumn.  If this is an EXISTS, write
84437       ** an integer 0 (not exists) or 1 (exists) into a memory cell
84438       ** and record that memory cell in iColumn.
84439       */
84440       Select *pSel;                         /* SELECT statement to encode */
84441       SelectDest dest;                      /* How to deal with SELECt result */
84442
84443       testcase( pExpr->op==TK_EXISTS );
84444       testcase( pExpr->op==TK_SELECT );
84445       assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
84446
84447       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
84448       pSel = pExpr->x.pSelect;
84449       sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
84450       if( pExpr->op==TK_SELECT ){
84451         dest.eDest = SRT_Mem;
84452         dest.iSdst = dest.iSDParm;
84453         sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
84454         VdbeComment((v, "Init subquery result"));
84455       }else{
84456         dest.eDest = SRT_Exists;
84457         sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
84458         VdbeComment((v, "Init EXISTS result"));
84459       }
84460       sqlite3ExprDelete(pParse->db, pSel->pLimit);
84461       pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
84462                                   &sqlite3IntTokens[1]);
84463       pSel->iLimit = 0;
84464       if( sqlite3Select(pParse, pSel, &dest) ){
84465         return 0;
84466       }
84467       rReg = dest.iSDParm;
84468       ExprSetVVAProperty(pExpr, EP_NoReduce);
84469       break;
84470     }
84471   }
84472
84473   if( rHasNullFlag ){
84474     sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
84475   }
84476
84477   if( jmpIfDynamic>=0 ){
84478     sqlite3VdbeJumpHere(v, jmpIfDynamic);
84479   }
84480   sqlite3ExprCachePop(pParse);
84481
84482   return rReg;
84483 }
84484 #endif /* SQLITE_OMIT_SUBQUERY */
84485
84486 #ifndef SQLITE_OMIT_SUBQUERY
84487 /*
84488 ** Generate code for an IN expression.
84489 **
84490 **      x IN (SELECT ...)
84491 **      x IN (value, value, ...)
84492 **
84493 ** The left-hand side (LHS) is a scalar expression.  The right-hand side (RHS)
84494 ** is an array of zero or more values.  The expression is true if the LHS is
84495 ** contained within the RHS.  The value of the expression is unknown (NULL)
84496 ** if the LHS is NULL or if the LHS is not contained within the RHS and the
84497 ** RHS contains one or more NULL values.
84498 **
84499 ** This routine generates code that jumps to destIfFalse if the LHS is not 
84500 ** contained within the RHS.  If due to NULLs we cannot determine if the LHS
84501 ** is contained in the RHS then jump to destIfNull.  If the LHS is contained
84502 ** within the RHS then fall through.
84503 */
84504 static void sqlite3ExprCodeIN(
84505   Parse *pParse,        /* Parsing and code generating context */
84506   Expr *pExpr,          /* The IN expression */
84507   int destIfFalse,      /* Jump here if LHS is not contained in the RHS */
84508   int destIfNull        /* Jump here if the results are unknown due to NULLs */
84509 ){
84510   int rRhsHasNull = 0;  /* Register that is true if RHS contains NULL values */
84511   char affinity;        /* Comparison affinity to use */
84512   int eType;            /* Type of the RHS */
84513   int r1;               /* Temporary use register */
84514   Vdbe *v;              /* Statement under construction */
84515
84516   /* Compute the RHS.   After this step, the table with cursor
84517   ** pExpr->iTable will contains the values that make up the RHS.
84518   */
84519   v = pParse->pVdbe;
84520   assert( v!=0 );       /* OOM detected prior to this routine */
84521   VdbeNoopComment((v, "begin IN expr"));
84522   eType = sqlite3FindInIndex(pParse, pExpr,
84523                              IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
84524                              destIfFalse==destIfNull ? 0 : &rRhsHasNull);
84525
84526   /* Figure out the affinity to use to create a key from the results
84527   ** of the expression. affinityStr stores a static string suitable for
84528   ** P4 of OP_MakeRecord.
84529   */
84530   affinity = comparisonAffinity(pExpr);
84531
84532   /* Code the LHS, the <expr> from "<expr> IN (...)".
84533   */
84534   sqlite3ExprCachePush(pParse);
84535   r1 = sqlite3GetTempReg(pParse);
84536   sqlite3ExprCode(pParse, pExpr->pLeft, r1);
84537
84538   /* If sqlite3FindInIndex() did not find or create an index that is
84539   ** suitable for evaluating the IN operator, then evaluate using a
84540   ** sequence of comparisons.
84541   */
84542   if( eType==IN_INDEX_NOOP ){
84543     ExprList *pList = pExpr->x.pList;
84544     CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
84545     int labelOk = sqlite3VdbeMakeLabel(v);
84546     int r2, regToFree;
84547     int regCkNull = 0;
84548     int ii;
84549     assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
84550     if( destIfNull!=destIfFalse ){
84551       regCkNull = sqlite3GetTempReg(pParse);
84552       sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
84553     }
84554     for(ii=0; ii<pList->nExpr; ii++){
84555       r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
84556       if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
84557         sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
84558       }
84559       if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
84560         sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
84561                           (void*)pColl, P4_COLLSEQ);
84562         VdbeCoverageIf(v, ii<pList->nExpr-1);
84563         VdbeCoverageIf(v, ii==pList->nExpr-1);
84564         sqlite3VdbeChangeP5(v, affinity);
84565       }else{
84566         assert( destIfNull==destIfFalse );
84567         sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
84568                           (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
84569         sqlite3VdbeChangeP5(v, affinity | SQLITE_JUMPIFNULL);
84570       }
84571       sqlite3ReleaseTempReg(pParse, regToFree);
84572     }
84573     if( regCkNull ){
84574       sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
84575       sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
84576     }
84577     sqlite3VdbeResolveLabel(v, labelOk);
84578     sqlite3ReleaseTempReg(pParse, regCkNull);
84579   }else{
84580   
84581     /* If the LHS is NULL, then the result is either false or NULL depending
84582     ** on whether the RHS is empty or not, respectively.
84583     */
84584     if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
84585       if( destIfNull==destIfFalse ){
84586         /* Shortcut for the common case where the false and NULL outcomes are
84587         ** the same. */
84588         sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
84589       }else{
84590         int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
84591         sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
84592         VdbeCoverage(v);
84593         sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
84594         sqlite3VdbeJumpHere(v, addr1);
84595       }
84596     }
84597   
84598     if( eType==IN_INDEX_ROWID ){
84599       /* In this case, the RHS is the ROWID of table b-tree
84600       */
84601       sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); VdbeCoverage(v);
84602       sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
84603       VdbeCoverage(v);
84604     }else{
84605       /* In this case, the RHS is an index b-tree.
84606       */
84607       sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
84608   
84609       /* If the set membership test fails, then the result of the 
84610       ** "x IN (...)" expression must be either 0 or NULL. If the set
84611       ** contains no NULL values, then the result is 0. If the set 
84612       ** contains one or more NULL values, then the result of the
84613       ** expression is also NULL.
84614       */
84615       assert( destIfFalse!=destIfNull || rRhsHasNull==0 );
84616       if( rRhsHasNull==0 ){
84617         /* This branch runs if it is known at compile time that the RHS
84618         ** cannot contain NULL values. This happens as the result
84619         ** of a "NOT NULL" constraint in the database schema.
84620         **
84621         ** Also run this branch if NULL is equivalent to FALSE
84622         ** for this particular IN operator.
84623         */
84624         sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
84625         VdbeCoverage(v);
84626       }else{
84627         /* In this branch, the RHS of the IN might contain a NULL and
84628         ** the presence of a NULL on the RHS makes a difference in the
84629         ** outcome.
84630         */
84631         int j1;
84632   
84633         /* First check to see if the LHS is contained in the RHS.  If so,
84634         ** then the answer is TRUE the presence of NULLs in the RHS does
84635         ** not matter.  If the LHS is not contained in the RHS, then the
84636         ** answer is NULL if the RHS contains NULLs and the answer is
84637         ** FALSE if the RHS is NULL-free.
84638         */
84639         j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
84640         VdbeCoverage(v);
84641         sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
84642         VdbeCoverage(v);
84643         sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
84644         sqlite3VdbeJumpHere(v, j1);
84645       }
84646     }
84647   }
84648   sqlite3ReleaseTempReg(pParse, r1);
84649   sqlite3ExprCachePop(pParse);
84650   VdbeComment((v, "end IN expr"));
84651 }
84652 #endif /* SQLITE_OMIT_SUBQUERY */
84653
84654 /*
84655 ** Duplicate an 8-byte value
84656 */
84657 static char *dup8bytes(Vdbe *v, const char *in){
84658   char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
84659   if( out ){
84660     memcpy(out, in, 8);
84661   }
84662   return out;
84663 }
84664
84665 #ifndef SQLITE_OMIT_FLOATING_POINT
84666 /*
84667 ** Generate an instruction that will put the floating point
84668 ** value described by z[0..n-1] into register iMem.
84669 **
84670 ** The z[] string will probably not be zero-terminated.  But the 
84671 ** z[n] character is guaranteed to be something that does not look
84672 ** like the continuation of the number.
84673 */
84674 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
84675   if( ALWAYS(z!=0) ){
84676     double value;
84677     char *zV;
84678     sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
84679     assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
84680     if( negateFlag ) value = -value;
84681     zV = dup8bytes(v, (char*)&value);
84682     sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
84683   }
84684 }
84685 #endif
84686
84687
84688 /*
84689 ** Generate an instruction that will put the integer describe by
84690 ** text z[0..n-1] into register iMem.
84691 **
84692 ** Expr.u.zToken is always UTF8 and zero-terminated.
84693 */
84694 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
84695   Vdbe *v = pParse->pVdbe;
84696   if( pExpr->flags & EP_IntValue ){
84697     int i = pExpr->u.iValue;
84698     assert( i>=0 );
84699     if( negFlag ) i = -i;
84700     sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
84701   }else{
84702     int c;
84703     i64 value;
84704     const char *z = pExpr->u.zToken;
84705     assert( z!=0 );
84706     c = sqlite3DecOrHexToI64(z, &value);
84707     if( c==0 || (c==2 && negFlag) ){
84708       char *zV;
84709       if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
84710       zV = dup8bytes(v, (char*)&value);
84711       sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
84712     }else{
84713 #ifdef SQLITE_OMIT_FLOATING_POINT
84714       sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
84715 #else
84716 #ifndef SQLITE_OMIT_HEX_INTEGER
84717       if( sqlite3_strnicmp(z,"0x",2)==0 ){
84718         sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
84719       }else
84720 #endif
84721       {
84722         codeReal(v, z, negFlag, iMem);
84723       }
84724 #endif
84725     }
84726   }
84727 }
84728
84729 /*
84730 ** Clear a cache entry.
84731 */
84732 static void cacheEntryClear(Parse *pParse, struct yColCache *p){
84733   if( p->tempReg ){
84734     if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
84735       pParse->aTempReg[pParse->nTempReg++] = p->iReg;
84736     }
84737     p->tempReg = 0;
84738   }
84739 }
84740
84741
84742 /*
84743 ** Record in the column cache that a particular column from a
84744 ** particular table is stored in a particular register.
84745 */
84746 SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
84747   int i;
84748   int minLru;
84749   int idxLru;
84750   struct yColCache *p;
84751
84752   /* Unless an error has occurred, register numbers are always positive. */
84753   assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
84754   assert( iCol>=-1 && iCol<32768 );  /* Finite column numbers */
84755
84756   /* The SQLITE_ColumnCache flag disables the column cache.  This is used
84757   ** for testing only - to verify that SQLite always gets the same answer
84758   ** with and without the column cache.
84759   */
84760   if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
84761
84762   /* First replace any existing entry.
84763   **
84764   ** Actually, the way the column cache is currently used, we are guaranteed
84765   ** that the object will never already be in cache.  Verify this guarantee.
84766   */
84767 #ifndef NDEBUG
84768   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
84769     assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
84770   }
84771 #endif
84772
84773   /* Find an empty slot and replace it */
84774   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
84775     if( p->iReg==0 ){
84776       p->iLevel = pParse->iCacheLevel;
84777       p->iTable = iTab;
84778       p->iColumn = iCol;
84779       p->iReg = iReg;
84780       p->tempReg = 0;
84781       p->lru = pParse->iCacheCnt++;
84782       return;
84783     }
84784   }
84785
84786   /* Replace the last recently used */
84787   minLru = 0x7fffffff;
84788   idxLru = -1;
84789   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
84790     if( p->lru<minLru ){
84791       idxLru = i;
84792       minLru = p->lru;
84793     }
84794   }
84795   if( ALWAYS(idxLru>=0) ){
84796     p = &pParse->aColCache[idxLru];
84797     p->iLevel = pParse->iCacheLevel;
84798     p->iTable = iTab;
84799     p->iColumn = iCol;
84800     p->iReg = iReg;
84801     p->tempReg = 0;
84802     p->lru = pParse->iCacheCnt++;
84803     return;
84804   }
84805 }
84806
84807 /*
84808 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
84809 ** Purge the range of registers from the column cache.
84810 */
84811 SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
84812   int i;
84813   int iLast = iReg + nReg - 1;
84814   struct yColCache *p;
84815   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
84816     int r = p->iReg;
84817     if( r>=iReg && r<=iLast ){
84818       cacheEntryClear(pParse, p);
84819       p->iReg = 0;
84820     }
84821   }
84822 }
84823
84824 /*
84825 ** Remember the current column cache context.  Any new entries added
84826 ** added to the column cache after this call are removed when the
84827 ** corresponding pop occurs.
84828 */
84829 SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
84830   pParse->iCacheLevel++;
84831 #ifdef SQLITE_DEBUG
84832   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
84833     printf("PUSH to %d\n", pParse->iCacheLevel);
84834   }
84835 #endif
84836 }
84837
84838 /*
84839 ** Remove from the column cache any entries that were added since the
84840 ** the previous sqlite3ExprCachePush operation.  In other words, restore
84841 ** the cache to the state it was in prior the most recent Push.
84842 */
84843 SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
84844   int i;
84845   struct yColCache *p;
84846   assert( pParse->iCacheLevel>=1 );
84847   pParse->iCacheLevel--;
84848 #ifdef SQLITE_DEBUG
84849   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
84850     printf("POP  to %d\n", pParse->iCacheLevel);
84851   }
84852 #endif
84853   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
84854     if( p->iReg && p->iLevel>pParse->iCacheLevel ){
84855       cacheEntryClear(pParse, p);
84856       p->iReg = 0;
84857     }
84858   }
84859 }
84860
84861 /*
84862 ** When a cached column is reused, make sure that its register is
84863 ** no longer available as a temp register.  ticket #3879:  that same
84864 ** register might be in the cache in multiple places, so be sure to
84865 ** get them all.
84866 */
84867 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
84868   int i;
84869   struct yColCache *p;
84870   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
84871     if( p->iReg==iReg ){
84872       p->tempReg = 0;
84873     }
84874   }
84875 }
84876
84877 /*
84878 ** Generate code to extract the value of the iCol-th column of a table.
84879 */
84880 SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
84881   Vdbe *v,        /* The VDBE under construction */
84882   Table *pTab,    /* The table containing the value */
84883   int iTabCur,    /* The table cursor.  Or the PK cursor for WITHOUT ROWID */
84884   int iCol,       /* Index of the column to extract */
84885   int regOut      /* Extract the value into this register */
84886 ){
84887   if( iCol<0 || iCol==pTab->iPKey ){
84888     sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
84889   }else{
84890     int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
84891     int x = iCol;
84892     if( !HasRowid(pTab) ){
84893       x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
84894     }
84895     sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
84896   }
84897   if( iCol>=0 ){
84898     sqlite3ColumnDefault(v, pTab, iCol, regOut);
84899   }
84900 }
84901
84902 /*
84903 ** Generate code that will extract the iColumn-th column from
84904 ** table pTab and store the column value in a register.  An effort
84905 ** is made to store the column value in register iReg, but this is
84906 ** not guaranteed.  The location of the column value is returned.
84907 **
84908 ** There must be an open cursor to pTab in iTable when this routine
84909 ** is called.  If iColumn<0 then code is generated that extracts the rowid.
84910 */
84911 SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
84912   Parse *pParse,   /* Parsing and code generating context */
84913   Table *pTab,     /* Description of the table we are reading from */
84914   int iColumn,     /* Index of the table column */
84915   int iTable,      /* The cursor pointing to the table */
84916   int iReg,        /* Store results here */
84917   u8 p5            /* P5 value for OP_Column */
84918 ){
84919   Vdbe *v = pParse->pVdbe;
84920   int i;
84921   struct yColCache *p;
84922
84923   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
84924     if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
84925       p->lru = pParse->iCacheCnt++;
84926       sqlite3ExprCachePinRegister(pParse, p->iReg);
84927       return p->iReg;
84928     }
84929   }  
84930   assert( v!=0 );
84931   sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
84932   if( p5 ){
84933     sqlite3VdbeChangeP5(v, p5);
84934   }else{   
84935     sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
84936   }
84937   return iReg;
84938 }
84939
84940 /*
84941 ** Clear all column cache entries.
84942 */
84943 SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
84944   int i;
84945   struct yColCache *p;
84946
84947 #if SQLITE_DEBUG
84948   if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
84949     printf("CLEAR\n");
84950   }
84951 #endif
84952   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
84953     if( p->iReg ){
84954       cacheEntryClear(pParse, p);
84955       p->iReg = 0;
84956     }
84957   }
84958 }
84959
84960 /*
84961 ** Record the fact that an affinity change has occurred on iCount
84962 ** registers starting with iStart.
84963 */
84964 SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
84965   sqlite3ExprCacheRemove(pParse, iStart, iCount);
84966 }
84967
84968 /*
84969 ** Generate code to move content from registers iFrom...iFrom+nReg-1
84970 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
84971 */
84972 SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
84973   assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
84974   sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
84975   sqlite3ExprCacheRemove(pParse, iFrom, nReg);
84976 }
84977
84978 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
84979 /*
84980 ** Return true if any register in the range iFrom..iTo (inclusive)
84981 ** is used as part of the column cache.
84982 **
84983 ** This routine is used within assert() and testcase() macros only
84984 ** and does not appear in a normal build.
84985 */
84986 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
84987   int i;
84988   struct yColCache *p;
84989   for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
84990     int r = p->iReg;
84991     if( r>=iFrom && r<=iTo ) return 1;    /*NO_TEST*/
84992   }
84993   return 0;
84994 }
84995 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
84996
84997 /*
84998 ** Convert an expression node to a TK_REGISTER
84999 */
85000 static void exprToRegister(Expr *p, int iReg){
85001   p->op2 = p->op;
85002   p->op = TK_REGISTER;
85003   p->iTable = iReg;
85004   ExprClearProperty(p, EP_Skip);
85005 }
85006
85007 /*
85008 ** Generate code into the current Vdbe to evaluate the given
85009 ** expression.  Attempt to store the results in register "target".
85010 ** Return the register where results are stored.
85011 **
85012 ** With this routine, there is no guarantee that results will
85013 ** be stored in target.  The result might be stored in some other
85014 ** register if it is convenient to do so.  The calling function
85015 ** must check the return code and move the results to the desired
85016 ** register.
85017 */
85018 SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
85019   Vdbe *v = pParse->pVdbe;  /* The VM under construction */
85020   int op;                   /* The opcode being coded */
85021   int inReg = target;       /* Results stored in register inReg */
85022   int regFree1 = 0;         /* If non-zero free this temporary register */
85023   int regFree2 = 0;         /* If non-zero free this temporary register */
85024   int r1, r2, r3, r4;       /* Various register numbers */
85025   sqlite3 *db = pParse->db; /* The database connection */
85026   Expr tempX;               /* Temporary expression node */
85027
85028   assert( target>0 && target<=pParse->nMem );
85029   if( v==0 ){
85030     assert( pParse->db->mallocFailed );
85031     return 0;
85032   }
85033
85034   if( pExpr==0 ){
85035     op = TK_NULL;
85036   }else{
85037     op = pExpr->op;
85038   }
85039   switch( op ){
85040     case TK_AGG_COLUMN: {
85041       AggInfo *pAggInfo = pExpr->pAggInfo;
85042       struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
85043       if( !pAggInfo->directMode ){
85044         assert( pCol->iMem>0 );
85045         inReg = pCol->iMem;
85046         break;
85047       }else if( pAggInfo->useSortingIdx ){
85048         sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
85049                               pCol->iSorterColumn, target);
85050         break;
85051       }
85052       /* Otherwise, fall thru into the TK_COLUMN case */
85053     }
85054     case TK_COLUMN: {
85055       int iTab = pExpr->iTable;
85056       if( iTab<0 ){
85057         if( pParse->ckBase>0 ){
85058           /* Generating CHECK constraints or inserting into partial index */
85059           inReg = pExpr->iColumn + pParse->ckBase;
85060           break;
85061         }else{
85062           /* Deleting from a partial index */
85063           iTab = pParse->iPartIdxTab;
85064         }
85065       }
85066       inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
85067                                pExpr->iColumn, iTab, target,
85068                                pExpr->op2);
85069       break;
85070     }
85071     case TK_INTEGER: {
85072       codeInteger(pParse, pExpr, 0, target);
85073       break;
85074     }
85075 #ifndef SQLITE_OMIT_FLOATING_POINT
85076     case TK_FLOAT: {
85077       assert( !ExprHasProperty(pExpr, EP_IntValue) );
85078       codeReal(v, pExpr->u.zToken, 0, target);
85079       break;
85080     }
85081 #endif
85082     case TK_STRING: {
85083       assert( !ExprHasProperty(pExpr, EP_IntValue) );
85084       sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
85085       break;
85086     }
85087     case TK_NULL: {
85088       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
85089       break;
85090     }
85091 #ifndef SQLITE_OMIT_BLOB_LITERAL
85092     case TK_BLOB: {
85093       int n;
85094       const char *z;
85095       char *zBlob;
85096       assert( !ExprHasProperty(pExpr, EP_IntValue) );
85097       assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
85098       assert( pExpr->u.zToken[1]=='\'' );
85099       z = &pExpr->u.zToken[2];
85100       n = sqlite3Strlen30(z) - 1;
85101       assert( z[n]=='\'' );
85102       zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
85103       sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
85104       break;
85105     }
85106 #endif
85107     case TK_VARIABLE: {
85108       assert( !ExprHasProperty(pExpr, EP_IntValue) );
85109       assert( pExpr->u.zToken!=0 );
85110       assert( pExpr->u.zToken[0]!=0 );
85111       sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
85112       if( pExpr->u.zToken[1]!=0 ){
85113         assert( pExpr->u.zToken[0]=='?' 
85114              || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
85115         sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
85116       }
85117       break;
85118     }
85119     case TK_REGISTER: {
85120       inReg = pExpr->iTable;
85121       break;
85122     }
85123     case TK_AS: {
85124       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
85125       break;
85126     }
85127 #ifndef SQLITE_OMIT_CAST
85128     case TK_CAST: {
85129       /* Expressions of the form:   CAST(pLeft AS token) */
85130       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
85131       if( inReg!=target ){
85132         sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
85133         inReg = target;
85134       }
85135       sqlite3VdbeAddOp2(v, OP_Cast, target,
85136                         sqlite3AffinityType(pExpr->u.zToken, 0));
85137       testcase( usedAsColumnCache(pParse, inReg, inReg) );
85138       sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
85139       break;
85140     }
85141 #endif /* SQLITE_OMIT_CAST */
85142     case TK_LT:
85143     case TK_LE:
85144     case TK_GT:
85145     case TK_GE:
85146     case TK_NE:
85147     case TK_EQ: {
85148       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
85149       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
85150       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
85151                   r1, r2, inReg, SQLITE_STOREP2);
85152       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
85153       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
85154       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
85155       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
85156       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
85157       assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
85158       testcase( regFree1==0 );
85159       testcase( regFree2==0 );
85160       break;
85161     }
85162     case TK_IS:
85163     case TK_ISNOT: {
85164       testcase( op==TK_IS );
85165       testcase( op==TK_ISNOT );
85166       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
85167       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
85168       op = (op==TK_IS) ? TK_EQ : TK_NE;
85169       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
85170                   r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
85171       VdbeCoverageIf(v, op==TK_EQ);
85172       VdbeCoverageIf(v, op==TK_NE);
85173       testcase( regFree1==0 );
85174       testcase( regFree2==0 );
85175       break;
85176     }
85177     case TK_AND:
85178     case TK_OR:
85179     case TK_PLUS:
85180     case TK_STAR:
85181     case TK_MINUS:
85182     case TK_REM:
85183     case TK_BITAND:
85184     case TK_BITOR:
85185     case TK_SLASH:
85186     case TK_LSHIFT:
85187     case TK_RSHIFT: 
85188     case TK_CONCAT: {
85189       assert( TK_AND==OP_And );            testcase( op==TK_AND );
85190       assert( TK_OR==OP_Or );              testcase( op==TK_OR );
85191       assert( TK_PLUS==OP_Add );           testcase( op==TK_PLUS );
85192       assert( TK_MINUS==OP_Subtract );     testcase( op==TK_MINUS );
85193       assert( TK_REM==OP_Remainder );      testcase( op==TK_REM );
85194       assert( TK_BITAND==OP_BitAnd );      testcase( op==TK_BITAND );
85195       assert( TK_BITOR==OP_BitOr );        testcase( op==TK_BITOR );
85196       assert( TK_SLASH==OP_Divide );       testcase( op==TK_SLASH );
85197       assert( TK_LSHIFT==OP_ShiftLeft );   testcase( op==TK_LSHIFT );
85198       assert( TK_RSHIFT==OP_ShiftRight );  testcase( op==TK_RSHIFT );
85199       assert( TK_CONCAT==OP_Concat );      testcase( op==TK_CONCAT );
85200       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
85201       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
85202       sqlite3VdbeAddOp3(v, op, r2, r1, target);
85203       testcase( regFree1==0 );
85204       testcase( regFree2==0 );
85205       break;
85206     }
85207     case TK_UMINUS: {
85208       Expr *pLeft = pExpr->pLeft;
85209       assert( pLeft );
85210       if( pLeft->op==TK_INTEGER ){
85211         codeInteger(pParse, pLeft, 1, target);
85212 #ifndef SQLITE_OMIT_FLOATING_POINT
85213       }else if( pLeft->op==TK_FLOAT ){
85214         assert( !ExprHasProperty(pExpr, EP_IntValue) );
85215         codeReal(v, pLeft->u.zToken, 1, target);
85216 #endif
85217       }else{
85218         tempX.op = TK_INTEGER;
85219         tempX.flags = EP_IntValue|EP_TokenOnly;
85220         tempX.u.iValue = 0;
85221         r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
85222         r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
85223         sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
85224         testcase( regFree2==0 );
85225       }
85226       inReg = target;
85227       break;
85228     }
85229     case TK_BITNOT:
85230     case TK_NOT: {
85231       assert( TK_BITNOT==OP_BitNot );   testcase( op==TK_BITNOT );
85232       assert( TK_NOT==OP_Not );         testcase( op==TK_NOT );
85233       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
85234       testcase( regFree1==0 );
85235       inReg = target;
85236       sqlite3VdbeAddOp2(v, op, r1, inReg);
85237       break;
85238     }
85239     case TK_ISNULL:
85240     case TK_NOTNULL: {
85241       int addr;
85242       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
85243       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
85244       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
85245       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
85246       testcase( regFree1==0 );
85247       addr = sqlite3VdbeAddOp1(v, op, r1);
85248       VdbeCoverageIf(v, op==TK_ISNULL);
85249       VdbeCoverageIf(v, op==TK_NOTNULL);
85250       sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
85251       sqlite3VdbeJumpHere(v, addr);
85252       break;
85253     }
85254     case TK_AGG_FUNCTION: {
85255       AggInfo *pInfo = pExpr->pAggInfo;
85256       if( pInfo==0 ){
85257         assert( !ExprHasProperty(pExpr, EP_IntValue) );
85258         sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
85259       }else{
85260         inReg = pInfo->aFunc[pExpr->iAgg].iMem;
85261       }
85262       break;
85263     }
85264     case TK_FUNCTION: {
85265       ExprList *pFarg;       /* List of function arguments */
85266       int nFarg;             /* Number of function arguments */
85267       FuncDef *pDef;         /* The function definition object */
85268       int nId;               /* Length of the function name in bytes */
85269       const char *zId;       /* The function name */
85270       u32 constMask = 0;     /* Mask of function arguments that are constant */
85271       int i;                 /* Loop counter */
85272       u8 enc = ENC(db);      /* The text encoding used by this database */
85273       CollSeq *pColl = 0;    /* A collating sequence */
85274
85275       assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
85276       if( ExprHasProperty(pExpr, EP_TokenOnly) ){
85277         pFarg = 0;
85278       }else{
85279         pFarg = pExpr->x.pList;
85280       }
85281       nFarg = pFarg ? pFarg->nExpr : 0;
85282       assert( !ExprHasProperty(pExpr, EP_IntValue) );
85283       zId = pExpr->u.zToken;
85284       nId = sqlite3Strlen30(zId);
85285       pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
85286       if( pDef==0 || pDef->xFunc==0 ){
85287         sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
85288         break;
85289       }
85290
85291       /* Attempt a direct implementation of the built-in COALESCE() and
85292       ** IFNULL() functions.  This avoids unnecessary evaluation of
85293       ** arguments past the first non-NULL argument.
85294       */
85295       if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
85296         int endCoalesce = sqlite3VdbeMakeLabel(v);
85297         assert( nFarg>=2 );
85298         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
85299         for(i=1; i<nFarg; i++){
85300           sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
85301           VdbeCoverage(v);
85302           sqlite3ExprCacheRemove(pParse, target, 1);
85303           sqlite3ExprCachePush(pParse);
85304           sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
85305           sqlite3ExprCachePop(pParse);
85306         }
85307         sqlite3VdbeResolveLabel(v, endCoalesce);
85308         break;
85309       }
85310
85311       /* The UNLIKELY() function is a no-op.  The result is the value
85312       ** of the first argument.
85313       */
85314       if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
85315         assert( nFarg>=1 );
85316         sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
85317         break;
85318       }
85319
85320       for(i=0; i<nFarg; i++){
85321         if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
85322           testcase( i==31 );
85323           constMask |= MASKBIT32(i);
85324         }
85325         if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
85326           pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
85327         }
85328       }
85329       if( pFarg ){
85330         if( constMask ){
85331           r1 = pParse->nMem+1;
85332           pParse->nMem += nFarg;
85333         }else{
85334           r1 = sqlite3GetTempRange(pParse, nFarg);
85335         }
85336
85337         /* For length() and typeof() functions with a column argument,
85338         ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
85339         ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
85340         ** loading.
85341         */
85342         if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
85343           u8 exprOp;
85344           assert( nFarg==1 );
85345           assert( pFarg->a[0].pExpr!=0 );
85346           exprOp = pFarg->a[0].pExpr->op;
85347           if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
85348             assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
85349             assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
85350             testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
85351             pFarg->a[0].pExpr->op2 = 
85352                   pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
85353           }
85354         }
85355
85356         sqlite3ExprCachePush(pParse);     /* Ticket 2ea2425d34be */
85357         sqlite3ExprCodeExprList(pParse, pFarg, r1,
85358                                 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
85359         sqlite3ExprCachePop(pParse);      /* Ticket 2ea2425d34be */
85360       }else{
85361         r1 = 0;
85362       }
85363 #ifndef SQLITE_OMIT_VIRTUALTABLE
85364       /* Possibly overload the function if the first argument is
85365       ** a virtual table column.
85366       **
85367       ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
85368       ** second argument, not the first, as the argument to test to
85369       ** see if it is a column in a virtual table.  This is done because
85370       ** the left operand of infix functions (the operand we want to
85371       ** control overloading) ends up as the second argument to the
85372       ** function.  The expression "A glob B" is equivalent to 
85373       ** "glob(B,A).  We want to use the A in "A glob B" to test
85374       ** for function overloading.  But we use the B term in "glob(B,A)".
85375       */
85376       if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
85377         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
85378       }else if( nFarg>0 ){
85379         pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
85380       }
85381 #endif
85382       if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
85383         if( !pColl ) pColl = db->pDfltColl; 
85384         sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
85385       }
85386       sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
85387                         (char*)pDef, P4_FUNCDEF);
85388       sqlite3VdbeChangeP5(v, (u8)nFarg);
85389       if( nFarg && constMask==0 ){
85390         sqlite3ReleaseTempRange(pParse, r1, nFarg);
85391       }
85392       break;
85393     }
85394 #ifndef SQLITE_OMIT_SUBQUERY
85395     case TK_EXISTS:
85396     case TK_SELECT: {
85397       testcase( op==TK_EXISTS );
85398       testcase( op==TK_SELECT );
85399       inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
85400       break;
85401     }
85402     case TK_IN: {
85403       int destIfFalse = sqlite3VdbeMakeLabel(v);
85404       int destIfNull = sqlite3VdbeMakeLabel(v);
85405       sqlite3VdbeAddOp2(v, OP_Null, 0, target);
85406       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
85407       sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
85408       sqlite3VdbeResolveLabel(v, destIfFalse);
85409       sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
85410       sqlite3VdbeResolveLabel(v, destIfNull);
85411       break;
85412     }
85413 #endif /* SQLITE_OMIT_SUBQUERY */
85414
85415
85416     /*
85417     **    x BETWEEN y AND z
85418     **
85419     ** This is equivalent to
85420     **
85421     **    x>=y AND x<=z
85422     **
85423     ** X is stored in pExpr->pLeft.
85424     ** Y is stored in pExpr->pList->a[0].pExpr.
85425     ** Z is stored in pExpr->pList->a[1].pExpr.
85426     */
85427     case TK_BETWEEN: {
85428       Expr *pLeft = pExpr->pLeft;
85429       struct ExprList_item *pLItem = pExpr->x.pList->a;
85430       Expr *pRight = pLItem->pExpr;
85431
85432       r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
85433       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
85434       testcase( regFree1==0 );
85435       testcase( regFree2==0 );
85436       r3 = sqlite3GetTempReg(pParse);
85437       r4 = sqlite3GetTempReg(pParse);
85438       codeCompare(pParse, pLeft, pRight, OP_Ge,
85439                   r1, r2, r3, SQLITE_STOREP2);  VdbeCoverage(v);
85440       pLItem++;
85441       pRight = pLItem->pExpr;
85442       sqlite3ReleaseTempReg(pParse, regFree2);
85443       r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
85444       testcase( regFree2==0 );
85445       codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
85446       VdbeCoverage(v);
85447       sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
85448       sqlite3ReleaseTempReg(pParse, r3);
85449       sqlite3ReleaseTempReg(pParse, r4);
85450       break;
85451     }
85452     case TK_COLLATE: 
85453     case TK_UPLUS: {
85454       inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
85455       break;
85456     }
85457
85458     case TK_TRIGGER: {
85459       /* If the opcode is TK_TRIGGER, then the expression is a reference
85460       ** to a column in the new.* or old.* pseudo-tables available to
85461       ** trigger programs. In this case Expr.iTable is set to 1 for the
85462       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
85463       ** is set to the column of the pseudo-table to read, or to -1 to
85464       ** read the rowid field.
85465       **
85466       ** The expression is implemented using an OP_Param opcode. The p1
85467       ** parameter is set to 0 for an old.rowid reference, or to (i+1)
85468       ** to reference another column of the old.* pseudo-table, where 
85469       ** i is the index of the column. For a new.rowid reference, p1 is
85470       ** set to (n+1), where n is the number of columns in each pseudo-table.
85471       ** For a reference to any other column in the new.* pseudo-table, p1
85472       ** is set to (n+2+i), where n and i are as defined previously. For
85473       ** example, if the table on which triggers are being fired is
85474       ** declared as:
85475       **
85476       **   CREATE TABLE t1(a, b);
85477       **
85478       ** Then p1 is interpreted as follows:
85479       **
85480       **   p1==0   ->    old.rowid     p1==3   ->    new.rowid
85481       **   p1==1   ->    old.a         p1==4   ->    new.a
85482       **   p1==2   ->    old.b         p1==5   ->    new.b       
85483       */
85484       Table *pTab = pExpr->pTab;
85485       int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
85486
85487       assert( pExpr->iTable==0 || pExpr->iTable==1 );
85488       assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
85489       assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
85490       assert( p1>=0 && p1<(pTab->nCol*2+2) );
85491
85492       sqlite3VdbeAddOp2(v, OP_Param, p1, target);
85493       VdbeComment((v, "%s.%s -> $%d",
85494         (pExpr->iTable ? "new" : "old"),
85495         (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
85496         target
85497       ));
85498
85499 #ifndef SQLITE_OMIT_FLOATING_POINT
85500       /* If the column has REAL affinity, it may currently be stored as an
85501       ** integer. Use OP_RealAffinity to make sure it is really real.
85502       **
85503       ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
85504       ** floating point when extracting it from the record.  */
85505       if( pExpr->iColumn>=0 
85506        && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
85507       ){
85508         sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
85509       }
85510 #endif
85511       break;
85512     }
85513
85514
85515     /*
85516     ** Form A:
85517     **   CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
85518     **
85519     ** Form B:
85520     **   CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
85521     **
85522     ** Form A is can be transformed into the equivalent form B as follows:
85523     **   CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
85524     **        WHEN x=eN THEN rN ELSE y END
85525     **
85526     ** X (if it exists) is in pExpr->pLeft.
85527     ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
85528     ** odd.  The Y is also optional.  If the number of elements in x.pList
85529     ** is even, then Y is omitted and the "otherwise" result is NULL.
85530     ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
85531     **
85532     ** The result of the expression is the Ri for the first matching Ei,
85533     ** or if there is no matching Ei, the ELSE term Y, or if there is
85534     ** no ELSE term, NULL.
85535     */
85536     default: assert( op==TK_CASE ); {
85537       int endLabel;                     /* GOTO label for end of CASE stmt */
85538       int nextCase;                     /* GOTO label for next WHEN clause */
85539       int nExpr;                        /* 2x number of WHEN terms */
85540       int i;                            /* Loop counter */
85541       ExprList *pEList;                 /* List of WHEN terms */
85542       struct ExprList_item *aListelem;  /* Array of WHEN terms */
85543       Expr opCompare;                   /* The X==Ei expression */
85544       Expr *pX;                         /* The X expression */
85545       Expr *pTest = 0;                  /* X==Ei (form A) or just Ei (form B) */
85546       VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
85547
85548       assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
85549       assert(pExpr->x.pList->nExpr > 0);
85550       pEList = pExpr->x.pList;
85551       aListelem = pEList->a;
85552       nExpr = pEList->nExpr;
85553       endLabel = sqlite3VdbeMakeLabel(v);
85554       if( (pX = pExpr->pLeft)!=0 ){
85555         tempX = *pX;
85556         testcase( pX->op==TK_COLUMN );
85557         exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
85558         testcase( regFree1==0 );
85559         opCompare.op = TK_EQ;
85560         opCompare.pLeft = &tempX;
85561         pTest = &opCompare;
85562         /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
85563         ** The value in regFree1 might get SCopy-ed into the file result.
85564         ** So make sure that the regFree1 register is not reused for other
85565         ** purposes and possibly overwritten.  */
85566         regFree1 = 0;
85567       }
85568       for(i=0; i<nExpr-1; i=i+2){
85569         sqlite3ExprCachePush(pParse);
85570         if( pX ){
85571           assert( pTest!=0 );
85572           opCompare.pRight = aListelem[i].pExpr;
85573         }else{
85574           pTest = aListelem[i].pExpr;
85575         }
85576         nextCase = sqlite3VdbeMakeLabel(v);
85577         testcase( pTest->op==TK_COLUMN );
85578         sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
85579         testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
85580         sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
85581         sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
85582         sqlite3ExprCachePop(pParse);
85583         sqlite3VdbeResolveLabel(v, nextCase);
85584       }
85585       if( (nExpr&1)!=0 ){
85586         sqlite3ExprCachePush(pParse);
85587         sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
85588         sqlite3ExprCachePop(pParse);
85589       }else{
85590         sqlite3VdbeAddOp2(v, OP_Null, 0, target);
85591       }
85592       assert( db->mallocFailed || pParse->nErr>0 
85593            || pParse->iCacheLevel==iCacheLevel );
85594       sqlite3VdbeResolveLabel(v, endLabel);
85595       break;
85596     }
85597 #ifndef SQLITE_OMIT_TRIGGER
85598     case TK_RAISE: {
85599       assert( pExpr->affinity==OE_Rollback 
85600            || pExpr->affinity==OE_Abort
85601            || pExpr->affinity==OE_Fail
85602            || pExpr->affinity==OE_Ignore
85603       );
85604       if( !pParse->pTriggerTab ){
85605         sqlite3ErrorMsg(pParse,
85606                        "RAISE() may only be used within a trigger-program");
85607         return 0;
85608       }
85609       if( pExpr->affinity==OE_Abort ){
85610         sqlite3MayAbort(pParse);
85611       }
85612       assert( !ExprHasProperty(pExpr, EP_IntValue) );
85613       if( pExpr->affinity==OE_Ignore ){
85614         sqlite3VdbeAddOp4(
85615             v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
85616         VdbeCoverage(v);
85617       }else{
85618         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
85619                               pExpr->affinity, pExpr->u.zToken, 0, 0);
85620       }
85621
85622       break;
85623     }
85624 #endif
85625   }
85626   sqlite3ReleaseTempReg(pParse, regFree1);
85627   sqlite3ReleaseTempReg(pParse, regFree2);
85628   return inReg;
85629 }
85630
85631 /*
85632 ** Factor out the code of the given expression to initialization time.
85633 */
85634 SQLITE_PRIVATE void sqlite3ExprCodeAtInit(
85635   Parse *pParse,    /* Parsing context */
85636   Expr *pExpr,      /* The expression to code when the VDBE initializes */
85637   int regDest,      /* Store the value in this register */
85638   u8 reusable       /* True if this expression is reusable */
85639 ){
85640   ExprList *p;
85641   assert( ConstFactorOk(pParse) );
85642   p = pParse->pConstExpr;
85643   pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
85644   p = sqlite3ExprListAppend(pParse, p, pExpr);
85645   if( p ){
85646      struct ExprList_item *pItem = &p->a[p->nExpr-1];
85647      pItem->u.iConstExprReg = regDest;
85648      pItem->reusable = reusable;
85649   }
85650   pParse->pConstExpr = p;
85651 }
85652
85653 /*
85654 ** Generate code to evaluate an expression and store the results
85655 ** into a register.  Return the register number where the results
85656 ** are stored.
85657 **
85658 ** If the register is a temporary register that can be deallocated,
85659 ** then write its number into *pReg.  If the result register is not
85660 ** a temporary, then set *pReg to zero.
85661 **
85662 ** If pExpr is a constant, then this routine might generate this
85663 ** code to fill the register in the initialization section of the
85664 ** VDBE program, in order to factor it out of the evaluation loop.
85665 */
85666 SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
85667   int r2;
85668   pExpr = sqlite3ExprSkipCollate(pExpr);
85669   if( ConstFactorOk(pParse)
85670    && pExpr->op!=TK_REGISTER
85671    && sqlite3ExprIsConstantNotJoin(pExpr)
85672   ){
85673     ExprList *p = pParse->pConstExpr;
85674     int i;
85675     *pReg  = 0;
85676     if( p ){
85677       struct ExprList_item *pItem;
85678       for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
85679         if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
85680           return pItem->u.iConstExprReg;
85681         }
85682       }
85683     }
85684     r2 = ++pParse->nMem;
85685     sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
85686   }else{
85687     int r1 = sqlite3GetTempReg(pParse);
85688     r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
85689     if( r2==r1 ){
85690       *pReg = r1;
85691     }else{
85692       sqlite3ReleaseTempReg(pParse, r1);
85693       *pReg = 0;
85694     }
85695   }
85696   return r2;
85697 }
85698
85699 /*
85700 ** Generate code that will evaluate expression pExpr and store the
85701 ** results in register target.  The results are guaranteed to appear
85702 ** in register target.
85703 */
85704 SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
85705   int inReg;
85706
85707   assert( target>0 && target<=pParse->nMem );
85708   if( pExpr && pExpr->op==TK_REGISTER ){
85709     sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
85710   }else{
85711     inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
85712     assert( pParse->pVdbe || pParse->db->mallocFailed );
85713     if( inReg!=target && pParse->pVdbe ){
85714       sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
85715     }
85716   }
85717 }
85718
85719 /*
85720 ** Generate code that will evaluate expression pExpr and store the
85721 ** results in register target.  The results are guaranteed to appear
85722 ** in register target.  If the expression is constant, then this routine
85723 ** might choose to code the expression at initialization time.
85724 */
85725 SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
85726   if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
85727     sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
85728   }else{
85729     sqlite3ExprCode(pParse, pExpr, target);
85730   }
85731 }
85732
85733 /*
85734 ** Generate code that evaluates the given expression and puts the result
85735 ** in register target.
85736 **
85737 ** Also make a copy of the expression results into another "cache" register
85738 ** and modify the expression so that the next time it is evaluated,
85739 ** the result is a copy of the cache register.
85740 **
85741 ** This routine is used for expressions that are used multiple 
85742 ** times.  They are evaluated once and the results of the expression
85743 ** are reused.
85744 */
85745 SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
85746   Vdbe *v = pParse->pVdbe;
85747   int iMem;
85748
85749   assert( target>0 );
85750   assert( pExpr->op!=TK_REGISTER );
85751   sqlite3ExprCode(pParse, pExpr, target);
85752   iMem = ++pParse->nMem;
85753   sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
85754   exprToRegister(pExpr, iMem);
85755 }
85756
85757 #ifdef SQLITE_DEBUG
85758 /*
85759 ** Generate a human-readable explanation of an expression tree.
85760 */
85761 SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
85762   const char *zBinOp = 0;   /* Binary operator */
85763   const char *zUniOp = 0;   /* Unary operator */
85764   pView = sqlite3TreeViewPush(pView, moreToFollow);
85765   if( pExpr==0 ){
85766     sqlite3TreeViewLine(pView, "nil");
85767     sqlite3TreeViewPop(pView);
85768     return;
85769   }
85770   switch( pExpr->op ){
85771     case TK_AGG_COLUMN: {
85772       sqlite3TreeViewLine(pView, "AGG{%d:%d}",
85773             pExpr->iTable, pExpr->iColumn);
85774       break;
85775     }
85776     case TK_COLUMN: {
85777       if( pExpr->iTable<0 ){
85778         /* This only happens when coding check constraints */
85779         sqlite3TreeViewLine(pView, "COLUMN(%d)", pExpr->iColumn);
85780       }else{
85781         sqlite3TreeViewLine(pView, "{%d:%d}",
85782                              pExpr->iTable, pExpr->iColumn);
85783       }
85784       break;
85785     }
85786     case TK_INTEGER: {
85787       if( pExpr->flags & EP_IntValue ){
85788         sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
85789       }else{
85790         sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
85791       }
85792       break;
85793     }
85794 #ifndef SQLITE_OMIT_FLOATING_POINT
85795     case TK_FLOAT: {
85796       sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
85797       break;
85798     }
85799 #endif
85800     case TK_STRING: {
85801       sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
85802       break;
85803     }
85804     case TK_NULL: {
85805       sqlite3TreeViewLine(pView,"NULL");
85806       break;
85807     }
85808 #ifndef SQLITE_OMIT_BLOB_LITERAL
85809     case TK_BLOB: {
85810       sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
85811       break;
85812     }
85813 #endif
85814     case TK_VARIABLE: {
85815       sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
85816                           pExpr->u.zToken, pExpr->iColumn);
85817       break;
85818     }
85819     case TK_REGISTER: {
85820       sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
85821       break;
85822     }
85823     case TK_AS: {
85824       sqlite3TreeViewLine(pView,"AS %Q", pExpr->u.zToken);
85825       sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
85826       break;
85827     }
85828     case TK_ID: {
85829       sqlite3TreeViewLine(pView,"ID %Q", pExpr->u.zToken);
85830       break;
85831     }
85832 #ifndef SQLITE_OMIT_CAST
85833     case TK_CAST: {
85834       /* Expressions of the form:   CAST(pLeft AS token) */
85835       sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
85836       sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
85837       break;
85838     }
85839 #endif /* SQLITE_OMIT_CAST */
85840     case TK_LT:      zBinOp = "LT";     break;
85841     case TK_LE:      zBinOp = "LE";     break;
85842     case TK_GT:      zBinOp = "GT";     break;
85843     case TK_GE:      zBinOp = "GE";     break;
85844     case TK_NE:      zBinOp = "NE";     break;
85845     case TK_EQ:      zBinOp = "EQ";     break;
85846     case TK_IS:      zBinOp = "IS";     break;
85847     case TK_ISNOT:   zBinOp = "ISNOT";  break;
85848     case TK_AND:     zBinOp = "AND";    break;
85849     case TK_OR:      zBinOp = "OR";     break;
85850     case TK_PLUS:    zBinOp = "ADD";    break;
85851     case TK_STAR:    zBinOp = "MUL";    break;
85852     case TK_MINUS:   zBinOp = "SUB";    break;
85853     case TK_REM:     zBinOp = "REM";    break;
85854     case TK_BITAND:  zBinOp = "BITAND"; break;
85855     case TK_BITOR:   zBinOp = "BITOR";  break;
85856     case TK_SLASH:   zBinOp = "DIV";    break;
85857     case TK_LSHIFT:  zBinOp = "LSHIFT"; break;
85858     case TK_RSHIFT:  zBinOp = "RSHIFT"; break;
85859     case TK_CONCAT:  zBinOp = "CONCAT"; break;
85860     case TK_DOT:     zBinOp = "DOT";    break;
85861
85862     case TK_UMINUS:  zUniOp = "UMINUS"; break;
85863     case TK_UPLUS:   zUniOp = "UPLUS";  break;
85864     case TK_BITNOT:  zUniOp = "BITNOT"; break;
85865     case TK_NOT:     zUniOp = "NOT";    break;
85866     case TK_ISNULL:  zUniOp = "ISNULL"; break;
85867     case TK_NOTNULL: zUniOp = "NOTNULL"; break;
85868
85869     case TK_COLLATE: {
85870       sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
85871       sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
85872       break;
85873     }
85874
85875     case TK_AGG_FUNCTION:
85876     case TK_FUNCTION: {
85877       ExprList *pFarg;       /* List of function arguments */
85878       if( ExprHasProperty(pExpr, EP_TokenOnly) ){
85879         pFarg = 0;
85880       }else{
85881         pFarg = pExpr->x.pList;
85882       }
85883       if( pExpr->op==TK_AGG_FUNCTION ){
85884         sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
85885                              pExpr->op2, pExpr->u.zToken);
85886       }else{
85887         sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
85888       }
85889       if( pFarg ){
85890         sqlite3TreeViewExprList(pView, pFarg, 0, 0);
85891       }
85892       break;
85893     }
85894 #ifndef SQLITE_OMIT_SUBQUERY
85895     case TK_EXISTS: {
85896       sqlite3TreeViewLine(pView, "EXISTS-expr");
85897       sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
85898       break;
85899     }
85900     case TK_SELECT: {
85901       sqlite3TreeViewLine(pView, "SELECT-expr");
85902       sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
85903       break;
85904     }
85905     case TK_IN: {
85906       sqlite3TreeViewLine(pView, "IN");
85907       sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
85908       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
85909         sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
85910       }else{
85911         sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
85912       }
85913       break;
85914     }
85915 #endif /* SQLITE_OMIT_SUBQUERY */
85916
85917     /*
85918     **    x BETWEEN y AND z
85919     **
85920     ** This is equivalent to
85921     **
85922     **    x>=y AND x<=z
85923     **
85924     ** X is stored in pExpr->pLeft.
85925     ** Y is stored in pExpr->pList->a[0].pExpr.
85926     ** Z is stored in pExpr->pList->a[1].pExpr.
85927     */
85928     case TK_BETWEEN: {
85929       Expr *pX = pExpr->pLeft;
85930       Expr *pY = pExpr->x.pList->a[0].pExpr;
85931       Expr *pZ = pExpr->x.pList->a[1].pExpr;
85932       sqlite3TreeViewLine(pView, "BETWEEN");
85933       sqlite3TreeViewExpr(pView, pX, 1);
85934       sqlite3TreeViewExpr(pView, pY, 1);
85935       sqlite3TreeViewExpr(pView, pZ, 0);
85936       break;
85937     }
85938     case TK_TRIGGER: {
85939       /* If the opcode is TK_TRIGGER, then the expression is a reference
85940       ** to a column in the new.* or old.* pseudo-tables available to
85941       ** trigger programs. In this case Expr.iTable is set to 1 for the
85942       ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
85943       ** is set to the column of the pseudo-table to read, or to -1 to
85944       ** read the rowid field.
85945       */
85946       sqlite3TreeViewLine(pView, "%s(%d)", 
85947           pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
85948       break;
85949     }
85950     case TK_CASE: {
85951       sqlite3TreeViewLine(pView, "CASE");
85952       sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
85953       sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
85954       break;
85955     }
85956 #ifndef SQLITE_OMIT_TRIGGER
85957     case TK_RAISE: {
85958       const char *zType = "unk";
85959       switch( pExpr->affinity ){
85960         case OE_Rollback:   zType = "rollback";  break;
85961         case OE_Abort:      zType = "abort";     break;
85962         case OE_Fail:       zType = "fail";      break;
85963         case OE_Ignore:     zType = "ignore";    break;
85964       }
85965       sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
85966       break;
85967     }
85968 #endif
85969     default: {
85970       sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
85971       break;
85972     }
85973   }
85974   if( zBinOp ){
85975     sqlite3TreeViewLine(pView, "%s", zBinOp);
85976     sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
85977     sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
85978   }else if( zUniOp ){
85979     sqlite3TreeViewLine(pView, "%s", zUniOp);
85980     sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
85981   }
85982   sqlite3TreeViewPop(pView);
85983 }
85984 #endif /* SQLITE_DEBUG */
85985
85986 #ifdef SQLITE_DEBUG
85987 /*
85988 ** Generate a human-readable explanation of an expression list.
85989 */
85990 SQLITE_PRIVATE void sqlite3TreeViewExprList(
85991   TreeView *pView,
85992   const ExprList *pList,
85993   u8 moreToFollow,
85994   const char *zLabel
85995 ){
85996   int i;
85997   pView = sqlite3TreeViewPush(pView, moreToFollow);
85998   if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
85999   if( pList==0 ){
86000     sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
86001   }else{
86002     sqlite3TreeViewLine(pView, "%s", zLabel);
86003     for(i=0; i<pList->nExpr; i++){
86004       sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
86005 #if 0
86006      if( pList->a[i].zName ){
86007         sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
86008       }
86009       if( pList->a[i].bSpanIsTab ){
86010         sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
86011       }
86012 #endif
86013     }
86014   }
86015   sqlite3TreeViewPop(pView);
86016 }
86017 #endif /* SQLITE_DEBUG */
86018
86019 /*
86020 ** Generate code that pushes the value of every element of the given
86021 ** expression list into a sequence of registers beginning at target.
86022 **
86023 ** Return the number of elements evaluated.
86024 **
86025 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
86026 ** filled using OP_SCopy.  OP_Copy must be used instead.
86027 **
86028 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
86029 ** factored out into initialization code.
86030 */
86031 SQLITE_PRIVATE int sqlite3ExprCodeExprList(
86032   Parse *pParse,     /* Parsing context */
86033   ExprList *pList,   /* The expression list to be coded */
86034   int target,        /* Where to write results */
86035   u8 flags           /* SQLITE_ECEL_* flags */
86036 ){
86037   struct ExprList_item *pItem;
86038   int i, n;
86039   u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
86040   assert( pList!=0 );
86041   assert( target>0 );
86042   assert( pParse->pVdbe!=0 );  /* Never gets this far otherwise */
86043   n = pList->nExpr;
86044   if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
86045   for(pItem=pList->a, i=0; i<n; i++, pItem++){
86046     Expr *pExpr = pItem->pExpr;
86047     if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
86048       sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
86049     }else{
86050       int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
86051       if( inReg!=target+i ){
86052         VdbeOp *pOp;
86053         Vdbe *v = pParse->pVdbe;
86054         if( copyOp==OP_Copy
86055          && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
86056          && pOp->p1+pOp->p3+1==inReg
86057          && pOp->p2+pOp->p3+1==target+i
86058         ){
86059           pOp->p3++;
86060         }else{
86061           sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
86062         }
86063       }
86064     }
86065   }
86066   return n;
86067 }
86068
86069 /*
86070 ** Generate code for a BETWEEN operator.
86071 **
86072 **    x BETWEEN y AND z
86073 **
86074 ** The above is equivalent to 
86075 **
86076 **    x>=y AND x<=z
86077 **
86078 ** Code it as such, taking care to do the common subexpression
86079 ** elimination of x.
86080 */
86081 static void exprCodeBetween(
86082   Parse *pParse,    /* Parsing and code generating context */
86083   Expr *pExpr,      /* The BETWEEN expression */
86084   int dest,         /* Jump here if the jump is taken */
86085   int jumpIfTrue,   /* Take the jump if the BETWEEN is true */
86086   int jumpIfNull    /* Take the jump if the BETWEEN is NULL */
86087 ){
86088   Expr exprAnd;     /* The AND operator in  x>=y AND x<=z  */
86089   Expr compLeft;    /* The  x>=y  term */
86090   Expr compRight;   /* The  x<=z  term */
86091   Expr exprX;       /* The  x  subexpression */
86092   int regFree1 = 0; /* Temporary use register */
86093
86094   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
86095   exprX = *pExpr->pLeft;
86096   exprAnd.op = TK_AND;
86097   exprAnd.pLeft = &compLeft;
86098   exprAnd.pRight = &compRight;
86099   compLeft.op = TK_GE;
86100   compLeft.pLeft = &exprX;
86101   compLeft.pRight = pExpr->x.pList->a[0].pExpr;
86102   compRight.op = TK_LE;
86103   compRight.pLeft = &exprX;
86104   compRight.pRight = pExpr->x.pList->a[1].pExpr;
86105   exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
86106   if( jumpIfTrue ){
86107     sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
86108   }else{
86109     sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
86110   }
86111   sqlite3ReleaseTempReg(pParse, regFree1);
86112
86113   /* Ensure adequate test coverage */
86114   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
86115   testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
86116   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
86117   testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
86118   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
86119   testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
86120   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
86121   testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
86122 }
86123
86124 /*
86125 ** Generate code for a boolean expression such that a jump is made
86126 ** to the label "dest" if the expression is true but execution
86127 ** continues straight thru if the expression is false.
86128 **
86129 ** If the expression evaluates to NULL (neither true nor false), then
86130 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
86131 **
86132 ** This code depends on the fact that certain token values (ex: TK_EQ)
86133 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
86134 ** operation.  Special comments in vdbe.c and the mkopcodeh.awk script in
86135 ** the make process cause these values to align.  Assert()s in the code
86136 ** below verify that the numbers are aligned correctly.
86137 */
86138 SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
86139   Vdbe *v = pParse->pVdbe;
86140   int op = 0;
86141   int regFree1 = 0;
86142   int regFree2 = 0;
86143   int r1, r2;
86144
86145   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
86146   if( NEVER(v==0) )     return;  /* Existence of VDBE checked by caller */
86147   if( NEVER(pExpr==0) ) return;  /* No way this can happen */
86148   op = pExpr->op;
86149   switch( op ){
86150     case TK_AND: {
86151       int d2 = sqlite3VdbeMakeLabel(v);
86152       testcase( jumpIfNull==0 );
86153       sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
86154       sqlite3ExprCachePush(pParse);
86155       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
86156       sqlite3VdbeResolveLabel(v, d2);
86157       sqlite3ExprCachePop(pParse);
86158       break;
86159     }
86160     case TK_OR: {
86161       testcase( jumpIfNull==0 );
86162       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
86163       sqlite3ExprCachePush(pParse);
86164       sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
86165       sqlite3ExprCachePop(pParse);
86166       break;
86167     }
86168     case TK_NOT: {
86169       testcase( jumpIfNull==0 );
86170       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
86171       break;
86172     }
86173     case TK_LT:
86174     case TK_LE:
86175     case TK_GT:
86176     case TK_GE:
86177     case TK_NE:
86178     case TK_EQ: {
86179       testcase( jumpIfNull==0 );
86180       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
86181       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
86182       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
86183                   r1, r2, dest, jumpIfNull);
86184       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
86185       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
86186       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
86187       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
86188       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
86189       assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
86190       testcase( regFree1==0 );
86191       testcase( regFree2==0 );
86192       break;
86193     }
86194     case TK_IS:
86195     case TK_ISNOT: {
86196       testcase( op==TK_IS );
86197       testcase( op==TK_ISNOT );
86198       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
86199       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
86200       op = (op==TK_IS) ? TK_EQ : TK_NE;
86201       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
86202                   r1, r2, dest, SQLITE_NULLEQ);
86203       VdbeCoverageIf(v, op==TK_EQ);
86204       VdbeCoverageIf(v, op==TK_NE);
86205       testcase( regFree1==0 );
86206       testcase( regFree2==0 );
86207       break;
86208     }
86209     case TK_ISNULL:
86210     case TK_NOTNULL: {
86211       assert( TK_ISNULL==OP_IsNull );   testcase( op==TK_ISNULL );
86212       assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
86213       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
86214       sqlite3VdbeAddOp2(v, op, r1, dest);
86215       VdbeCoverageIf(v, op==TK_ISNULL);
86216       VdbeCoverageIf(v, op==TK_NOTNULL);
86217       testcase( regFree1==0 );
86218       break;
86219     }
86220     case TK_BETWEEN: {
86221       testcase( jumpIfNull==0 );
86222       exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
86223       break;
86224     }
86225 #ifndef SQLITE_OMIT_SUBQUERY
86226     case TK_IN: {
86227       int destIfFalse = sqlite3VdbeMakeLabel(v);
86228       int destIfNull = jumpIfNull ? dest : destIfFalse;
86229       sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
86230       sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
86231       sqlite3VdbeResolveLabel(v, destIfFalse);
86232       break;
86233     }
86234 #endif
86235     default: {
86236       if( exprAlwaysTrue(pExpr) ){
86237         sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
86238       }else if( exprAlwaysFalse(pExpr) ){
86239         /* No-op */
86240       }else{
86241         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
86242         sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
86243         VdbeCoverage(v);
86244         testcase( regFree1==0 );
86245         testcase( jumpIfNull==0 );
86246       }
86247       break;
86248     }
86249   }
86250   sqlite3ReleaseTempReg(pParse, regFree1);
86251   sqlite3ReleaseTempReg(pParse, regFree2);  
86252 }
86253
86254 /*
86255 ** Generate code for a boolean expression such that a jump is made
86256 ** to the label "dest" if the expression is false but execution
86257 ** continues straight thru if the expression is true.
86258 **
86259 ** If the expression evaluates to NULL (neither true nor false) then
86260 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
86261 ** is 0.
86262 */
86263 SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
86264   Vdbe *v = pParse->pVdbe;
86265   int op = 0;
86266   int regFree1 = 0;
86267   int regFree2 = 0;
86268   int r1, r2;
86269
86270   assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
86271   if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
86272   if( pExpr==0 )    return;
86273
86274   /* The value of pExpr->op and op are related as follows:
86275   **
86276   **       pExpr->op            op
86277   **       ---------          ----------
86278   **       TK_ISNULL          OP_NotNull
86279   **       TK_NOTNULL         OP_IsNull
86280   **       TK_NE              OP_Eq
86281   **       TK_EQ              OP_Ne
86282   **       TK_GT              OP_Le
86283   **       TK_LE              OP_Gt
86284   **       TK_GE              OP_Lt
86285   **       TK_LT              OP_Ge
86286   **
86287   ** For other values of pExpr->op, op is undefined and unused.
86288   ** The value of TK_ and OP_ constants are arranged such that we
86289   ** can compute the mapping above using the following expression.
86290   ** Assert()s verify that the computation is correct.
86291   */
86292   op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
86293
86294   /* Verify correct alignment of TK_ and OP_ constants
86295   */
86296   assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
86297   assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
86298   assert( pExpr->op!=TK_NE || op==OP_Eq );
86299   assert( pExpr->op!=TK_EQ || op==OP_Ne );
86300   assert( pExpr->op!=TK_LT || op==OP_Ge );
86301   assert( pExpr->op!=TK_LE || op==OP_Gt );
86302   assert( pExpr->op!=TK_GT || op==OP_Le );
86303   assert( pExpr->op!=TK_GE || op==OP_Lt );
86304
86305   switch( pExpr->op ){
86306     case TK_AND: {
86307       testcase( jumpIfNull==0 );
86308       sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
86309       sqlite3ExprCachePush(pParse);
86310       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
86311       sqlite3ExprCachePop(pParse);
86312       break;
86313     }
86314     case TK_OR: {
86315       int d2 = sqlite3VdbeMakeLabel(v);
86316       testcase( jumpIfNull==0 );
86317       sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
86318       sqlite3ExprCachePush(pParse);
86319       sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
86320       sqlite3VdbeResolveLabel(v, d2);
86321       sqlite3ExprCachePop(pParse);
86322       break;
86323     }
86324     case TK_NOT: {
86325       testcase( jumpIfNull==0 );
86326       sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
86327       break;
86328     }
86329     case TK_LT:
86330     case TK_LE:
86331     case TK_GT:
86332     case TK_GE:
86333     case TK_NE:
86334     case TK_EQ: {
86335       testcase( jumpIfNull==0 );
86336       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
86337       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
86338       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
86339                   r1, r2, dest, jumpIfNull);
86340       assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
86341       assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
86342       assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
86343       assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
86344       assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
86345       assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
86346       testcase( regFree1==0 );
86347       testcase( regFree2==0 );
86348       break;
86349     }
86350     case TK_IS:
86351     case TK_ISNOT: {
86352       testcase( pExpr->op==TK_IS );
86353       testcase( pExpr->op==TK_ISNOT );
86354       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
86355       r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
86356       op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
86357       codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
86358                   r1, r2, dest, SQLITE_NULLEQ);
86359       VdbeCoverageIf(v, op==TK_EQ);
86360       VdbeCoverageIf(v, op==TK_NE);
86361       testcase( regFree1==0 );
86362       testcase( regFree2==0 );
86363       break;
86364     }
86365     case TK_ISNULL:
86366     case TK_NOTNULL: {
86367       r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
86368       sqlite3VdbeAddOp2(v, op, r1, dest);
86369       testcase( op==TK_ISNULL );   VdbeCoverageIf(v, op==TK_ISNULL);
86370       testcase( op==TK_NOTNULL );  VdbeCoverageIf(v, op==TK_NOTNULL);
86371       testcase( regFree1==0 );
86372       break;
86373     }
86374     case TK_BETWEEN: {
86375       testcase( jumpIfNull==0 );
86376       exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
86377       break;
86378     }
86379 #ifndef SQLITE_OMIT_SUBQUERY
86380     case TK_IN: {
86381       if( jumpIfNull ){
86382         sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
86383       }else{
86384         int destIfNull = sqlite3VdbeMakeLabel(v);
86385         sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
86386         sqlite3VdbeResolveLabel(v, destIfNull);
86387       }
86388       break;
86389     }
86390 #endif
86391     default: {
86392       if( exprAlwaysFalse(pExpr) ){
86393         sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
86394       }else if( exprAlwaysTrue(pExpr) ){
86395         /* no-op */
86396       }else{
86397         r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
86398         sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
86399         VdbeCoverage(v);
86400         testcase( regFree1==0 );
86401         testcase( jumpIfNull==0 );
86402       }
86403       break;
86404     }
86405   }
86406   sqlite3ReleaseTempReg(pParse, regFree1);
86407   sqlite3ReleaseTempReg(pParse, regFree2);
86408 }
86409
86410 /*
86411 ** Do a deep comparison of two expression trees.  Return 0 if the two
86412 ** expressions are completely identical.  Return 1 if they differ only
86413 ** by a COLLATE operator at the top level.  Return 2 if there are differences
86414 ** other than the top-level COLLATE operator.
86415 **
86416 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
86417 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
86418 **
86419 ** The pA side might be using TK_REGISTER.  If that is the case and pB is
86420 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
86421 **
86422 ** Sometimes this routine will return 2 even if the two expressions
86423 ** really are equivalent.  If we cannot prove that the expressions are
86424 ** identical, we return 2 just to be safe.  So if this routine
86425 ** returns 2, then you do not really know for certain if the two
86426 ** expressions are the same.  But if you get a 0 or 1 return, then you
86427 ** can be sure the expressions are the same.  In the places where
86428 ** this routine is used, it does not hurt to get an extra 2 - that
86429 ** just might result in some slightly slower code.  But returning
86430 ** an incorrect 0 or 1 could lead to a malfunction.
86431 */
86432 SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
86433   u32 combinedFlags;
86434   if( pA==0 || pB==0 ){
86435     return pB==pA ? 0 : 2;
86436   }
86437   combinedFlags = pA->flags | pB->flags;
86438   if( combinedFlags & EP_IntValue ){
86439     if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
86440       return 0;
86441     }
86442     return 2;
86443   }
86444   if( pA->op!=pB->op ){
86445     if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
86446       return 1;
86447     }
86448     if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
86449       return 1;
86450     }
86451     return 2;
86452   }
86453   if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken ){
86454     if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
86455       return pA->op==TK_COLLATE ? 1 : 2;
86456     }
86457   }
86458   if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
86459   if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
86460     if( combinedFlags & EP_xIsSelect ) return 2;
86461     if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
86462     if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
86463     if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
86464     if( ALWAYS((combinedFlags & EP_Reduced)==0) ){
86465       if( pA->iColumn!=pB->iColumn ) return 2;
86466       if( pA->iTable!=pB->iTable 
86467        && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
86468     }
86469   }
86470   return 0;
86471 }
86472
86473 /*
86474 ** Compare two ExprList objects.  Return 0 if they are identical and 
86475 ** non-zero if they differ in any way.
86476 **
86477 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
86478 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
86479 **
86480 ** This routine might return non-zero for equivalent ExprLists.  The
86481 ** only consequence will be disabled optimizations.  But this routine
86482 ** must never return 0 if the two ExprList objects are different, or
86483 ** a malfunction will result.
86484 **
86485 ** Two NULL pointers are considered to be the same.  But a NULL pointer
86486 ** always differs from a non-NULL pointer.
86487 */
86488 SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
86489   int i;
86490   if( pA==0 && pB==0 ) return 0;
86491   if( pA==0 || pB==0 ) return 1;
86492   if( pA->nExpr!=pB->nExpr ) return 1;
86493   for(i=0; i<pA->nExpr; i++){
86494     Expr *pExprA = pA->a[i].pExpr;
86495     Expr *pExprB = pB->a[i].pExpr;
86496     if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
86497     if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
86498   }
86499   return 0;
86500 }
86501
86502 /*
86503 ** Return true if we can prove the pE2 will always be true if pE1 is
86504 ** true.  Return false if we cannot complete the proof or if pE2 might
86505 ** be false.  Examples:
86506 **
86507 **     pE1: x==5       pE2: x==5             Result: true
86508 **     pE1: x>0        pE2: x==5             Result: false
86509 **     pE1: x=21       pE2: x=21 OR y=43     Result: true
86510 **     pE1: x!=123     pE2: x IS NOT NULL    Result: true
86511 **     pE1: x!=?1      pE2: x IS NOT NULL    Result: true
86512 **     pE1: x IS NULL  pE2: x IS NOT NULL    Result: false
86513 **     pE1: x IS ?2    pE2: x IS NOT NULL    Reuslt: false
86514 **
86515 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
86516 ** Expr.iTable<0 then assume a table number given by iTab.
86517 **
86518 ** When in doubt, return false.  Returning true might give a performance
86519 ** improvement.  Returning false might cause a performance reduction, but
86520 ** it will always give the correct answer and is hence always safe.
86521 */
86522 SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
86523   if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
86524     return 1;
86525   }
86526   if( pE2->op==TK_OR
86527    && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
86528              || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
86529   ){
86530     return 1;
86531   }
86532   if( pE2->op==TK_NOTNULL
86533    && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
86534    && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
86535   ){
86536     return 1;
86537   }
86538   return 0;
86539 }
86540
86541 /*
86542 ** An instance of the following structure is used by the tree walker
86543 ** to count references to table columns in the arguments of an 
86544 ** aggregate function, in order to implement the
86545 ** sqlite3FunctionThisSrc() routine.
86546 */
86547 struct SrcCount {
86548   SrcList *pSrc;   /* One particular FROM clause in a nested query */
86549   int nThis;       /* Number of references to columns in pSrcList */
86550   int nOther;      /* Number of references to columns in other FROM clauses */
86551 };
86552
86553 /*
86554 ** Count the number of references to columns.
86555 */
86556 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
86557   /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
86558   ** is always called before sqlite3ExprAnalyzeAggregates() and so the
86559   ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN.  If
86560   ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
86561   ** NEVER() will need to be removed. */
86562   if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
86563     int i;
86564     struct SrcCount *p = pWalker->u.pSrcCount;
86565     SrcList *pSrc = p->pSrc;
86566     int nSrc = pSrc ? pSrc->nSrc : 0;
86567     for(i=0; i<nSrc; i++){
86568       if( pExpr->iTable==pSrc->a[i].iCursor ) break;
86569     }
86570     if( i<nSrc ){
86571       p->nThis++;
86572     }else{
86573       p->nOther++;
86574     }
86575   }
86576   return WRC_Continue;
86577 }
86578
86579 /*
86580 ** Determine if any of the arguments to the pExpr Function reference
86581 ** pSrcList.  Return true if they do.  Also return true if the function
86582 ** has no arguments or has only constant arguments.  Return false if pExpr
86583 ** references columns but not columns of tables found in pSrcList.
86584 */
86585 SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
86586   Walker w;
86587   struct SrcCount cnt;
86588   assert( pExpr->op==TK_AGG_FUNCTION );
86589   memset(&w, 0, sizeof(w));
86590   w.xExprCallback = exprSrcCount;
86591   w.u.pSrcCount = &cnt;
86592   cnt.pSrc = pSrcList;
86593   cnt.nThis = 0;
86594   cnt.nOther = 0;
86595   sqlite3WalkExprList(&w, pExpr->x.pList);
86596   return cnt.nThis>0 || cnt.nOther==0;
86597 }
86598
86599 /*
86600 ** Add a new element to the pAggInfo->aCol[] array.  Return the index of
86601 ** the new element.  Return a negative number if malloc fails.
86602 */
86603 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
86604   int i;
86605   pInfo->aCol = sqlite3ArrayAllocate(
86606        db,
86607        pInfo->aCol,
86608        sizeof(pInfo->aCol[0]),
86609        &pInfo->nColumn,
86610        &i
86611   );
86612   return i;
86613 }    
86614
86615 /*
86616 ** Add a new element to the pAggInfo->aFunc[] array.  Return the index of
86617 ** the new element.  Return a negative number if malloc fails.
86618 */
86619 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
86620   int i;
86621   pInfo->aFunc = sqlite3ArrayAllocate(
86622        db, 
86623        pInfo->aFunc,
86624        sizeof(pInfo->aFunc[0]),
86625        &pInfo->nFunc,
86626        &i
86627   );
86628   return i;
86629 }    
86630
86631 /*
86632 ** This is the xExprCallback for a tree walker.  It is used to
86633 ** implement sqlite3ExprAnalyzeAggregates().  See sqlite3ExprAnalyzeAggregates
86634 ** for additional information.
86635 */
86636 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
86637   int i;
86638   NameContext *pNC = pWalker->u.pNC;
86639   Parse *pParse = pNC->pParse;
86640   SrcList *pSrcList = pNC->pSrcList;
86641   AggInfo *pAggInfo = pNC->pAggInfo;
86642
86643   switch( pExpr->op ){
86644     case TK_AGG_COLUMN:
86645     case TK_COLUMN: {
86646       testcase( pExpr->op==TK_AGG_COLUMN );
86647       testcase( pExpr->op==TK_COLUMN );
86648       /* Check to see if the column is in one of the tables in the FROM
86649       ** clause of the aggregate query */
86650       if( ALWAYS(pSrcList!=0) ){
86651         struct SrcList_item *pItem = pSrcList->a;
86652         for(i=0; i<pSrcList->nSrc; i++, pItem++){
86653           struct AggInfo_col *pCol;
86654           assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
86655           if( pExpr->iTable==pItem->iCursor ){
86656             /* If we reach this point, it means that pExpr refers to a table
86657             ** that is in the FROM clause of the aggregate query.  
86658             **
86659             ** Make an entry for the column in pAggInfo->aCol[] if there
86660             ** is not an entry there already.
86661             */
86662             int k;
86663             pCol = pAggInfo->aCol;
86664             for(k=0; k<pAggInfo->nColumn; k++, pCol++){
86665               if( pCol->iTable==pExpr->iTable &&
86666                   pCol->iColumn==pExpr->iColumn ){
86667                 break;
86668               }
86669             }
86670             if( (k>=pAggInfo->nColumn)
86671              && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0 
86672             ){
86673               pCol = &pAggInfo->aCol[k];
86674               pCol->pTab = pExpr->pTab;
86675               pCol->iTable = pExpr->iTable;
86676               pCol->iColumn = pExpr->iColumn;
86677               pCol->iMem = ++pParse->nMem;
86678               pCol->iSorterColumn = -1;
86679               pCol->pExpr = pExpr;
86680               if( pAggInfo->pGroupBy ){
86681                 int j, n;
86682                 ExprList *pGB = pAggInfo->pGroupBy;
86683                 struct ExprList_item *pTerm = pGB->a;
86684                 n = pGB->nExpr;
86685                 for(j=0; j<n; j++, pTerm++){
86686                   Expr *pE = pTerm->pExpr;
86687                   if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
86688                       pE->iColumn==pExpr->iColumn ){
86689                     pCol->iSorterColumn = j;
86690                     break;
86691                   }
86692                 }
86693               }
86694               if( pCol->iSorterColumn<0 ){
86695                 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
86696               }
86697             }
86698             /* There is now an entry for pExpr in pAggInfo->aCol[] (either
86699             ** because it was there before or because we just created it).
86700             ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
86701             ** pAggInfo->aCol[] entry.
86702             */
86703             ExprSetVVAProperty(pExpr, EP_NoReduce);
86704             pExpr->pAggInfo = pAggInfo;
86705             pExpr->op = TK_AGG_COLUMN;
86706             pExpr->iAgg = (i16)k;
86707             break;
86708           } /* endif pExpr->iTable==pItem->iCursor */
86709         } /* end loop over pSrcList */
86710       }
86711       return WRC_Prune;
86712     }
86713     case TK_AGG_FUNCTION: {
86714       if( (pNC->ncFlags & NC_InAggFunc)==0
86715        && pWalker->walkerDepth==pExpr->op2
86716       ){
86717         /* Check to see if pExpr is a duplicate of another aggregate 
86718         ** function that is already in the pAggInfo structure
86719         */
86720         struct AggInfo_func *pItem = pAggInfo->aFunc;
86721         for(i=0; i<pAggInfo->nFunc; i++, pItem++){
86722           if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
86723             break;
86724           }
86725         }
86726         if( i>=pAggInfo->nFunc ){
86727           /* pExpr is original.  Make a new entry in pAggInfo->aFunc[]
86728           */
86729           u8 enc = ENC(pParse->db);
86730           i = addAggInfoFunc(pParse->db, pAggInfo);
86731           if( i>=0 ){
86732             assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
86733             pItem = &pAggInfo->aFunc[i];
86734             pItem->pExpr = pExpr;
86735             pItem->iMem = ++pParse->nMem;
86736             assert( !ExprHasProperty(pExpr, EP_IntValue) );
86737             pItem->pFunc = sqlite3FindFunction(pParse->db,
86738                    pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
86739                    pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
86740             if( pExpr->flags & EP_Distinct ){
86741               pItem->iDistinct = pParse->nTab++;
86742             }else{
86743               pItem->iDistinct = -1;
86744             }
86745           }
86746         }
86747         /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
86748         */
86749         assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
86750         ExprSetVVAProperty(pExpr, EP_NoReduce);
86751         pExpr->iAgg = (i16)i;
86752         pExpr->pAggInfo = pAggInfo;
86753         return WRC_Prune;
86754       }else{
86755         return WRC_Continue;
86756       }
86757     }
86758   }
86759   return WRC_Continue;
86760 }
86761 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
86762   UNUSED_PARAMETER(pWalker);
86763   UNUSED_PARAMETER(pSelect);
86764   return WRC_Continue;
86765 }
86766
86767 /*
86768 ** Analyze the pExpr expression looking for aggregate functions and
86769 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
86770 ** points to.  Additional entries are made on the AggInfo object as
86771 ** necessary.
86772 **
86773 ** This routine should only be called after the expression has been
86774 ** analyzed by sqlite3ResolveExprNames().
86775 */
86776 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
86777   Walker w;
86778   memset(&w, 0, sizeof(w));
86779   w.xExprCallback = analyzeAggregate;
86780   w.xSelectCallback = analyzeAggregatesInSelect;
86781   w.u.pNC = pNC;
86782   assert( pNC->pSrcList!=0 );
86783   sqlite3WalkExpr(&w, pExpr);
86784 }
86785
86786 /*
86787 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
86788 ** expression list.  Return the number of errors.
86789 **
86790 ** If an error is found, the analysis is cut short.
86791 */
86792 SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
86793   struct ExprList_item *pItem;
86794   int i;
86795   if( pList ){
86796     for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
86797       sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
86798     }
86799   }
86800 }
86801
86802 /*
86803 ** Allocate a single new register for use to hold some intermediate result.
86804 */
86805 SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
86806   if( pParse->nTempReg==0 ){
86807     return ++pParse->nMem;
86808   }
86809   return pParse->aTempReg[--pParse->nTempReg];
86810 }
86811
86812 /*
86813 ** Deallocate a register, making available for reuse for some other
86814 ** purpose.
86815 **
86816 ** If a register is currently being used by the column cache, then
86817 ** the deallocation is deferred until the column cache line that uses
86818 ** the register becomes stale.
86819 */
86820 SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
86821   if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
86822     int i;
86823     struct yColCache *p;
86824     for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
86825       if( p->iReg==iReg ){
86826         p->tempReg = 1;
86827         return;
86828       }
86829     }
86830     pParse->aTempReg[pParse->nTempReg++] = iReg;
86831   }
86832 }
86833
86834 /*
86835 ** Allocate or deallocate a block of nReg consecutive registers
86836 */
86837 SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
86838   int i, n;
86839   i = pParse->iRangeReg;
86840   n = pParse->nRangeReg;
86841   if( nReg<=n ){
86842     assert( !usedAsColumnCache(pParse, i, i+n-1) );
86843     pParse->iRangeReg += nReg;
86844     pParse->nRangeReg -= nReg;
86845   }else{
86846     i = pParse->nMem+1;
86847     pParse->nMem += nReg;
86848   }
86849   return i;
86850 }
86851 SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
86852   sqlite3ExprCacheRemove(pParse, iReg, nReg);
86853   if( nReg>pParse->nRangeReg ){
86854     pParse->nRangeReg = nReg;
86855     pParse->iRangeReg = iReg;
86856   }
86857 }
86858
86859 /*
86860 ** Mark all temporary registers as being unavailable for reuse.
86861 */
86862 SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
86863   pParse->nTempReg = 0;
86864   pParse->nRangeReg = 0;
86865 }
86866
86867 /************** End of expr.c ************************************************/
86868 /************** Begin file alter.c *******************************************/
86869 /*
86870 ** 2005 February 15
86871 **
86872 ** The author disclaims copyright to this source code.  In place of
86873 ** a legal notice, here is a blessing:
86874 **
86875 **    May you do good and not evil.
86876 **    May you find forgiveness for yourself and forgive others.
86877 **    May you share freely, never taking more than you give.
86878 **
86879 *************************************************************************
86880 ** This file contains C code routines that used to generate VDBE code
86881 ** that implements the ALTER TABLE command.
86882 */
86883
86884 /*
86885 ** The code in this file only exists if we are not omitting the
86886 ** ALTER TABLE logic from the build.
86887 */
86888 #ifndef SQLITE_OMIT_ALTERTABLE
86889
86890
86891 /*
86892 ** This function is used by SQL generated to implement the 
86893 ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
86894 ** CREATE INDEX command. The second is a table name. The table name in 
86895 ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
86896 ** argument and the result returned. Examples:
86897 **
86898 ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
86899 **     -> 'CREATE TABLE def(a, b, c)'
86900 **
86901 ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
86902 **     -> 'CREATE INDEX i ON def(a, b, c)'
86903 */
86904 static void renameTableFunc(
86905   sqlite3_context *context,
86906   int NotUsed,
86907   sqlite3_value **argv
86908 ){
86909   unsigned char const *zSql = sqlite3_value_text(argv[0]);
86910   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
86911
86912   int token;
86913   Token tname;
86914   unsigned char const *zCsr = zSql;
86915   int len = 0;
86916   char *zRet;
86917
86918   sqlite3 *db = sqlite3_context_db_handle(context);
86919
86920   UNUSED_PARAMETER(NotUsed);
86921
86922   /* The principle used to locate the table name in the CREATE TABLE 
86923   ** statement is that the table name is the first non-space token that
86924   ** is immediately followed by a TK_LP or TK_USING token.
86925   */
86926   if( zSql ){
86927     do {
86928       if( !*zCsr ){
86929         /* Ran out of input before finding an opening bracket. Return NULL. */
86930         return;
86931       }
86932
86933       /* Store the token that zCsr points to in tname. */
86934       tname.z = (char*)zCsr;
86935       tname.n = len;
86936
86937       /* Advance zCsr to the next token. Store that token type in 'token',
86938       ** and its length in 'len' (to be used next iteration of this loop).
86939       */
86940       do {
86941         zCsr += len;
86942         len = sqlite3GetToken(zCsr, &token);
86943       } while( token==TK_SPACE );
86944       assert( len>0 );
86945     } while( token!=TK_LP && token!=TK_USING );
86946
86947     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
86948        zSql, zTableName, tname.z+tname.n);
86949     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
86950   }
86951 }
86952
86953 /*
86954 ** This C function implements an SQL user function that is used by SQL code
86955 ** generated by the ALTER TABLE ... RENAME command to modify the definition
86956 ** of any foreign key constraints that use the table being renamed as the 
86957 ** parent table. It is passed three arguments:
86958 **
86959 **   1) The complete text of the CREATE TABLE statement being modified,
86960 **   2) The old name of the table being renamed, and
86961 **   3) The new name of the table being renamed.
86962 **
86963 ** It returns the new CREATE TABLE statement. For example:
86964 **
86965 **   sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
86966 **       -> 'CREATE TABLE t1(a REFERENCES t3)'
86967 */
86968 #ifndef SQLITE_OMIT_FOREIGN_KEY
86969 static void renameParentFunc(
86970   sqlite3_context *context,
86971   int NotUsed,
86972   sqlite3_value **argv
86973 ){
86974   sqlite3 *db = sqlite3_context_db_handle(context);
86975   char *zOutput = 0;
86976   char *zResult;
86977   unsigned char const *zInput = sqlite3_value_text(argv[0]);
86978   unsigned char const *zOld = sqlite3_value_text(argv[1]);
86979   unsigned char const *zNew = sqlite3_value_text(argv[2]);
86980
86981   unsigned const char *z;         /* Pointer to token */
86982   int n;                          /* Length of token z */
86983   int token;                      /* Type of token */
86984
86985   UNUSED_PARAMETER(NotUsed);
86986   if( zInput==0 || zOld==0 ) return;
86987   for(z=zInput; *z; z=z+n){
86988     n = sqlite3GetToken(z, &token);
86989     if( token==TK_REFERENCES ){
86990       char *zParent;
86991       do {
86992         z += n;
86993         n = sqlite3GetToken(z, &token);
86994       }while( token==TK_SPACE );
86995
86996       zParent = sqlite3DbStrNDup(db, (const char *)z, n);
86997       if( zParent==0 ) break;
86998       sqlite3Dequote(zParent);
86999       if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
87000         char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"", 
87001             (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
87002         );
87003         sqlite3DbFree(db, zOutput);
87004         zOutput = zOut;
87005         zInput = &z[n];
87006       }
87007       sqlite3DbFree(db, zParent);
87008     }
87009   }
87010
87011   zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput), 
87012   sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
87013   sqlite3DbFree(db, zOutput);
87014 }
87015 #endif
87016
87017 #ifndef SQLITE_OMIT_TRIGGER
87018 /* This function is used by SQL generated to implement the
87019 ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER 
87020 ** statement. The second is a table name. The table name in the CREATE 
87021 ** TRIGGER statement is replaced with the third argument and the result 
87022 ** returned. This is analagous to renameTableFunc() above, except for CREATE
87023 ** TRIGGER, not CREATE INDEX and CREATE TABLE.
87024 */
87025 static void renameTriggerFunc(
87026   sqlite3_context *context,
87027   int NotUsed,
87028   sqlite3_value **argv
87029 ){
87030   unsigned char const *zSql = sqlite3_value_text(argv[0]);
87031   unsigned char const *zTableName = sqlite3_value_text(argv[1]);
87032
87033   int token;
87034   Token tname;
87035   int dist = 3;
87036   unsigned char const *zCsr = zSql;
87037   int len = 0;
87038   char *zRet;
87039   sqlite3 *db = sqlite3_context_db_handle(context);
87040
87041   UNUSED_PARAMETER(NotUsed);
87042
87043   /* The principle used to locate the table name in the CREATE TRIGGER 
87044   ** statement is that the table name is the first token that is immediately
87045   ** preceded by either TK_ON or TK_DOT and immediately followed by one
87046   ** of TK_WHEN, TK_BEGIN or TK_FOR.
87047   */
87048   if( zSql ){
87049     do {
87050
87051       if( !*zCsr ){
87052         /* Ran out of input before finding the table name. Return NULL. */
87053         return;
87054       }
87055
87056       /* Store the token that zCsr points to in tname. */
87057       tname.z = (char*)zCsr;
87058       tname.n = len;
87059
87060       /* Advance zCsr to the next token. Store that token type in 'token',
87061       ** and its length in 'len' (to be used next iteration of this loop).
87062       */
87063       do {
87064         zCsr += len;
87065         len = sqlite3GetToken(zCsr, &token);
87066       }while( token==TK_SPACE );
87067       assert( len>0 );
87068
87069       /* Variable 'dist' stores the number of tokens read since the most
87070       ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN 
87071       ** token is read and 'dist' equals 2, the condition stated above
87072       ** to be met.
87073       **
87074       ** Note that ON cannot be a database, table or column name, so
87075       ** there is no need to worry about syntax like 
87076       ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
87077       */
87078       dist++;
87079       if( token==TK_DOT || token==TK_ON ){
87080         dist = 0;
87081       }
87082     } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
87083
87084     /* Variable tname now contains the token that is the old table-name
87085     ** in the CREATE TRIGGER statement.
87086     */
87087     zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
87088        zSql, zTableName, tname.z+tname.n);
87089     sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
87090   }
87091 }
87092 #endif   /* !SQLITE_OMIT_TRIGGER */
87093
87094 /*
87095 ** Register built-in functions used to help implement ALTER TABLE
87096 */
87097 SQLITE_PRIVATE void sqlite3AlterFunctions(void){
87098   static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
87099     FUNCTION(sqlite_rename_table,   2, 0, 0, renameTableFunc),
87100 #ifndef SQLITE_OMIT_TRIGGER
87101     FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
87102 #endif
87103 #ifndef SQLITE_OMIT_FOREIGN_KEY
87104     FUNCTION(sqlite_rename_parent,  3, 0, 0, renameParentFunc),
87105 #endif
87106   };
87107   int i;
87108   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
87109   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
87110
87111   for(i=0; i<ArraySize(aAlterTableFuncs); i++){
87112     sqlite3FuncDefInsert(pHash, &aFunc[i]);
87113   }
87114 }
87115
87116 /*
87117 ** This function is used to create the text of expressions of the form:
87118 **
87119 **   name=<constant1> OR name=<constant2> OR ...
87120 **
87121 ** If argument zWhere is NULL, then a pointer string containing the text 
87122 ** "name=<constant>" is returned, where <constant> is the quoted version
87123 ** of the string passed as argument zConstant. The returned buffer is
87124 ** allocated using sqlite3DbMalloc(). It is the responsibility of the
87125 ** caller to ensure that it is eventually freed.
87126 **
87127 ** If argument zWhere is not NULL, then the string returned is 
87128 ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
87129 ** In this case zWhere is passed to sqlite3DbFree() before returning.
87130 ** 
87131 */
87132 static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
87133   char *zNew;
87134   if( !zWhere ){
87135     zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
87136   }else{
87137     zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
87138     sqlite3DbFree(db, zWhere);
87139   }
87140   return zNew;
87141 }
87142
87143 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
87144 /*
87145 ** Generate the text of a WHERE expression which can be used to select all
87146 ** tables that have foreign key constraints that refer to table pTab (i.e.
87147 ** constraints for which pTab is the parent table) from the sqlite_master
87148 ** table.
87149 */
87150 static char *whereForeignKeys(Parse *pParse, Table *pTab){
87151   FKey *p;
87152   char *zWhere = 0;
87153   for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
87154     zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
87155   }
87156   return zWhere;
87157 }
87158 #endif
87159
87160 /*
87161 ** Generate the text of a WHERE expression which can be used to select all
87162 ** temporary triggers on table pTab from the sqlite_temp_master table. If
87163 ** table pTab has no temporary triggers, or is itself stored in the 
87164 ** temporary database, NULL is returned.
87165 */
87166 static char *whereTempTriggers(Parse *pParse, Table *pTab){
87167   Trigger *pTrig;
87168   char *zWhere = 0;
87169   const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
87170
87171   /* If the table is not located in the temp-db (in which case NULL is 
87172   ** returned, loop through the tables list of triggers. For each trigger
87173   ** that is not part of the temp-db schema, add a clause to the WHERE 
87174   ** expression being built up in zWhere.
87175   */
87176   if( pTab->pSchema!=pTempSchema ){
87177     sqlite3 *db = pParse->db;
87178     for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
87179       if( pTrig->pSchema==pTempSchema ){
87180         zWhere = whereOrName(db, zWhere, pTrig->zName);
87181       }
87182     }
87183   }
87184   if( zWhere ){
87185     char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
87186     sqlite3DbFree(pParse->db, zWhere);
87187     zWhere = zNew;
87188   }
87189   return zWhere;
87190 }
87191
87192 /*
87193 ** Generate code to drop and reload the internal representation of table
87194 ** pTab from the database, including triggers and temporary triggers.
87195 ** Argument zName is the name of the table in the database schema at
87196 ** the time the generated code is executed. This can be different from
87197 ** pTab->zName if this function is being called to code part of an 
87198 ** "ALTER TABLE RENAME TO" statement.
87199 */
87200 static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
87201   Vdbe *v;
87202   char *zWhere;
87203   int iDb;                   /* Index of database containing pTab */
87204 #ifndef SQLITE_OMIT_TRIGGER
87205   Trigger *pTrig;
87206 #endif
87207
87208   v = sqlite3GetVdbe(pParse);
87209   if( NEVER(v==0) ) return;
87210   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
87211   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
87212   assert( iDb>=0 );
87213
87214 #ifndef SQLITE_OMIT_TRIGGER
87215   /* Drop any table triggers from the internal schema. */
87216   for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
87217     int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
87218     assert( iTrigDb==iDb || iTrigDb==1 );
87219     sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
87220   }
87221 #endif
87222
87223   /* Drop the table and index from the internal schema.  */
87224   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
87225
87226   /* Reload the table, index and permanent trigger schemas. */
87227   zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
87228   if( !zWhere ) return;
87229   sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
87230
87231 #ifndef SQLITE_OMIT_TRIGGER
87232   /* Now, if the table is not stored in the temp database, reload any temp 
87233   ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined. 
87234   */
87235   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
87236     sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
87237   }
87238 #endif
87239 }
87240
87241 /*
87242 ** Parameter zName is the name of a table that is about to be altered
87243 ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
87244 ** If the table is a system table, this function leaves an error message
87245 ** in pParse->zErr (system tables may not be altered) and returns non-zero.
87246 **
87247 ** Or, if zName is not a system table, zero is returned.
87248 */
87249 static int isSystemTable(Parse *pParse, const char *zName){
87250   if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
87251     sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
87252     return 1;
87253   }
87254   return 0;
87255 }
87256
87257 /*
87258 ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy" 
87259 ** command. 
87260 */
87261 SQLITE_PRIVATE void sqlite3AlterRenameTable(
87262   Parse *pParse,            /* Parser context. */
87263   SrcList *pSrc,            /* The table to rename. */
87264   Token *pName              /* The new table name. */
87265 ){
87266   int iDb;                  /* Database that contains the table */
87267   char *zDb;                /* Name of database iDb */
87268   Table *pTab;              /* Table being renamed */
87269   char *zName = 0;          /* NULL-terminated version of pName */ 
87270   sqlite3 *db = pParse->db; /* Database connection */
87271   int nTabName;             /* Number of UTF-8 characters in zTabName */
87272   const char *zTabName;     /* Original name of the table */
87273   Vdbe *v;
87274 #ifndef SQLITE_OMIT_TRIGGER
87275   char *zWhere = 0;         /* Where clause to locate temp triggers */
87276 #endif
87277   VTable *pVTab = 0;        /* Non-zero if this is a v-tab with an xRename() */
87278   int savedDbFlags;         /* Saved value of db->flags */
87279
87280   savedDbFlags = db->flags;  
87281   if( NEVER(db->mallocFailed) ) goto exit_rename_table;
87282   assert( pSrc->nSrc==1 );
87283   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
87284
87285   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
87286   if( !pTab ) goto exit_rename_table;
87287   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
87288   zDb = db->aDb[iDb].zName;
87289   db->flags |= SQLITE_PreferBuiltin;
87290
87291   /* Get a NULL terminated version of the new table name. */
87292   zName = sqlite3NameFromToken(db, pName);
87293   if( !zName ) goto exit_rename_table;
87294
87295   /* Check that a table or index named 'zName' does not already exist
87296   ** in database iDb. If so, this is an error.
87297   */
87298   if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
87299     sqlite3ErrorMsg(pParse, 
87300         "there is already another table or index with this name: %s", zName);
87301     goto exit_rename_table;
87302   }
87303
87304   /* Make sure it is not a system table being altered, or a reserved name
87305   ** that the table is being renamed to.
87306   */
87307   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
87308     goto exit_rename_table;
87309   }
87310   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
87311     exit_rename_table;
87312   }
87313
87314 #ifndef SQLITE_OMIT_VIEW
87315   if( pTab->pSelect ){
87316     sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
87317     goto exit_rename_table;
87318   }
87319 #endif
87320
87321 #ifndef SQLITE_OMIT_AUTHORIZATION
87322   /* Invoke the authorization callback. */
87323   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
87324     goto exit_rename_table;
87325   }
87326 #endif
87327
87328 #ifndef SQLITE_OMIT_VIRTUALTABLE
87329   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
87330     goto exit_rename_table;
87331   }
87332   if( IsVirtual(pTab) ){
87333     pVTab = sqlite3GetVTable(db, pTab);
87334     if( pVTab->pVtab->pModule->xRename==0 ){
87335       pVTab = 0;
87336     }
87337   }
87338 #endif
87339
87340   /* Begin a transaction for database iDb. 
87341   ** Then modify the schema cookie (since the ALTER TABLE modifies the
87342   ** schema). Open a statement transaction if the table is a virtual
87343   ** table.
87344   */
87345   v = sqlite3GetVdbe(pParse);
87346   if( v==0 ){
87347     goto exit_rename_table;
87348   }
87349   sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
87350   sqlite3ChangeCookie(pParse, iDb);
87351
87352   /* If this is a virtual table, invoke the xRename() function if
87353   ** one is defined. The xRename() callback will modify the names
87354   ** of any resources used by the v-table implementation (including other
87355   ** SQLite tables) that are identified by the name of the virtual table.
87356   */
87357 #ifndef SQLITE_OMIT_VIRTUALTABLE
87358   if( pVTab ){
87359     int i = ++pParse->nMem;
87360     sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
87361     sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
87362     sqlite3MayAbort(pParse);
87363   }
87364 #endif
87365
87366   /* figure out how many UTF-8 characters are in zName */
87367   zTabName = pTab->zName;
87368   nTabName = sqlite3Utf8CharLen(zTabName, -1);
87369
87370 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
87371   if( db->flags&SQLITE_ForeignKeys ){
87372     /* If foreign-key support is enabled, rewrite the CREATE TABLE 
87373     ** statements corresponding to all child tables of foreign key constraints
87374     ** for which the renamed table is the parent table.  */
87375     if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
87376       sqlite3NestedParse(pParse, 
87377           "UPDATE \"%w\".%s SET "
87378               "sql = sqlite_rename_parent(sql, %Q, %Q) "
87379               "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
87380       sqlite3DbFree(db, zWhere);
87381     }
87382   }
87383 #endif
87384
87385   /* Modify the sqlite_master table to use the new table name. */
87386   sqlite3NestedParse(pParse,
87387       "UPDATE %Q.%s SET "
87388 #ifdef SQLITE_OMIT_TRIGGER
87389           "sql = sqlite_rename_table(sql, %Q), "
87390 #else
87391           "sql = CASE "
87392             "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
87393             "ELSE sqlite_rename_table(sql, %Q) END, "
87394 #endif
87395           "tbl_name = %Q, "
87396           "name = CASE "
87397             "WHEN type='table' THEN %Q "
87398             "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
87399              "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
87400             "ELSE name END "
87401       "WHERE tbl_name=%Q COLLATE nocase AND "
87402           "(type='table' OR type='index' OR type='trigger');", 
87403       zDb, SCHEMA_TABLE(iDb), zName, zName, zName, 
87404 #ifndef SQLITE_OMIT_TRIGGER
87405       zName,
87406 #endif
87407       zName, nTabName, zTabName
87408   );
87409
87410 #ifndef SQLITE_OMIT_AUTOINCREMENT
87411   /* If the sqlite_sequence table exists in this database, then update 
87412   ** it with the new table name.
87413   */
87414   if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
87415     sqlite3NestedParse(pParse,
87416         "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
87417         zDb, zName, pTab->zName);
87418   }
87419 #endif
87420
87421 #ifndef SQLITE_OMIT_TRIGGER
87422   /* If there are TEMP triggers on this table, modify the sqlite_temp_master
87423   ** table. Don't do this if the table being ALTERed is itself located in
87424   ** the temp database.
87425   */
87426   if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
87427     sqlite3NestedParse(pParse, 
87428         "UPDATE sqlite_temp_master SET "
87429             "sql = sqlite_rename_trigger(sql, %Q), "
87430             "tbl_name = %Q "
87431             "WHERE %s;", zName, zName, zWhere);
87432     sqlite3DbFree(db, zWhere);
87433   }
87434 #endif
87435
87436 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
87437   if( db->flags&SQLITE_ForeignKeys ){
87438     FKey *p;
87439     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
87440       Table *pFrom = p->pFrom;
87441       if( pFrom!=pTab ){
87442         reloadTableSchema(pParse, p->pFrom, pFrom->zName);
87443       }
87444     }
87445   }
87446 #endif
87447
87448   /* Drop and reload the internal table schema. */
87449   reloadTableSchema(pParse, pTab, zName);
87450
87451 exit_rename_table:
87452   sqlite3SrcListDelete(db, pSrc);
87453   sqlite3DbFree(db, zName);
87454   db->flags = savedDbFlags;
87455 }
87456
87457
87458 /*
87459 ** Generate code to make sure the file format number is at least minFormat.
87460 ** The generated code will increase the file format number if necessary.
87461 */
87462 SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
87463   Vdbe *v;
87464   v = sqlite3GetVdbe(pParse);
87465   /* The VDBE should have been allocated before this routine is called.
87466   ** If that allocation failed, we would have quit before reaching this
87467   ** point */
87468   if( ALWAYS(v) ){
87469     int r1 = sqlite3GetTempReg(pParse);
87470     int r2 = sqlite3GetTempReg(pParse);
87471     int j1;
87472     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
87473     sqlite3VdbeUsesBtree(v, iDb);
87474     sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
87475     j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
87476     sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverage(v);
87477     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
87478     sqlite3VdbeJumpHere(v, j1);
87479     sqlite3ReleaseTempReg(pParse, r1);
87480     sqlite3ReleaseTempReg(pParse, r2);
87481   }
87482 }
87483
87484 /*
87485 ** This function is called after an "ALTER TABLE ... ADD" statement
87486 ** has been parsed. Argument pColDef contains the text of the new
87487 ** column definition.
87488 **
87489 ** The Table structure pParse->pNewTable was extended to include
87490 ** the new column during parsing.
87491 */
87492 SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
87493   Table *pNew;              /* Copy of pParse->pNewTable */
87494   Table *pTab;              /* Table being altered */
87495   int iDb;                  /* Database number */
87496   const char *zDb;          /* Database name */
87497   const char *zTab;         /* Table name */
87498   char *zCol;               /* Null-terminated column definition */
87499   Column *pCol;             /* The new column */
87500   Expr *pDflt;              /* Default value for the new column */
87501   sqlite3 *db;              /* The database connection; */
87502
87503   db = pParse->db;
87504   if( pParse->nErr || db->mallocFailed ) return;
87505   pNew = pParse->pNewTable;
87506   assert( pNew );
87507
87508   assert( sqlite3BtreeHoldsAllMutexes(db) );
87509   iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
87510   zDb = db->aDb[iDb].zName;
87511   zTab = &pNew->zName[16];  /* Skip the "sqlite_altertab_" prefix on the name */
87512   pCol = &pNew->aCol[pNew->nCol-1];
87513   pDflt = pCol->pDflt;
87514   pTab = sqlite3FindTable(db, zTab, zDb);
87515   assert( pTab );
87516
87517 #ifndef SQLITE_OMIT_AUTHORIZATION
87518   /* Invoke the authorization callback. */
87519   if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
87520     return;
87521   }
87522 #endif
87523
87524   /* If the default value for the new column was specified with a 
87525   ** literal NULL, then set pDflt to 0. This simplifies checking
87526   ** for an SQL NULL default below.
87527   */
87528   if( pDflt && pDflt->op==TK_NULL ){
87529     pDflt = 0;
87530   }
87531
87532   /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
87533   ** If there is a NOT NULL constraint, then the default value for the
87534   ** column must not be NULL.
87535   */
87536   if( pCol->colFlags & COLFLAG_PRIMKEY ){
87537     sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
87538     return;
87539   }
87540   if( pNew->pIndex ){
87541     sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
87542     return;
87543   }
87544   if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
87545     sqlite3ErrorMsg(pParse, 
87546         "Cannot add a REFERENCES column with non-NULL default value");
87547     return;
87548   }
87549   if( pCol->notNull && !pDflt ){
87550     sqlite3ErrorMsg(pParse, 
87551         "Cannot add a NOT NULL column with default value NULL");
87552     return;
87553   }
87554
87555   /* Ensure the default expression is something that sqlite3ValueFromExpr()
87556   ** can handle (i.e. not CURRENT_TIME etc.)
87557   */
87558   if( pDflt ){
87559     sqlite3_value *pVal = 0;
87560     int rc;
87561     rc = sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal);
87562     assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
87563     if( rc!=SQLITE_OK ){
87564       db->mallocFailed = 1;
87565       return;
87566     }
87567     if( !pVal ){
87568       sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
87569       return;
87570     }
87571     sqlite3ValueFree(pVal);
87572   }
87573
87574   /* Modify the CREATE TABLE statement. */
87575   zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
87576   if( zCol ){
87577     char *zEnd = &zCol[pColDef->n-1];
87578     int savedDbFlags = db->flags;
87579     while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
87580       *zEnd-- = '\0';
87581     }
87582     db->flags |= SQLITE_PreferBuiltin;
87583     sqlite3NestedParse(pParse, 
87584         "UPDATE \"%w\".%s SET "
87585           "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
87586         "WHERE type = 'table' AND name = %Q", 
87587       zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
87588       zTab
87589     );
87590     sqlite3DbFree(db, zCol);
87591     db->flags = savedDbFlags;
87592   }
87593
87594   /* If the default value of the new column is NULL, then set the file
87595   ** format to 2. If the default value of the new column is not NULL,
87596   ** the file format becomes 3.
87597   */
87598   sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
87599
87600   /* Reload the schema of the modified table. */
87601   reloadTableSchema(pParse, pTab, pTab->zName);
87602 }
87603
87604 /*
87605 ** This function is called by the parser after the table-name in
87606 ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument 
87607 ** pSrc is the full-name of the table being altered.
87608 **
87609 ** This routine makes a (partial) copy of the Table structure
87610 ** for the table being altered and sets Parse.pNewTable to point
87611 ** to it. Routines called by the parser as the column definition
87612 ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to 
87613 ** the copy. The copy of the Table structure is deleted by tokenize.c 
87614 ** after parsing is finished.
87615 **
87616 ** Routine sqlite3AlterFinishAddColumn() will be called to complete
87617 ** coding the "ALTER TABLE ... ADD" statement.
87618 */
87619 SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
87620   Table *pNew;
87621   Table *pTab;
87622   Vdbe *v;
87623   int iDb;
87624   int i;
87625   int nAlloc;
87626   sqlite3 *db = pParse->db;
87627
87628   /* Look up the table being altered. */
87629   assert( pParse->pNewTable==0 );
87630   assert( sqlite3BtreeHoldsAllMutexes(db) );
87631   if( db->mallocFailed ) goto exit_begin_add_column;
87632   pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
87633   if( !pTab ) goto exit_begin_add_column;
87634
87635 #ifndef SQLITE_OMIT_VIRTUALTABLE
87636   if( IsVirtual(pTab) ){
87637     sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
87638     goto exit_begin_add_column;
87639   }
87640 #endif
87641
87642   /* Make sure this is not an attempt to ALTER a view. */
87643   if( pTab->pSelect ){
87644     sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
87645     goto exit_begin_add_column;
87646   }
87647   if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
87648     goto exit_begin_add_column;
87649   }
87650
87651   assert( pTab->addColOffset>0 );
87652   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
87653
87654   /* Put a copy of the Table struct in Parse.pNewTable for the
87655   ** sqlite3AddColumn() function and friends to modify.  But modify
87656   ** the name by adding an "sqlite_altertab_" prefix.  By adding this
87657   ** prefix, we insure that the name will not collide with an existing
87658   ** table because user table are not allowed to have the "sqlite_"
87659   ** prefix on their name.
87660   */
87661   pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
87662   if( !pNew ) goto exit_begin_add_column;
87663   pParse->pNewTable = pNew;
87664   pNew->nRef = 1;
87665   pNew->nCol = pTab->nCol;
87666   assert( pNew->nCol>0 );
87667   nAlloc = (((pNew->nCol-1)/8)*8)+8;
87668   assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
87669   pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
87670   pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
87671   if( !pNew->aCol || !pNew->zName ){
87672     db->mallocFailed = 1;
87673     goto exit_begin_add_column;
87674   }
87675   memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
87676   for(i=0; i<pNew->nCol; i++){
87677     Column *pCol = &pNew->aCol[i];
87678     pCol->zName = sqlite3DbStrDup(db, pCol->zName);
87679     pCol->zColl = 0;
87680     pCol->zType = 0;
87681     pCol->pDflt = 0;
87682     pCol->zDflt = 0;
87683   }
87684   pNew->pSchema = db->aDb[iDb].pSchema;
87685   pNew->addColOffset = pTab->addColOffset;
87686   pNew->nRef = 1;
87687
87688   /* Begin a transaction and increment the schema cookie.  */
87689   sqlite3BeginWriteOperation(pParse, 0, iDb);
87690   v = sqlite3GetVdbe(pParse);
87691   if( !v ) goto exit_begin_add_column;
87692   sqlite3ChangeCookie(pParse, iDb);
87693
87694 exit_begin_add_column:
87695   sqlite3SrcListDelete(db, pSrc);
87696   return;
87697 }
87698 #endif  /* SQLITE_ALTER_TABLE */
87699
87700 /************** End of alter.c ***********************************************/
87701 /************** Begin file analyze.c *****************************************/
87702 /*
87703 ** 2005-07-08
87704 **
87705 ** The author disclaims copyright to this source code.  In place of
87706 ** a legal notice, here is a blessing:
87707 **
87708 **    May you do good and not evil.
87709 **    May you find forgiveness for yourself and forgive others.
87710 **    May you share freely, never taking more than you give.
87711 **
87712 *************************************************************************
87713 ** This file contains code associated with the ANALYZE command.
87714 **
87715 ** The ANALYZE command gather statistics about the content of tables
87716 ** and indices.  These statistics are made available to the query planner
87717 ** to help it make better decisions about how to perform queries.
87718 **
87719 ** The following system tables are or have been supported:
87720 **
87721 **    CREATE TABLE sqlite_stat1(tbl, idx, stat);
87722 **    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
87723 **    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
87724 **    CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
87725 **
87726 ** Additional tables might be added in future releases of SQLite.
87727 ** The sqlite_stat2 table is not created or used unless the SQLite version
87728 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
87729 ** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
87730 ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
87731 ** created and used by SQLite versions 3.7.9 and later and with
87732 ** SQLITE_ENABLE_STAT3 defined.  The functionality of sqlite_stat3
87733 ** is a superset of sqlite_stat2.  The sqlite_stat4 is an enhanced
87734 ** version of sqlite_stat3 and is only available when compiled with
87735 ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later.  It is
87736 ** not possible to enable both STAT3 and STAT4 at the same time.  If they
87737 ** are both enabled, then STAT4 takes precedence.
87738 **
87739 ** For most applications, sqlite_stat1 provides all the statistics required
87740 ** for the query planner to make good choices.
87741 **
87742 ** Format of sqlite_stat1:
87743 **
87744 ** There is normally one row per index, with the index identified by the
87745 ** name in the idx column.  The tbl column is the name of the table to
87746 ** which the index belongs.  In each such row, the stat column will be
87747 ** a string consisting of a list of integers.  The first integer in this
87748 ** list is the number of rows in the index.  (This is the same as the
87749 ** number of rows in the table, except for partial indices.)  The second
87750 ** integer is the average number of rows in the index that have the same
87751 ** value in the first column of the index.  The third integer is the average
87752 ** number of rows in the index that have the same value for the first two
87753 ** columns.  The N-th integer (for N>1) is the average number of rows in 
87754 ** the index which have the same value for the first N-1 columns.  For
87755 ** a K-column index, there will be K+1 integers in the stat column.  If
87756 ** the index is unique, then the last integer will be 1.
87757 **
87758 ** The list of integers in the stat column can optionally be followed
87759 ** by the keyword "unordered".  The "unordered" keyword, if it is present,
87760 ** must be separated from the last integer by a single space.  If the
87761 ** "unordered" keyword is present, then the query planner assumes that
87762 ** the index is unordered and will not use the index for a range query.
87763 ** 
87764 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
87765 ** column contains a single integer which is the (estimated) number of
87766 ** rows in the table identified by sqlite_stat1.tbl.
87767 **
87768 ** Format of sqlite_stat2:
87769 **
87770 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
87771 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
87772 ** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
87773 ** about the distribution of keys within an index.  The index is identified by
87774 ** the "idx" column and the "tbl" column is the name of the table to which
87775 ** the index belongs.  There are usually 10 rows in the sqlite_stat2
87776 ** table for each index.
87777 **
87778 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
87779 ** inclusive are samples of the left-most key value in the index taken at
87780 ** evenly spaced points along the index.  Let the number of samples be S
87781 ** (10 in the standard build) and let C be the number of rows in the index.
87782 ** Then the sampled rows are given by:
87783 **
87784 **     rownumber = (i*C*2 + C)/(S*2)
87785 **
87786 ** For i between 0 and S-1.  Conceptually, the index space is divided into
87787 ** S uniform buckets and the samples are the middle row from each bucket.
87788 **
87789 ** The format for sqlite_stat2 is recorded here for legacy reference.  This
87790 ** version of SQLite does not support sqlite_stat2.  It neither reads nor
87791 ** writes the sqlite_stat2 table.  This version of SQLite only supports
87792 ** sqlite_stat3.
87793 **
87794 ** Format for sqlite_stat3:
87795 **
87796 ** The sqlite_stat3 format is a subset of sqlite_stat4.  Hence, the
87797 ** sqlite_stat4 format will be described first.  Further information
87798 ** about sqlite_stat3 follows the sqlite_stat4 description.
87799 **
87800 ** Format for sqlite_stat4:
87801 **
87802 ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
87803 ** to aid the query planner in choosing good indices based on the values
87804 ** that indexed columns are compared against in the WHERE clauses of
87805 ** queries.
87806 **
87807 ** The sqlite_stat4 table contains multiple entries for each index.
87808 ** The idx column names the index and the tbl column is the table of the
87809 ** index.  If the idx and tbl columns are the same, then the sample is
87810 ** of the INTEGER PRIMARY KEY.  The sample column is a blob which is the
87811 ** binary encoding of a key from the index.  The nEq column is a
87812 ** list of integers.  The first integer is the approximate number
87813 ** of entries in the index whose left-most column exactly matches
87814 ** the left-most column of the sample.  The second integer in nEq
87815 ** is the approximate number of entries in the index where the
87816 ** first two columns match the first two columns of the sample.
87817 ** And so forth.  nLt is another list of integers that show the approximate
87818 ** number of entries that are strictly less than the sample.  The first
87819 ** integer in nLt contains the number of entries in the index where the
87820 ** left-most column is less than the left-most column of the sample.
87821 ** The K-th integer in the nLt entry is the number of index entries 
87822 ** where the first K columns are less than the first K columns of the
87823 ** sample.  The nDLt column is like nLt except that it contains the 
87824 ** number of distinct entries in the index that are less than the
87825 ** sample.
87826 **
87827 ** There can be an arbitrary number of sqlite_stat4 entries per index.
87828 ** The ANALYZE command will typically generate sqlite_stat4 tables
87829 ** that contain between 10 and 40 samples which are distributed across
87830 ** the key space, though not uniformly, and which include samples with
87831 ** large nEq values.
87832 **
87833 ** Format for sqlite_stat3 redux:
87834 **
87835 ** The sqlite_stat3 table is like sqlite_stat4 except that it only
87836 ** looks at the left-most column of the index.  The sqlite_stat3.sample
87837 ** column contains the actual value of the left-most column instead
87838 ** of a blob encoding of the complete index key as is found in
87839 ** sqlite_stat4.sample.  The nEq, nLt, and nDLt entries of sqlite_stat3
87840 ** all contain just a single integer which is the same as the first
87841 ** integer in the equivalent columns in sqlite_stat4.
87842 */
87843 #ifndef SQLITE_OMIT_ANALYZE
87844
87845 #if defined(SQLITE_ENABLE_STAT4)
87846 # define IsStat4     1
87847 # define IsStat3     0
87848 #elif defined(SQLITE_ENABLE_STAT3)
87849 # define IsStat4     0
87850 # define IsStat3     1
87851 #else
87852 # define IsStat4     0
87853 # define IsStat3     0
87854 # undef SQLITE_STAT4_SAMPLES
87855 # define SQLITE_STAT4_SAMPLES 1
87856 #endif
87857 #define IsStat34    (IsStat3+IsStat4)  /* 1 for STAT3 or STAT4. 0 otherwise */
87858
87859 /*
87860 ** This routine generates code that opens the sqlite_statN tables.
87861 ** The sqlite_stat1 table is always relevant.  sqlite_stat2 is now
87862 ** obsolete.  sqlite_stat3 and sqlite_stat4 are only opened when
87863 ** appropriate compile-time options are provided.
87864 **
87865 ** If the sqlite_statN tables do not previously exist, it is created.
87866 **
87867 ** Argument zWhere may be a pointer to a buffer containing a table name,
87868 ** or it may be a NULL pointer. If it is not NULL, then all entries in
87869 ** the sqlite_statN tables associated with the named table are deleted.
87870 ** If zWhere==0, then code is generated to delete all stat table entries.
87871 */
87872 static void openStatTable(
87873   Parse *pParse,          /* Parsing context */
87874   int iDb,                /* The database we are looking in */
87875   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
87876   const char *zWhere,     /* Delete entries for this table or index */
87877   const char *zWhereType  /* Either "tbl" or "idx" */
87878 ){
87879   static const struct {
87880     const char *zName;
87881     const char *zCols;
87882   } aTable[] = {
87883     { "sqlite_stat1", "tbl,idx,stat" },
87884 #if defined(SQLITE_ENABLE_STAT4)
87885     { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
87886     { "sqlite_stat3", 0 },
87887 #elif defined(SQLITE_ENABLE_STAT3)
87888     { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
87889     { "sqlite_stat4", 0 },
87890 #else
87891     { "sqlite_stat3", 0 },
87892     { "sqlite_stat4", 0 },
87893 #endif
87894   };
87895   int i;
87896   sqlite3 *db = pParse->db;
87897   Db *pDb;
87898   Vdbe *v = sqlite3GetVdbe(pParse);
87899   int aRoot[ArraySize(aTable)];
87900   u8 aCreateTbl[ArraySize(aTable)];
87901
87902   if( v==0 ) return;
87903   assert( sqlite3BtreeHoldsAllMutexes(db) );
87904   assert( sqlite3VdbeDb(v)==db );
87905   pDb = &db->aDb[iDb];
87906
87907   /* Create new statistic tables if they do not exist, or clear them
87908   ** if they do already exist.
87909   */
87910   for(i=0; i<ArraySize(aTable); i++){
87911     const char *zTab = aTable[i].zName;
87912     Table *pStat;
87913     if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
87914       if( aTable[i].zCols ){
87915         /* The sqlite_statN table does not exist. Create it. Note that a 
87916         ** side-effect of the CREATE TABLE statement is to leave the rootpage 
87917         ** of the new table in register pParse->regRoot. This is important 
87918         ** because the OpenWrite opcode below will be needing it. */
87919         sqlite3NestedParse(pParse,
87920             "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
87921         );
87922         aRoot[i] = pParse->regRoot;
87923         aCreateTbl[i] = OPFLAG_P2ISREG;
87924       }
87925     }else{
87926       /* The table already exists. If zWhere is not NULL, delete all entries 
87927       ** associated with the table zWhere. If zWhere is NULL, delete the
87928       ** entire contents of the table. */
87929       aRoot[i] = pStat->tnum;
87930       aCreateTbl[i] = 0;
87931       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
87932       if( zWhere ){
87933         sqlite3NestedParse(pParse,
87934            "DELETE FROM %Q.%s WHERE %s=%Q",
87935            pDb->zName, zTab, zWhereType, zWhere
87936         );
87937       }else{
87938         /* The sqlite_stat[134] table already exists.  Delete all rows. */
87939         sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
87940       }
87941     }
87942   }
87943
87944   /* Open the sqlite_stat[134] tables for writing. */
87945   for(i=0; aTable[i].zCols; i++){
87946     assert( i<ArraySize(aTable) );
87947     sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
87948     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
87949     VdbeComment((v, aTable[i].zName));
87950   }
87951 }
87952
87953 /*
87954 ** Recommended number of samples for sqlite_stat4
87955 */
87956 #ifndef SQLITE_STAT4_SAMPLES
87957 # define SQLITE_STAT4_SAMPLES 24
87958 #endif
87959
87960 /*
87961 ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
87962 ** share an instance of the following structure to hold their state
87963 ** information.
87964 */
87965 typedef struct Stat4Accum Stat4Accum;
87966 typedef struct Stat4Sample Stat4Sample;
87967 struct Stat4Sample {
87968   tRowcnt *anEq;                  /* sqlite_stat4.nEq */
87969   tRowcnt *anDLt;                 /* sqlite_stat4.nDLt */
87970 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
87971   tRowcnt *anLt;                  /* sqlite_stat4.nLt */
87972   union {
87973     i64 iRowid;                     /* Rowid in main table of the key */
87974     u8 *aRowid;                     /* Key for WITHOUT ROWID tables */
87975   } u;
87976   u32 nRowid;                     /* Sizeof aRowid[] */
87977   u8 isPSample;                   /* True if a periodic sample */
87978   int iCol;                       /* If !isPSample, the reason for inclusion */
87979   u32 iHash;                      /* Tiebreaker hash */
87980 #endif
87981 };                                                    
87982 struct Stat4Accum {
87983   tRowcnt nRow;             /* Number of rows in the entire table */
87984   tRowcnt nPSample;         /* How often to do a periodic sample */
87985   int nCol;                 /* Number of columns in index + pk/rowid */
87986   int nKeyCol;              /* Number of index columns w/o the pk/rowid */
87987   int mxSample;             /* Maximum number of samples to accumulate */
87988   Stat4Sample current;      /* Current row as a Stat4Sample */
87989   u32 iPrn;                 /* Pseudo-random number used for sampling */
87990   Stat4Sample *aBest;       /* Array of nCol best samples */
87991   int iMin;                 /* Index in a[] of entry with minimum score */
87992   int nSample;              /* Current number of samples */
87993   int iGet;                 /* Index of current sample accessed by stat_get() */
87994   Stat4Sample *a;           /* Array of mxSample Stat4Sample objects */
87995   sqlite3 *db;              /* Database connection, for malloc() */
87996 };
87997
87998 /* Reclaim memory used by a Stat4Sample
87999 */
88000 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88001 static void sampleClear(sqlite3 *db, Stat4Sample *p){
88002   assert( db!=0 );
88003   if( p->nRowid ){
88004     sqlite3DbFree(db, p->u.aRowid);
88005     p->nRowid = 0;
88006   }
88007 }
88008 #endif
88009
88010 /* Initialize the BLOB value of a ROWID
88011 */
88012 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88013 static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
88014   assert( db!=0 );
88015   if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
88016   p->u.aRowid = sqlite3DbMallocRaw(db, n);
88017   if( p->u.aRowid ){
88018     p->nRowid = n;
88019     memcpy(p->u.aRowid, pData, n);
88020   }else{
88021     p->nRowid = 0;
88022   }
88023 }
88024 #endif
88025
88026 /* Initialize the INTEGER value of a ROWID.
88027 */
88028 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88029 static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
88030   assert( db!=0 );
88031   if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
88032   p->nRowid = 0;
88033   p->u.iRowid = iRowid;
88034 }
88035 #endif
88036
88037
88038 /*
88039 ** Copy the contents of object (*pFrom) into (*pTo).
88040 */
88041 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88042 static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
88043   pTo->isPSample = pFrom->isPSample;
88044   pTo->iCol = pFrom->iCol;
88045   pTo->iHash = pFrom->iHash;
88046   memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
88047   memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
88048   memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
88049   if( pFrom->nRowid ){
88050     sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
88051   }else{
88052     sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
88053   }
88054 }
88055 #endif
88056
88057 /*
88058 ** Reclaim all memory of a Stat4Accum structure.
88059 */
88060 static void stat4Destructor(void *pOld){
88061   Stat4Accum *p = (Stat4Accum*)pOld;
88062 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88063   int i;
88064   for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
88065   for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
88066   sampleClear(p->db, &p->current);
88067 #endif
88068   sqlite3DbFree(p->db, p);
88069 }
88070
88071 /*
88072 ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
88073 ** are:
88074 **     N:    The number of columns in the index including the rowid/pk (note 1)
88075 **     K:    The number of columns in the index excluding the rowid/pk.
88076 **     C:    The number of rows in the index (note 2)
88077 **
88078 ** Note 1:  In the special case of the covering index that implements a
88079 ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
88080 ** total number of columns in the table.
88081 **
88082 ** Note 2:  C is only used for STAT3 and STAT4.
88083 **
88084 ** For indexes on ordinary rowid tables, N==K+1.  But for indexes on
88085 ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
88086 ** PRIMARY KEY of the table.  The covering index that implements the
88087 ** original WITHOUT ROWID table as N==K as a special case.
88088 **
88089 ** This routine allocates the Stat4Accum object in heap memory. The return 
88090 ** value is a pointer to the Stat4Accum object.  The datatype of the
88091 ** return value is BLOB, but it is really just a pointer to the Stat4Accum
88092 ** object.
88093 */
88094 static void statInit(
88095   sqlite3_context *context,
88096   int argc,
88097   sqlite3_value **argv
88098 ){
88099   Stat4Accum *p;
88100   int nCol;                       /* Number of columns in index being sampled */
88101   int nKeyCol;                    /* Number of key columns */
88102   int nColUp;                     /* nCol rounded up for alignment */
88103   int n;                          /* Bytes of space to allocate */
88104   sqlite3 *db;                    /* Database connection */
88105 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88106   int mxSample = SQLITE_STAT4_SAMPLES;
88107 #endif
88108
88109   /* Decode the three function arguments */
88110   UNUSED_PARAMETER(argc);
88111   nCol = sqlite3_value_int(argv[0]);
88112   assert( nCol>0 );
88113   nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
88114   nKeyCol = sqlite3_value_int(argv[1]);
88115   assert( nKeyCol<=nCol );
88116   assert( nKeyCol>0 );
88117
88118   /* Allocate the space required for the Stat4Accum object */
88119   n = sizeof(*p) 
88120     + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anEq */
88121     + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anDLt */
88122 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88123     + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anLt */
88124     + sizeof(Stat4Sample)*(nCol+mxSample)     /* Stat4Accum.aBest[], a[] */
88125     + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
88126 #endif
88127   ;
88128   db = sqlite3_context_db_handle(context);
88129   p = sqlite3DbMallocZero(db, n);
88130   if( p==0 ){
88131     sqlite3_result_error_nomem(context);
88132     return;
88133   }
88134
88135   p->db = db;
88136   p->nRow = 0;
88137   p->nCol = nCol;
88138   p->nKeyCol = nKeyCol;
88139   p->current.anDLt = (tRowcnt*)&p[1];
88140   p->current.anEq = &p->current.anDLt[nColUp];
88141
88142 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88143   {
88144     u8 *pSpace;                     /* Allocated space not yet assigned */
88145     int i;                          /* Used to iterate through p->aSample[] */
88146
88147     p->iGet = -1;
88148     p->mxSample = mxSample;
88149     p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
88150     p->current.anLt = &p->current.anEq[nColUp];
88151     p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
88152   
88153     /* Set up the Stat4Accum.a[] and aBest[] arrays */
88154     p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
88155     p->aBest = &p->a[mxSample];
88156     pSpace = (u8*)(&p->a[mxSample+nCol]);
88157     for(i=0; i<(mxSample+nCol); i++){
88158       p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
88159       p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
88160       p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
88161     }
88162     assert( (pSpace - (u8*)p)==n );
88163   
88164     for(i=0; i<nCol; i++){
88165       p->aBest[i].iCol = i;
88166     }
88167   }
88168 #endif
88169
88170   /* Return a pointer to the allocated object to the caller.  Note that
88171   ** only the pointer (the 2nd parameter) matters.  The size of the object
88172   ** (given by the 3rd parameter) is never used and can be any positive
88173   ** value. */
88174   sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
88175 }
88176 static const FuncDef statInitFuncdef = {
88177   2+IsStat34,      /* nArg */
88178   SQLITE_UTF8,     /* funcFlags */
88179   0,               /* pUserData */
88180   0,               /* pNext */
88181   statInit,        /* xFunc */
88182   0,               /* xStep */
88183   0,               /* xFinalize */
88184   "stat_init",     /* zName */
88185   0,               /* pHash */
88186   0                /* pDestructor */
88187 };
88188
88189 #ifdef SQLITE_ENABLE_STAT4
88190 /*
88191 ** pNew and pOld are both candidate non-periodic samples selected for 
88192 ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and 
88193 ** considering only any trailing columns and the sample hash value, this
88194 ** function returns true if sample pNew is to be preferred over pOld.
88195 ** In other words, if we assume that the cardinalities of the selected
88196 ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
88197 **
88198 ** This function assumes that for each argument sample, the contents of
88199 ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid. 
88200 */
88201 static int sampleIsBetterPost(
88202   Stat4Accum *pAccum, 
88203   Stat4Sample *pNew, 
88204   Stat4Sample *pOld
88205 ){
88206   int nCol = pAccum->nCol;
88207   int i;
88208   assert( pNew->iCol==pOld->iCol );
88209   for(i=pNew->iCol+1; i<nCol; i++){
88210     if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
88211     if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
88212   }
88213   if( pNew->iHash>pOld->iHash ) return 1;
88214   return 0;
88215 }
88216 #endif
88217
88218 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88219 /*
88220 ** Return true if pNew is to be preferred over pOld.
88221 **
88222 ** This function assumes that for each argument sample, the contents of
88223 ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid. 
88224 */
88225 static int sampleIsBetter(
88226   Stat4Accum *pAccum, 
88227   Stat4Sample *pNew, 
88228   Stat4Sample *pOld
88229 ){
88230   tRowcnt nEqNew = pNew->anEq[pNew->iCol];
88231   tRowcnt nEqOld = pOld->anEq[pOld->iCol];
88232
88233   assert( pOld->isPSample==0 && pNew->isPSample==0 );
88234   assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
88235
88236   if( (nEqNew>nEqOld) ) return 1;
88237 #ifdef SQLITE_ENABLE_STAT4
88238   if( nEqNew==nEqOld ){
88239     if( pNew->iCol<pOld->iCol ) return 1;
88240     return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
88241   }
88242   return 0;
88243 #else
88244   return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
88245 #endif
88246 }
88247
88248 /*
88249 ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
88250 ** remove the least desirable sample from p->a[] to make room.
88251 */
88252 static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
88253   Stat4Sample *pSample = 0;
88254   int i;
88255
88256   assert( IsStat4 || nEqZero==0 );
88257
88258 #ifdef SQLITE_ENABLE_STAT4
88259   if( pNew->isPSample==0 ){
88260     Stat4Sample *pUpgrade = 0;
88261     assert( pNew->anEq[pNew->iCol]>0 );
88262
88263     /* This sample is being added because the prefix that ends in column 
88264     ** iCol occurs many times in the table. However, if we have already
88265     ** added a sample that shares this prefix, there is no need to add
88266     ** this one. Instead, upgrade the priority of the highest priority
88267     ** existing sample that shares this prefix.  */
88268     for(i=p->nSample-1; i>=0; i--){
88269       Stat4Sample *pOld = &p->a[i];
88270       if( pOld->anEq[pNew->iCol]==0 ){
88271         if( pOld->isPSample ) return;
88272         assert( pOld->iCol>pNew->iCol );
88273         assert( sampleIsBetter(p, pNew, pOld) );
88274         if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
88275           pUpgrade = pOld;
88276         }
88277       }
88278     }
88279     if( pUpgrade ){
88280       pUpgrade->iCol = pNew->iCol;
88281       pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
88282       goto find_new_min;
88283     }
88284   }
88285 #endif
88286
88287   /* If necessary, remove sample iMin to make room for the new sample. */
88288   if( p->nSample>=p->mxSample ){
88289     Stat4Sample *pMin = &p->a[p->iMin];
88290     tRowcnt *anEq = pMin->anEq;
88291     tRowcnt *anLt = pMin->anLt;
88292     tRowcnt *anDLt = pMin->anDLt;
88293     sampleClear(p->db, pMin);
88294     memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
88295     pSample = &p->a[p->nSample-1];
88296     pSample->nRowid = 0;
88297     pSample->anEq = anEq;
88298     pSample->anDLt = anDLt;
88299     pSample->anLt = anLt;
88300     p->nSample = p->mxSample-1;
88301   }
88302
88303   /* The "rows less-than" for the rowid column must be greater than that
88304   ** for the last sample in the p->a[] array. Otherwise, the samples would
88305   ** be out of order. */
88306 #ifdef SQLITE_ENABLE_STAT4
88307   assert( p->nSample==0 
88308        || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
88309 #endif
88310
88311   /* Insert the new sample */
88312   pSample = &p->a[p->nSample];
88313   sampleCopy(p, pSample, pNew);
88314   p->nSample++;
88315
88316   /* Zero the first nEqZero entries in the anEq[] array. */
88317   memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
88318
88319 #ifdef SQLITE_ENABLE_STAT4
88320  find_new_min:
88321 #endif
88322   if( p->nSample>=p->mxSample ){
88323     int iMin = -1;
88324     for(i=0; i<p->mxSample; i++){
88325       if( p->a[i].isPSample ) continue;
88326       if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
88327         iMin = i;
88328       }
88329     }
88330     assert( iMin>=0 );
88331     p->iMin = iMin;
88332   }
88333 }
88334 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
88335
88336 /*
88337 ** Field iChng of the index being scanned has changed. So at this point
88338 ** p->current contains a sample that reflects the previous row of the
88339 ** index. The value of anEq[iChng] and subsequent anEq[] elements are
88340 ** correct at this point.
88341 */
88342 static void samplePushPrevious(Stat4Accum *p, int iChng){
88343 #ifdef SQLITE_ENABLE_STAT4
88344   int i;
88345
88346   /* Check if any samples from the aBest[] array should be pushed
88347   ** into IndexSample.a[] at this point.  */
88348   for(i=(p->nCol-2); i>=iChng; i--){
88349     Stat4Sample *pBest = &p->aBest[i];
88350     pBest->anEq[i] = p->current.anEq[i];
88351     if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
88352       sampleInsert(p, pBest, i);
88353     }
88354   }
88355
88356   /* Update the anEq[] fields of any samples already collected. */
88357   for(i=p->nSample-1; i>=0; i--){
88358     int j;
88359     for(j=iChng; j<p->nCol; j++){
88360       if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
88361     }
88362   }
88363 #endif
88364
88365 #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
88366   if( iChng==0 ){
88367     tRowcnt nLt = p->current.anLt[0];
88368     tRowcnt nEq = p->current.anEq[0];
88369
88370     /* Check if this is to be a periodic sample. If so, add it. */
88371     if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
88372       p->current.isPSample = 1;
88373       sampleInsert(p, &p->current, 0);
88374       p->current.isPSample = 0;
88375     }else 
88376
88377     /* Or if it is a non-periodic sample. Add it in this case too. */
88378     if( p->nSample<p->mxSample 
88379      || sampleIsBetter(p, &p->current, &p->a[p->iMin]) 
88380     ){
88381       sampleInsert(p, &p->current, 0);
88382     }
88383   }
88384 #endif
88385
88386 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
88387   UNUSED_PARAMETER( p );
88388   UNUSED_PARAMETER( iChng );
88389 #endif
88390 }
88391
88392 /*
88393 ** Implementation of the stat_push SQL function:  stat_push(P,C,R)
88394 ** Arguments:
88395 **
88396 **    P     Pointer to the Stat4Accum object created by stat_init()
88397 **    C     Index of left-most column to differ from previous row
88398 **    R     Rowid for the current row.  Might be a key record for
88399 **          WITHOUT ROWID tables.
88400 **
88401 ** This SQL function always returns NULL.  It's purpose it to accumulate
88402 ** statistical data and/or samples in the Stat4Accum object about the
88403 ** index being analyzed.  The stat_get() SQL function will later be used to
88404 ** extract relevant information for constructing the sqlite_statN tables.
88405 **
88406 ** The R parameter is only used for STAT3 and STAT4
88407 */
88408 static void statPush(
88409   sqlite3_context *context,
88410   int argc,
88411   sqlite3_value **argv
88412 ){
88413   int i;
88414
88415   /* The three function arguments */
88416   Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
88417   int iChng = sqlite3_value_int(argv[1]);
88418
88419   UNUSED_PARAMETER( argc );
88420   UNUSED_PARAMETER( context );
88421   assert( p->nCol>0 );
88422   assert( iChng<p->nCol );
88423
88424   if( p->nRow==0 ){
88425     /* This is the first call to this function. Do initialization. */
88426     for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
88427   }else{
88428     /* Second and subsequent calls get processed here */
88429     samplePushPrevious(p, iChng);
88430
88431     /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
88432     ** to the current row of the index. */
88433     for(i=0; i<iChng; i++){
88434       p->current.anEq[i]++;
88435     }
88436     for(i=iChng; i<p->nCol; i++){
88437       p->current.anDLt[i]++;
88438 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88439       p->current.anLt[i] += p->current.anEq[i];
88440 #endif
88441       p->current.anEq[i] = 1;
88442     }
88443   }
88444   p->nRow++;
88445 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88446   if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
88447     sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
88448   }else{
88449     sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
88450                                        sqlite3_value_blob(argv[2]));
88451   }
88452   p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
88453 #endif
88454
88455 #ifdef SQLITE_ENABLE_STAT4
88456   {
88457     tRowcnt nLt = p->current.anLt[p->nCol-1];
88458
88459     /* Check if this is to be a periodic sample. If so, add it. */
88460     if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
88461       p->current.isPSample = 1;
88462       p->current.iCol = 0;
88463       sampleInsert(p, &p->current, p->nCol-1);
88464       p->current.isPSample = 0;
88465     }
88466
88467     /* Update the aBest[] array. */
88468     for(i=0; i<(p->nCol-1); i++){
88469       p->current.iCol = i;
88470       if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
88471         sampleCopy(p, &p->aBest[i], &p->current);
88472       }
88473     }
88474   }
88475 #endif
88476 }
88477 static const FuncDef statPushFuncdef = {
88478   2+IsStat34,      /* nArg */
88479   SQLITE_UTF8,     /* funcFlags */
88480   0,               /* pUserData */
88481   0,               /* pNext */
88482   statPush,        /* xFunc */
88483   0,               /* xStep */
88484   0,               /* xFinalize */
88485   "stat_push",     /* zName */
88486   0,               /* pHash */
88487   0                /* pDestructor */
88488 };
88489
88490 #define STAT_GET_STAT1 0          /* "stat" column of stat1 table */
88491 #define STAT_GET_ROWID 1          /* "rowid" column of stat[34] entry */
88492 #define STAT_GET_NEQ   2          /* "neq" column of stat[34] entry */
88493 #define STAT_GET_NLT   3          /* "nlt" column of stat[34] entry */
88494 #define STAT_GET_NDLT  4          /* "ndlt" column of stat[34] entry */
88495
88496 /*
88497 ** Implementation of the stat_get(P,J) SQL function.  This routine is
88498 ** used to query statistical information that has been gathered into
88499 ** the Stat4Accum object by prior calls to stat_push().  The P parameter
88500 ** has type BLOB but it is really just a pointer to the Stat4Accum object.
88501 ** The content to returned is determined by the parameter J
88502 ** which is one of the STAT_GET_xxxx values defined above.
88503 **
88504 ** If neither STAT3 nor STAT4 are enabled, then J is always
88505 ** STAT_GET_STAT1 and is hence omitted and this routine becomes
88506 ** a one-parameter function, stat_get(P), that always returns the
88507 ** stat1 table entry information.
88508 */
88509 static void statGet(
88510   sqlite3_context *context,
88511   int argc,
88512   sqlite3_value **argv
88513 ){
88514   Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
88515 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88516   /* STAT3 and STAT4 have a parameter on this routine. */
88517   int eCall = sqlite3_value_int(argv[1]);
88518   assert( argc==2 );
88519   assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ 
88520        || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
88521        || eCall==STAT_GET_NDLT 
88522   );
88523   if( eCall==STAT_GET_STAT1 )
88524 #else
88525   assert( argc==1 );
88526 #endif
88527   {
88528     /* Return the value to store in the "stat" column of the sqlite_stat1
88529     ** table for this index.
88530     **
88531     ** The value is a string composed of a list of integers describing 
88532     ** the index. The first integer in the list is the total number of 
88533     ** entries in the index. There is one additional integer in the list 
88534     ** for each indexed column. This additional integer is an estimate of
88535     ** the number of rows matched by a stabbing query on the index using
88536     ** a key with the corresponding number of fields. In other words,
88537     ** if the index is on columns (a,b) and the sqlite_stat1 value is 
88538     ** "100 10 2", then SQLite estimates that:
88539     **
88540     **   * the index contains 100 rows,
88541     **   * "WHERE a=?" matches 10 rows, and
88542     **   * "WHERE a=? AND b=?" matches 2 rows.
88543     **
88544     ** If D is the count of distinct values and K is the total number of 
88545     ** rows, then each estimate is computed as:
88546     **
88547     **        I = (K+D-1)/D
88548     */
88549     char *z;
88550     int i;
88551
88552     char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
88553     if( zRet==0 ){
88554       sqlite3_result_error_nomem(context);
88555       return;
88556     }
88557
88558     sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
88559     z = zRet + sqlite3Strlen30(zRet);
88560     for(i=0; i<p->nKeyCol; i++){
88561       u64 nDistinct = p->current.anDLt[i] + 1;
88562       u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
88563       sqlite3_snprintf(24, z, " %llu", iVal);
88564       z += sqlite3Strlen30(z);
88565       assert( p->current.anEq[i] );
88566     }
88567     assert( z[0]=='\0' && z>zRet );
88568
88569     sqlite3_result_text(context, zRet, -1, sqlite3_free);
88570   }
88571 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88572   else if( eCall==STAT_GET_ROWID ){
88573     if( p->iGet<0 ){
88574       samplePushPrevious(p, 0);
88575       p->iGet = 0;
88576     }
88577     if( p->iGet<p->nSample ){
88578       Stat4Sample *pS = p->a + p->iGet;
88579       if( pS->nRowid==0 ){
88580         sqlite3_result_int64(context, pS->u.iRowid);
88581       }else{
88582         sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
88583                             SQLITE_TRANSIENT);
88584       }
88585     }
88586   }else{
88587     tRowcnt *aCnt = 0;
88588
88589     assert( p->iGet<p->nSample );
88590     switch( eCall ){
88591       case STAT_GET_NEQ:  aCnt = p->a[p->iGet].anEq; break;
88592       case STAT_GET_NLT:  aCnt = p->a[p->iGet].anLt; break;
88593       default: {
88594         aCnt = p->a[p->iGet].anDLt; 
88595         p->iGet++;
88596         break;
88597       }
88598     }
88599
88600     if( IsStat3 ){
88601       sqlite3_result_int64(context, (i64)aCnt[0]);
88602     }else{
88603       char *zRet = sqlite3MallocZero(p->nCol * 25);
88604       if( zRet==0 ){
88605         sqlite3_result_error_nomem(context);
88606       }else{
88607         int i;
88608         char *z = zRet;
88609         for(i=0; i<p->nCol; i++){
88610           sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
88611           z += sqlite3Strlen30(z);
88612         }
88613         assert( z[0]=='\0' && z>zRet );
88614         z[-1] = '\0';
88615         sqlite3_result_text(context, zRet, -1, sqlite3_free);
88616       }
88617     }
88618   }
88619 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
88620 #ifndef SQLITE_DEBUG
88621   UNUSED_PARAMETER( argc );
88622 #endif
88623 }
88624 static const FuncDef statGetFuncdef = {
88625   1+IsStat34,      /* nArg */
88626   SQLITE_UTF8,     /* funcFlags */
88627   0,               /* pUserData */
88628   0,               /* pNext */
88629   statGet,         /* xFunc */
88630   0,               /* xStep */
88631   0,               /* xFinalize */
88632   "stat_get",      /* zName */
88633   0,               /* pHash */
88634   0                /* pDestructor */
88635 };
88636
88637 static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
88638   assert( regOut!=regStat4 && regOut!=regStat4+1 );
88639 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88640   sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
88641 #elif SQLITE_DEBUG
88642   assert( iParam==STAT_GET_STAT1 );
88643 #else
88644   UNUSED_PARAMETER( iParam );
88645 #endif
88646   sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut);
88647   sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
88648   sqlite3VdbeChangeP5(v, 1 + IsStat34);
88649 }
88650
88651 /*
88652 ** Generate code to do an analysis of all indices associated with
88653 ** a single table.
88654 */
88655 static void analyzeOneTable(
88656   Parse *pParse,   /* Parser context */
88657   Table *pTab,     /* Table whose indices are to be analyzed */
88658   Index *pOnlyIdx, /* If not NULL, only analyze this one index */
88659   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
88660   int iMem,        /* Available memory locations begin here */
88661   int iTab         /* Next available cursor */
88662 ){
88663   sqlite3 *db = pParse->db;    /* Database handle */
88664   Index *pIdx;                 /* An index to being analyzed */
88665   int iIdxCur;                 /* Cursor open on index being analyzed */
88666   int iTabCur;                 /* Table cursor */
88667   Vdbe *v;                     /* The virtual machine being built up */
88668   int i;                       /* Loop counter */
88669   int jZeroRows = -1;          /* Jump from here if number of rows is zero */
88670   int iDb;                     /* Index of database containing pTab */
88671   u8 needTableCnt = 1;         /* True to count the table */
88672   int regNewRowid = iMem++;    /* Rowid for the inserted record */
88673   int regStat4 = iMem++;       /* Register to hold Stat4Accum object */
88674   int regChng = iMem++;        /* Index of changed index field */
88675 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88676   int regRowid = iMem++;       /* Rowid argument passed to stat_push() */
88677 #endif
88678   int regTemp = iMem++;        /* Temporary use register */
88679   int regTabname = iMem++;     /* Register containing table name */
88680   int regIdxname = iMem++;     /* Register containing index name */
88681   int regStat1 = iMem++;       /* Value for the stat column of sqlite_stat1 */
88682   int regPrev = iMem;          /* MUST BE LAST (see below) */
88683
88684   pParse->nMem = MAX(pParse->nMem, iMem);
88685   v = sqlite3GetVdbe(pParse);
88686   if( v==0 || NEVER(pTab==0) ){
88687     return;
88688   }
88689   if( pTab->tnum==0 ){
88690     /* Do not gather statistics on views or virtual tables */
88691     return;
88692   }
88693   if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
88694     /* Do not gather statistics on system tables */
88695     return;
88696   }
88697   assert( sqlite3BtreeHoldsAllMutexes(db) );
88698   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
88699   assert( iDb>=0 );
88700   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
88701 #ifndef SQLITE_OMIT_AUTHORIZATION
88702   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
88703       db->aDb[iDb].zName ) ){
88704     return;
88705   }
88706 #endif
88707
88708   /* Establish a read-lock on the table at the shared-cache level. 
88709   ** Open a read-only cursor on the table. Also allocate a cursor number
88710   ** to use for scanning indexes (iIdxCur). No index cursor is opened at
88711   ** this time though.  */
88712   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
88713   iTabCur = iTab++;
88714   iIdxCur = iTab++;
88715   pParse->nTab = MAX(pParse->nTab, iTab);
88716   sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
88717   sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
88718
88719   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
88720     int nCol;                     /* Number of columns in pIdx. "N" */
88721     int addrRewind;               /* Address of "OP_Rewind iIdxCur" */
88722     int addrNextRow;              /* Address of "next_row:" */
88723     const char *zIdxName;         /* Name of the index */
88724     int nColTest;                 /* Number of columns to test for changes */
88725
88726     if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
88727     if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
88728     if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
88729       nCol = pIdx->nKeyCol;
88730       zIdxName = pTab->zName;
88731       nColTest = nCol - 1;
88732     }else{
88733       nCol = pIdx->nColumn;
88734       zIdxName = pIdx->zName;
88735       nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
88736     }
88737
88738     /* Populate the register containing the index name. */
88739     sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, zIdxName, 0);
88740     VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
88741
88742     /*
88743     ** Pseudo-code for loop that calls stat_push():
88744     **
88745     **   Rewind csr
88746     **   if eof(csr) goto end_of_scan;
88747     **   regChng = 0
88748     **   goto chng_addr_0;
88749     **
88750     **  next_row:
88751     **   regChng = 0
88752     **   if( idx(0) != regPrev(0) ) goto chng_addr_0
88753     **   regChng = 1
88754     **   if( idx(1) != regPrev(1) ) goto chng_addr_1
88755     **   ...
88756     **   regChng = N
88757     **   goto chng_addr_N
88758     **
88759     **  chng_addr_0:
88760     **   regPrev(0) = idx(0)
88761     **  chng_addr_1:
88762     **   regPrev(1) = idx(1)
88763     **  ...
88764     **
88765     **  endDistinctTest:
88766     **   regRowid = idx(rowid)
88767     **   stat_push(P, regChng, regRowid)
88768     **   Next csr
88769     **   if !eof(csr) goto next_row;
88770     **
88771     **  end_of_scan:
88772     */
88773
88774     /* Make sure there are enough memory cells allocated to accommodate 
88775     ** the regPrev array and a trailing rowid (the rowid slot is required
88776     ** when building a record to insert into the sample column of 
88777     ** the sqlite_stat4 table.  */
88778     pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
88779
88780     /* Open a read-only cursor on the index being analyzed. */
88781     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
88782     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
88783     sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
88784     VdbeComment((v, "%s", pIdx->zName));
88785
88786     /* Invoke the stat_init() function. The arguments are:
88787     ** 
88788     **    (1) the number of columns in the index including the rowid
88789     **        (or for a WITHOUT ROWID table, the number of PK columns),
88790     **    (2) the number of columns in the key without the rowid/pk
88791     **    (3) the number of rows in the index,
88792     **
88793     **
88794     ** The third argument is only used for STAT3 and STAT4
88795     */
88796 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88797     sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
88798 #endif
88799     sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
88800     sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
88801     sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4+1, regStat4);
88802     sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
88803     sqlite3VdbeChangeP5(v, 2+IsStat34);
88804
88805     /* Implementation of the following:
88806     **
88807     **   Rewind csr
88808     **   if eof(csr) goto end_of_scan;
88809     **   regChng = 0
88810     **   goto next_push_0;
88811     **
88812     */
88813     addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
88814     VdbeCoverage(v);
88815     sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
88816     addrNextRow = sqlite3VdbeCurrentAddr(v);
88817
88818     if( nColTest>0 ){
88819       int endDistinctTest = sqlite3VdbeMakeLabel(v);
88820       int *aGotoChng;               /* Array of jump instruction addresses */
88821       aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*nColTest);
88822       if( aGotoChng==0 ) continue;
88823
88824       /*
88825       **  next_row:
88826       **   regChng = 0
88827       **   if( idx(0) != regPrev(0) ) goto chng_addr_0
88828       **   regChng = 1
88829       **   if( idx(1) != regPrev(1) ) goto chng_addr_1
88830       **   ...
88831       **   regChng = N
88832       **   goto endDistinctTest
88833       */
88834       sqlite3VdbeAddOp0(v, OP_Goto);
88835       addrNextRow = sqlite3VdbeCurrentAddr(v);
88836       if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
88837         /* For a single-column UNIQUE index, once we have found a non-NULL
88838         ** row, we know that all the rest will be distinct, so skip 
88839         ** subsequent distinctness tests. */
88840         sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
88841         VdbeCoverage(v);
88842       }
88843       for(i=0; i<nColTest; i++){
88844         char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
88845         sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
88846         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
88847         aGotoChng[i] = 
88848         sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
88849         sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
88850         VdbeCoverage(v);
88851       }
88852       sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
88853       sqlite3VdbeAddOp2(v, OP_Goto, 0, endDistinctTest);
88854   
88855   
88856       /*
88857       **  chng_addr_0:
88858       **   regPrev(0) = idx(0)
88859       **  chng_addr_1:
88860       **   regPrev(1) = idx(1)
88861       **  ...
88862       */
88863       sqlite3VdbeJumpHere(v, addrNextRow-1);
88864       for(i=0; i<nColTest; i++){
88865         sqlite3VdbeJumpHere(v, aGotoChng[i]);
88866         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
88867       }
88868       sqlite3VdbeResolveLabel(v, endDistinctTest);
88869       sqlite3DbFree(db, aGotoChng);
88870     }
88871   
88872     /*
88873     **  chng_addr_N:
88874     **   regRowid = idx(rowid)            // STAT34 only
88875     **   stat_push(P, regChng, regRowid)  // 3rd parameter STAT34 only
88876     **   Next csr
88877     **   if !eof(csr) goto next_row;
88878     */
88879 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88880     assert( regRowid==(regStat4+2) );
88881     if( HasRowid(pTab) ){
88882       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
88883     }else{
88884       Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
88885       int j, k, regKey;
88886       regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
88887       for(j=0; j<pPk->nKeyCol; j++){
88888         k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
88889         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
88890         VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
88891       }
88892       sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
88893       sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
88894     }
88895 #endif
88896     assert( regChng==(regStat4+1) );
88897     sqlite3VdbeAddOp3(v, OP_Function, 1, regStat4, regTemp);
88898     sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
88899     sqlite3VdbeChangeP5(v, 2+IsStat34);
88900     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
88901
88902     /* Add the entry to the stat1 table. */
88903     callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
88904     assert( "BBB"[0]==SQLITE_AFF_TEXT );
88905     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
88906     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
88907     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
88908     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
88909
88910     /* Add the entries to the stat3 or stat4 table. */
88911 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
88912     {
88913       int regEq = regStat1;
88914       int regLt = regStat1+1;
88915       int regDLt = regStat1+2;
88916       int regSample = regStat1+3;
88917       int regCol = regStat1+4;
88918       int regSampleRowid = regCol + nCol;
88919       int addrNext;
88920       int addrIsNull;
88921       u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
88922
88923       pParse->nMem = MAX(pParse->nMem, regCol+nCol);
88924
88925       addrNext = sqlite3VdbeCurrentAddr(v);
88926       callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
88927       addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
88928       VdbeCoverage(v);
88929       callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
88930       callStatGet(v, regStat4, STAT_GET_NLT, regLt);
88931       callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
88932       sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
88933       /* We know that the regSampleRowid row exists because it was read by
88934       ** the previous loop.  Thus the not-found jump of seekOp will never
88935       ** be taken */
88936       VdbeCoverageNeverTaken(v);
88937 #ifdef SQLITE_ENABLE_STAT3
88938       sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, 
88939                                       pIdx->aiColumn[0], regSample);
88940 #else
88941       for(i=0; i<nCol; i++){
88942         i16 iCol = pIdx->aiColumn[i];
88943         sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i);
88944       }
88945       sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
88946 #endif
88947       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
88948       sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
88949       sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
88950       sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
88951       sqlite3VdbeJumpHere(v, addrIsNull);
88952     }
88953 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
88954
88955     /* End of analysis */
88956     sqlite3VdbeJumpHere(v, addrRewind);
88957   }
88958
88959
88960   /* Create a single sqlite_stat1 entry containing NULL as the index
88961   ** name and the row count as the content.
88962   */
88963   if( pOnlyIdx==0 && needTableCnt ){
88964     VdbeComment((v, "%s", pTab->zName));
88965     sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
88966     jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
88967     sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
88968     assert( "BBB"[0]==SQLITE_AFF_TEXT );
88969     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
88970     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
88971     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
88972     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
88973     sqlite3VdbeJumpHere(v, jZeroRows);
88974   }
88975 }
88976
88977
88978 /*
88979 ** Generate code that will cause the most recent index analysis to
88980 ** be loaded into internal hash tables where is can be used.
88981 */
88982 static void loadAnalysis(Parse *pParse, int iDb){
88983   Vdbe *v = sqlite3GetVdbe(pParse);
88984   if( v ){
88985     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
88986   }
88987 }
88988
88989 /*
88990 ** Generate code that will do an analysis of an entire database
88991 */
88992 static void analyzeDatabase(Parse *pParse, int iDb){
88993   sqlite3 *db = pParse->db;
88994   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
88995   HashElem *k;
88996   int iStatCur;
88997   int iMem;
88998   int iTab;
88999
89000   sqlite3BeginWriteOperation(pParse, 0, iDb);
89001   iStatCur = pParse->nTab;
89002   pParse->nTab += 3;
89003   openStatTable(pParse, iDb, iStatCur, 0, 0);
89004   iMem = pParse->nMem+1;
89005   iTab = pParse->nTab;
89006   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
89007   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
89008     Table *pTab = (Table*)sqliteHashData(k);
89009     analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
89010   }
89011   loadAnalysis(pParse, iDb);
89012 }
89013
89014 /*
89015 ** Generate code that will do an analysis of a single table in
89016 ** a database.  If pOnlyIdx is not NULL then it is a single index
89017 ** in pTab that should be analyzed.
89018 */
89019 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
89020   int iDb;
89021   int iStatCur;
89022
89023   assert( pTab!=0 );
89024   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
89025   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
89026   sqlite3BeginWriteOperation(pParse, 0, iDb);
89027   iStatCur = pParse->nTab;
89028   pParse->nTab += 3;
89029   if( pOnlyIdx ){
89030     openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
89031   }else{
89032     openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
89033   }
89034   analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
89035   loadAnalysis(pParse, iDb);
89036 }
89037
89038 /*
89039 ** Generate code for the ANALYZE command.  The parser calls this routine
89040 ** when it recognizes an ANALYZE command.
89041 **
89042 **        ANALYZE                            -- 1
89043 **        ANALYZE  <database>                -- 2
89044 **        ANALYZE  ?<database>.?<tablename>  -- 3
89045 **
89046 ** Form 1 causes all indices in all attached databases to be analyzed.
89047 ** Form 2 analyzes all indices the single database named.
89048 ** Form 3 analyzes all indices associated with the named table.
89049 */
89050 SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
89051   sqlite3 *db = pParse->db;
89052   int iDb;
89053   int i;
89054   char *z, *zDb;
89055   Table *pTab;
89056   Index *pIdx;
89057   Token *pTableName;
89058   Vdbe *v;
89059
89060   /* Read the database schema. If an error occurs, leave an error message
89061   ** and code in pParse and return NULL. */
89062   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
89063   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
89064     return;
89065   }
89066
89067   assert( pName2!=0 || pName1==0 );
89068   if( pName1==0 ){
89069     /* Form 1:  Analyze everything */
89070     for(i=0; i<db->nDb; i++){
89071       if( i==1 ) continue;  /* Do not analyze the TEMP database */
89072       analyzeDatabase(pParse, i);
89073     }
89074   }else if( pName2->n==0 ){
89075     /* Form 2:  Analyze the database or table named */
89076     iDb = sqlite3FindDb(db, pName1);
89077     if( iDb>=0 ){
89078       analyzeDatabase(pParse, iDb);
89079     }else{
89080       z = sqlite3NameFromToken(db, pName1);
89081       if( z ){
89082         if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
89083           analyzeTable(pParse, pIdx->pTable, pIdx);
89084         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
89085           analyzeTable(pParse, pTab, 0);
89086         }
89087         sqlite3DbFree(db, z);
89088       }
89089     }
89090   }else{
89091     /* Form 3: Analyze the fully qualified table name */
89092     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
89093     if( iDb>=0 ){
89094       zDb = db->aDb[iDb].zName;
89095       z = sqlite3NameFromToken(db, pTableName);
89096       if( z ){
89097         if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
89098           analyzeTable(pParse, pIdx->pTable, pIdx);
89099         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
89100           analyzeTable(pParse, pTab, 0);
89101         }
89102         sqlite3DbFree(db, z);
89103       }
89104     }   
89105   }
89106   v = sqlite3GetVdbe(pParse);
89107   if( v ) sqlite3VdbeAddOp0(v, OP_Expire);
89108 }
89109
89110 /*
89111 ** Used to pass information from the analyzer reader through to the
89112 ** callback routine.
89113 */
89114 typedef struct analysisInfo analysisInfo;
89115 struct analysisInfo {
89116   sqlite3 *db;
89117   const char *zDatabase;
89118 };
89119
89120 /*
89121 ** The first argument points to a nul-terminated string containing a
89122 ** list of space separated integers. Read the first nOut of these into
89123 ** the array aOut[].
89124 */
89125 static void decodeIntArray(
89126   char *zIntArray,       /* String containing int array to decode */
89127   int nOut,              /* Number of slots in aOut[] */
89128   tRowcnt *aOut,         /* Store integers here */
89129   LogEst *aLog,          /* Or, if aOut==0, here */
89130   Index *pIndex          /* Handle extra flags for this index, if not NULL */
89131 ){
89132   char *z = zIntArray;
89133   int c;
89134   int i;
89135   tRowcnt v;
89136
89137 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
89138   if( z==0 ) z = "";
89139 #else
89140   assert( z!=0 );
89141 #endif
89142   for(i=0; *z && i<nOut; i++){
89143     v = 0;
89144     while( (c=z[0])>='0' && c<='9' ){
89145       v = v*10 + c - '0';
89146       z++;
89147     }
89148 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
89149     if( aOut ) aOut[i] = v;
89150     if( aLog ) aLog[i] = sqlite3LogEst(v);
89151 #else
89152     assert( aOut==0 );
89153     UNUSED_PARAMETER(aOut);
89154     assert( aLog!=0 );
89155     aLog[i] = sqlite3LogEst(v);
89156 #endif
89157     if( *z==' ' ) z++;
89158   }
89159 #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
89160   assert( pIndex!=0 ); {
89161 #else
89162   if( pIndex ){
89163 #endif
89164     pIndex->bUnordered = 0;
89165     pIndex->noSkipScan = 0;
89166     while( z[0] ){
89167       if( sqlite3_strglob("unordered*", z)==0 ){
89168         pIndex->bUnordered = 1;
89169       }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
89170         pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
89171       }else if( sqlite3_strglob("noskipscan*", z)==0 ){
89172         pIndex->noSkipScan = 1;
89173       }
89174 #ifdef SQLITE_ENABLE_COSTMULT
89175       else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
89176         pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
89177       }
89178 #endif
89179       while( z[0]!=0 && z[0]!=' ' ) z++;
89180       while( z[0]==' ' ) z++;
89181     }
89182   }
89183 }
89184
89185 /*
89186 ** This callback is invoked once for each index when reading the
89187 ** sqlite_stat1 table.  
89188 **
89189 **     argv[0] = name of the table
89190 **     argv[1] = name of the index (might be NULL)
89191 **     argv[2] = results of analysis - on integer for each column
89192 **
89193 ** Entries for which argv[1]==NULL simply record the number of rows in
89194 ** the table.
89195 */
89196 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
89197   analysisInfo *pInfo = (analysisInfo*)pData;
89198   Index *pIndex;
89199   Table *pTable;
89200   const char *z;
89201
89202   assert( argc==3 );
89203   UNUSED_PARAMETER2(NotUsed, argc);
89204
89205   if( argv==0 || argv[0]==0 || argv[2]==0 ){
89206     return 0;
89207   }
89208   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
89209   if( pTable==0 ){
89210     return 0;
89211   }
89212   if( argv[1]==0 ){
89213     pIndex = 0;
89214   }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
89215     pIndex = sqlite3PrimaryKeyIndex(pTable);
89216   }else{
89217     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
89218   }
89219   z = argv[2];
89220
89221   if( pIndex ){
89222     int nCol = pIndex->nKeyCol+1;
89223 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
89224     tRowcnt * const aiRowEst = pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(
89225         sizeof(tRowcnt) * nCol
89226     );
89227     if( aiRowEst==0 ) pInfo->db->mallocFailed = 1;
89228 #else
89229     tRowcnt * const aiRowEst = 0;
89230 #endif
89231     pIndex->bUnordered = 0;
89232     decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
89233     if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
89234   }else{
89235     Index fakeIdx;
89236     fakeIdx.szIdxRow = pTable->szTabRow;
89237 #ifdef SQLITE_ENABLE_COSTMULT
89238     fakeIdx.pTable = pTable;
89239 #endif
89240     decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
89241     pTable->szTabRow = fakeIdx.szIdxRow;
89242   }
89243
89244   return 0;
89245 }
89246
89247 /*
89248 ** If the Index.aSample variable is not NULL, delete the aSample[] array
89249 ** and its contents.
89250 */
89251 SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
89252 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
89253   if( pIdx->aSample ){
89254     int j;
89255     for(j=0; j<pIdx->nSample; j++){
89256       IndexSample *p = &pIdx->aSample[j];
89257       sqlite3DbFree(db, p->p);
89258     }
89259     sqlite3DbFree(db, pIdx->aSample);
89260   }
89261   if( db && db->pnBytesFreed==0 ){
89262     pIdx->nSample = 0;
89263     pIdx->aSample = 0;
89264   }
89265 #else
89266   UNUSED_PARAMETER(db);
89267   UNUSED_PARAMETER(pIdx);
89268 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
89269 }
89270
89271 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
89272 /*
89273 ** Populate the pIdx->aAvgEq[] array based on the samples currently
89274 ** stored in pIdx->aSample[]. 
89275 */
89276 static void initAvgEq(Index *pIdx){
89277   if( pIdx ){
89278     IndexSample *aSample = pIdx->aSample;
89279     IndexSample *pFinal = &aSample[pIdx->nSample-1];
89280     int iCol;
89281     int nCol = 1;
89282     if( pIdx->nSampleCol>1 ){
89283       /* If this is stat4 data, then calculate aAvgEq[] values for all
89284       ** sample columns except the last. The last is always set to 1, as
89285       ** once the trailing PK fields are considered all index keys are
89286       ** unique.  */
89287       nCol = pIdx->nSampleCol-1;
89288       pIdx->aAvgEq[nCol] = 1;
89289     }
89290     for(iCol=0; iCol<nCol; iCol++){
89291       int nSample = pIdx->nSample;
89292       int i;                    /* Used to iterate through samples */
89293       tRowcnt sumEq = 0;        /* Sum of the nEq values */
89294       tRowcnt avgEq = 0;
89295       tRowcnt nRow;             /* Number of rows in index */
89296       i64 nSum100 = 0;          /* Number of terms contributing to sumEq */
89297       i64 nDist100;             /* Number of distinct values in index */
89298
89299       if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
89300         nRow = pFinal->anLt[iCol];
89301         nDist100 = (i64)100 * pFinal->anDLt[iCol];
89302         nSample--;
89303       }else{
89304         nRow = pIdx->aiRowEst[0];
89305         nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
89306       }
89307       pIdx->nRowEst0 = nRow;
89308
89309       /* Set nSum to the number of distinct (iCol+1) field prefixes that
89310       ** occur in the stat4 table for this index. Set sumEq to the sum of 
89311       ** the nEq values for column iCol for the same set (adding the value 
89312       ** only once where there exist duplicate prefixes).  */
89313       for(i=0; i<nSample; i++){
89314         if( i==(pIdx->nSample-1)
89315          || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] 
89316         ){
89317           sumEq += aSample[i].anEq[iCol];
89318           nSum100 += 100;
89319         }
89320       }
89321
89322       if( nDist100>nSum100 ){
89323         avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
89324       }
89325       if( avgEq==0 ) avgEq = 1;
89326       pIdx->aAvgEq[iCol] = avgEq;
89327     }
89328   }
89329 }
89330
89331 /*
89332 ** Look up an index by name.  Or, if the name of a WITHOUT ROWID table
89333 ** is supplied instead, find the PRIMARY KEY index for that table.
89334 */
89335 static Index *findIndexOrPrimaryKey(
89336   sqlite3 *db,
89337   const char *zName,
89338   const char *zDb
89339 ){
89340   Index *pIdx = sqlite3FindIndex(db, zName, zDb);
89341   if( pIdx==0 ){
89342     Table *pTab = sqlite3FindTable(db, zName, zDb);
89343     if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
89344   }
89345   return pIdx;
89346 }
89347
89348 /*
89349 ** Load the content from either the sqlite_stat4 or sqlite_stat3 table 
89350 ** into the relevant Index.aSample[] arrays.
89351 **
89352 ** Arguments zSql1 and zSql2 must point to SQL statements that return
89353 ** data equivalent to the following (statements are different for stat3,
89354 ** see the caller of this function for details):
89355 **
89356 **    zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
89357 **    zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
89358 **
89359 ** where %Q is replaced with the database name before the SQL is executed.
89360 */
89361 static int loadStatTbl(
89362   sqlite3 *db,                  /* Database handle */
89363   int bStat3,                   /* Assume single column records only */
89364   const char *zSql1,            /* SQL statement 1 (see above) */
89365   const char *zSql2,            /* SQL statement 2 (see above) */
89366   const char *zDb               /* Database name (e.g. "main") */
89367 ){
89368   int rc;                       /* Result codes from subroutines */
89369   sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
89370   char *zSql;                   /* Text of the SQL statement */
89371   Index *pPrevIdx = 0;          /* Previous index in the loop */
89372   IndexSample *pSample;         /* A slot in pIdx->aSample[] */
89373
89374   assert( db->lookaside.bEnabled==0 );
89375   zSql = sqlite3MPrintf(db, zSql1, zDb);
89376   if( !zSql ){
89377     return SQLITE_NOMEM;
89378   }
89379   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
89380   sqlite3DbFree(db, zSql);
89381   if( rc ) return rc;
89382
89383   while( sqlite3_step(pStmt)==SQLITE_ROW ){
89384     int nIdxCol = 1;              /* Number of columns in stat4 records */
89385
89386     char *zIndex;   /* Index name */
89387     Index *pIdx;    /* Pointer to the index object */
89388     int nSample;    /* Number of samples */
89389     int nByte;      /* Bytes of space required */
89390     int i;          /* Bytes of space required */
89391     tRowcnt *pSpace;
89392
89393     zIndex = (char *)sqlite3_column_text(pStmt, 0);
89394     if( zIndex==0 ) continue;
89395     nSample = sqlite3_column_int(pStmt, 1);
89396     pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
89397     assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
89398     /* Index.nSample is non-zero at this point if data has already been
89399     ** loaded from the stat4 table. In this case ignore stat3 data.  */
89400     if( pIdx==0 || pIdx->nSample ) continue;
89401     if( bStat3==0 ){
89402       assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
89403       if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
89404         nIdxCol = pIdx->nKeyCol;
89405       }else{
89406         nIdxCol = pIdx->nColumn;
89407       }
89408     }
89409     pIdx->nSampleCol = nIdxCol;
89410     nByte = sizeof(IndexSample) * nSample;
89411     nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
89412     nByte += nIdxCol * sizeof(tRowcnt);     /* Space for Index.aAvgEq[] */
89413
89414     pIdx->aSample = sqlite3DbMallocZero(db, nByte);
89415     if( pIdx->aSample==0 ){
89416       sqlite3_finalize(pStmt);
89417       return SQLITE_NOMEM;
89418     }
89419     pSpace = (tRowcnt*)&pIdx->aSample[nSample];
89420     pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
89421     for(i=0; i<nSample; i++){
89422       pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
89423       pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
89424       pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
89425     }
89426     assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
89427   }
89428   rc = sqlite3_finalize(pStmt);
89429   if( rc ) return rc;
89430
89431   zSql = sqlite3MPrintf(db, zSql2, zDb);
89432   if( !zSql ){
89433     return SQLITE_NOMEM;
89434   }
89435   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
89436   sqlite3DbFree(db, zSql);
89437   if( rc ) return rc;
89438
89439   while( sqlite3_step(pStmt)==SQLITE_ROW ){
89440     char *zIndex;                 /* Index name */
89441     Index *pIdx;                  /* Pointer to the index object */
89442     int nCol = 1;                 /* Number of columns in index */
89443
89444     zIndex = (char *)sqlite3_column_text(pStmt, 0);
89445     if( zIndex==0 ) continue;
89446     pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
89447     if( pIdx==0 ) continue;
89448     /* This next condition is true if data has already been loaded from 
89449     ** the sqlite_stat4 table. In this case ignore stat3 data.  */
89450     nCol = pIdx->nSampleCol;
89451     if( bStat3 && nCol>1 ) continue;
89452     if( pIdx!=pPrevIdx ){
89453       initAvgEq(pPrevIdx);
89454       pPrevIdx = pIdx;
89455     }
89456     pSample = &pIdx->aSample[pIdx->nSample];
89457     decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
89458     decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
89459     decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
89460
89461     /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
89462     ** This is in case the sample record is corrupted. In that case, the
89463     ** sqlite3VdbeRecordCompare() may read up to two varints past the
89464     ** end of the allocated buffer before it realizes it is dealing with
89465     ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
89466     ** a buffer overread.  */
89467     pSample->n = sqlite3_column_bytes(pStmt, 4);
89468     pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
89469     if( pSample->p==0 ){
89470       sqlite3_finalize(pStmt);
89471       return SQLITE_NOMEM;
89472     }
89473     memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
89474     pIdx->nSample++;
89475   }
89476   rc = sqlite3_finalize(pStmt);
89477   if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
89478   return rc;
89479 }
89480
89481 /*
89482 ** Load content from the sqlite_stat4 and sqlite_stat3 tables into 
89483 ** the Index.aSample[] arrays of all indices.
89484 */
89485 static int loadStat4(sqlite3 *db, const char *zDb){
89486   int rc = SQLITE_OK;             /* Result codes from subroutines */
89487
89488   assert( db->lookaside.bEnabled==0 );
89489   if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
89490     rc = loadStatTbl(db, 0,
89491       "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx", 
89492       "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
89493       zDb
89494     );
89495   }
89496
89497   if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
89498     rc = loadStatTbl(db, 1,
89499       "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx", 
89500       "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
89501       zDb
89502     );
89503   }
89504
89505   return rc;
89506 }
89507 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
89508
89509 /*
89510 ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
89511 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
89512 ** arrays. The contents of sqlite_stat3/4 are used to populate the
89513 ** Index.aSample[] arrays.
89514 **
89515 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
89516 ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined 
89517 ** during compilation and the sqlite_stat3/4 table is present, no data is 
89518 ** read from it.
89519 **
89520 ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the 
89521 ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
89522 ** returned. However, in this case, data is read from the sqlite_stat1
89523 ** table (if it is present) before returning.
89524 **
89525 ** If an OOM error occurs, this function always sets db->mallocFailed.
89526 ** This means if the caller does not care about other errors, the return
89527 ** code may be ignored.
89528 */
89529 SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
89530   analysisInfo sInfo;
89531   HashElem *i;
89532   char *zSql;
89533   int rc;
89534
89535   assert( iDb>=0 && iDb<db->nDb );
89536   assert( db->aDb[iDb].pBt!=0 );
89537
89538   /* Clear any prior statistics */
89539   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
89540   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
89541     Index *pIdx = sqliteHashData(i);
89542     sqlite3DefaultRowEst(pIdx);
89543 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
89544     sqlite3DeleteIndexSamples(db, pIdx);
89545     pIdx->aSample = 0;
89546 #endif
89547   }
89548
89549   /* Check to make sure the sqlite_stat1 table exists */
89550   sInfo.db = db;
89551   sInfo.zDatabase = db->aDb[iDb].zName;
89552   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
89553     return SQLITE_ERROR;
89554   }
89555
89556   /* Load new statistics out of the sqlite_stat1 table */
89557   zSql = sqlite3MPrintf(db, 
89558       "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
89559   if( zSql==0 ){
89560     rc = SQLITE_NOMEM;
89561   }else{
89562     rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
89563     sqlite3DbFree(db, zSql);
89564   }
89565
89566
89567   /* Load the statistics from the sqlite_stat4 table. */
89568 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
89569   if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
89570     int lookasideEnabled = db->lookaside.bEnabled;
89571     db->lookaside.bEnabled = 0;
89572     rc = loadStat4(db, sInfo.zDatabase);
89573     db->lookaside.bEnabled = lookasideEnabled;
89574   }
89575   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
89576     Index *pIdx = sqliteHashData(i);
89577     sqlite3_free(pIdx->aiRowEst);
89578     pIdx->aiRowEst = 0;
89579   }
89580 #endif
89581
89582   if( rc==SQLITE_NOMEM ){
89583     db->mallocFailed = 1;
89584   }
89585   return rc;
89586 }
89587
89588
89589 #endif /* SQLITE_OMIT_ANALYZE */
89590
89591 /************** End of analyze.c *********************************************/
89592 /************** Begin file attach.c ******************************************/
89593 /*
89594 ** 2003 April 6
89595 **
89596 ** The author disclaims copyright to this source code.  In place of
89597 ** a legal notice, here is a blessing:
89598 **
89599 **    May you do good and not evil.
89600 **    May you find forgiveness for yourself and forgive others.
89601 **    May you share freely, never taking more than you give.
89602 **
89603 *************************************************************************
89604 ** This file contains code used to implement the ATTACH and DETACH commands.
89605 */
89606
89607 #ifndef SQLITE_OMIT_ATTACH
89608 /*
89609 ** Resolve an expression that was part of an ATTACH or DETACH statement. This
89610 ** is slightly different from resolving a normal SQL expression, because simple
89611 ** identifiers are treated as strings, not possible column names or aliases.
89612 **
89613 ** i.e. if the parser sees:
89614 **
89615 **     ATTACH DATABASE abc AS def
89616 **
89617 ** it treats the two expressions as literal strings 'abc' and 'def' instead of
89618 ** looking for columns of the same name.
89619 **
89620 ** This only applies to the root node of pExpr, so the statement:
89621 **
89622 **     ATTACH DATABASE abc||def AS 'db2'
89623 **
89624 ** will fail because neither abc or def can be resolved.
89625 */
89626 static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
89627 {
89628   int rc = SQLITE_OK;
89629   if( pExpr ){
89630     if( pExpr->op!=TK_ID ){
89631       rc = sqlite3ResolveExprNames(pName, pExpr);
89632     }else{
89633       pExpr->op = TK_STRING;
89634     }
89635   }
89636   return rc;
89637 }
89638
89639 /*
89640 ** An SQL user-function registered to do the work of an ATTACH statement. The
89641 ** three arguments to the function come directly from an attach statement:
89642 **
89643 **     ATTACH DATABASE x AS y KEY z
89644 **
89645 **     SELECT sqlite_attach(x, y, z)
89646 **
89647 ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
89648 ** third argument.
89649 */
89650 static void attachFunc(
89651   sqlite3_context *context,
89652   int NotUsed,
89653   sqlite3_value **argv
89654 ){
89655   int i;
89656   int rc = 0;
89657   sqlite3 *db = sqlite3_context_db_handle(context);
89658   const char *zName;
89659   const char *zFile;
89660   char *zPath = 0;
89661   char *zErr = 0;
89662   unsigned int flags;
89663   Db *aNew;
89664   char *zErrDyn = 0;
89665   sqlite3_vfs *pVfs;
89666
89667   UNUSED_PARAMETER(NotUsed);
89668
89669   zFile = (const char *)sqlite3_value_text(argv[0]);
89670   zName = (const char *)sqlite3_value_text(argv[1]);
89671   if( zFile==0 ) zFile = "";
89672   if( zName==0 ) zName = "";
89673
89674   /* Check for the following errors:
89675   **
89676   **     * Too many attached databases,
89677   **     * Transaction currently open
89678   **     * Specified database name already being used.
89679   */
89680   if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
89681     zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d", 
89682       db->aLimit[SQLITE_LIMIT_ATTACHED]
89683     );
89684     goto attach_error;
89685   }
89686   if( !db->autoCommit ){
89687     zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
89688     goto attach_error;
89689   }
89690   for(i=0; i<db->nDb; i++){
89691     char *z = db->aDb[i].zName;
89692     assert( z && zName );
89693     if( sqlite3StrICmp(z, zName)==0 ){
89694       zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
89695       goto attach_error;
89696     }
89697   }
89698
89699   /* Allocate the new entry in the db->aDb[] array and initialize the schema
89700   ** hash tables.
89701   */
89702   if( db->aDb==db->aDbStatic ){
89703     aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
89704     if( aNew==0 ) return;
89705     memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
89706   }else{
89707     aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
89708     if( aNew==0 ) return;
89709   }
89710   db->aDb = aNew;
89711   aNew = &db->aDb[db->nDb];
89712   memset(aNew, 0, sizeof(*aNew));
89713
89714   /* Open the database file. If the btree is successfully opened, use
89715   ** it to obtain the database schema. At this point the schema may
89716   ** or may not be initialized.
89717   */
89718   flags = db->openFlags;
89719   rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
89720   if( rc!=SQLITE_OK ){
89721     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
89722     sqlite3_result_error(context, zErr, -1);
89723     sqlite3_free(zErr);
89724     return;
89725   }
89726   assert( pVfs );
89727   flags |= SQLITE_OPEN_MAIN_DB;
89728   rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
89729   sqlite3_free( zPath );
89730   db->nDb++;
89731   if( rc==SQLITE_CONSTRAINT ){
89732     rc = SQLITE_ERROR;
89733     zErrDyn = sqlite3MPrintf(db, "database is already attached");
89734   }else if( rc==SQLITE_OK ){
89735     Pager *pPager;
89736     aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
89737     if( !aNew->pSchema ){
89738       rc = SQLITE_NOMEM;
89739     }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
89740       zErrDyn = sqlite3MPrintf(db, 
89741         "attached databases must use the same text encoding as main database");
89742       rc = SQLITE_ERROR;
89743     }
89744     sqlite3BtreeEnter(aNew->pBt);
89745     pPager = sqlite3BtreePager(aNew->pBt);
89746     sqlite3PagerLockingMode(pPager, db->dfltLockMode);
89747     sqlite3BtreeSecureDelete(aNew->pBt,
89748                              sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
89749 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
89750     sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK));
89751 #endif
89752     sqlite3BtreeLeave(aNew->pBt);
89753   }
89754   aNew->safety_level = 3;
89755   aNew->zName = sqlite3DbStrDup(db, zName);
89756   if( rc==SQLITE_OK && aNew->zName==0 ){
89757     rc = SQLITE_NOMEM;
89758   }
89759
89760
89761 #ifdef SQLITE_HAS_CODEC
89762   if( rc==SQLITE_OK ){
89763     extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
89764     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
89765     int nKey;
89766     char *zKey;
89767     int t = sqlite3_value_type(argv[2]);
89768     switch( t ){
89769       case SQLITE_INTEGER:
89770       case SQLITE_FLOAT:
89771         zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
89772         rc = SQLITE_ERROR;
89773         break;
89774         
89775       case SQLITE_TEXT:
89776       case SQLITE_BLOB:
89777         nKey = sqlite3_value_bytes(argv[2]);
89778         zKey = (char *)sqlite3_value_blob(argv[2]);
89779         rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
89780         break;
89781
89782       case SQLITE_NULL:
89783         /* No key specified.  Use the key from the main database */
89784         sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
89785         if( nKey>0 || sqlite3BtreeGetOptimalReserve(db->aDb[0].pBt)>0 ){
89786           rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
89787         }
89788         break;
89789     }
89790   }
89791 #endif
89792
89793   /* If the file was opened successfully, read the schema for the new database.
89794   ** If this fails, or if opening the file failed, then close the file and 
89795   ** remove the entry from the db->aDb[] array. i.e. put everything back the way
89796   ** we found it.
89797   */
89798   if( rc==SQLITE_OK ){
89799     sqlite3BtreeEnterAll(db);
89800     rc = sqlite3Init(db, &zErrDyn);
89801     sqlite3BtreeLeaveAll(db);
89802   }
89803 #ifdef SQLITE_USER_AUTHENTICATION
89804   if( rc==SQLITE_OK ){
89805     u8 newAuth = 0;
89806     rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
89807     if( newAuth<db->auth.authLevel ){
89808       rc = SQLITE_AUTH_USER;
89809     }
89810   }
89811 #endif
89812   if( rc ){
89813     int iDb = db->nDb - 1;
89814     assert( iDb>=2 );
89815     if( db->aDb[iDb].pBt ){
89816       sqlite3BtreeClose(db->aDb[iDb].pBt);
89817       db->aDb[iDb].pBt = 0;
89818       db->aDb[iDb].pSchema = 0;
89819     }
89820     sqlite3ResetAllSchemasOfConnection(db);
89821     db->nDb = iDb;
89822     if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
89823       db->mallocFailed = 1;
89824       sqlite3DbFree(db, zErrDyn);
89825       zErrDyn = sqlite3MPrintf(db, "out of memory");
89826     }else if( zErrDyn==0 ){
89827       zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
89828     }
89829     goto attach_error;
89830   }
89831   
89832   return;
89833
89834 attach_error:
89835   /* Return an error if we get here */
89836   if( zErrDyn ){
89837     sqlite3_result_error(context, zErrDyn, -1);
89838     sqlite3DbFree(db, zErrDyn);
89839   }
89840   if( rc ) sqlite3_result_error_code(context, rc);
89841 }
89842
89843 /*
89844 ** An SQL user-function registered to do the work of an DETACH statement. The
89845 ** three arguments to the function come directly from a detach statement:
89846 **
89847 **     DETACH DATABASE x
89848 **
89849 **     SELECT sqlite_detach(x)
89850 */
89851 static void detachFunc(
89852   sqlite3_context *context,
89853   int NotUsed,
89854   sqlite3_value **argv
89855 ){
89856   const char *zName = (const char *)sqlite3_value_text(argv[0]);
89857   sqlite3 *db = sqlite3_context_db_handle(context);
89858   int i;
89859   Db *pDb = 0;
89860   char zErr[128];
89861
89862   UNUSED_PARAMETER(NotUsed);
89863
89864   if( zName==0 ) zName = "";
89865   for(i=0; i<db->nDb; i++){
89866     pDb = &db->aDb[i];
89867     if( pDb->pBt==0 ) continue;
89868     if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
89869   }
89870
89871   if( i>=db->nDb ){
89872     sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
89873     goto detach_error;
89874   }
89875   if( i<2 ){
89876     sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
89877     goto detach_error;
89878   }
89879   if( !db->autoCommit ){
89880     sqlite3_snprintf(sizeof(zErr), zErr,
89881                      "cannot DETACH database within transaction");
89882     goto detach_error;
89883   }
89884   if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
89885     sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
89886     goto detach_error;
89887   }
89888
89889   sqlite3BtreeClose(pDb->pBt);
89890   pDb->pBt = 0;
89891   pDb->pSchema = 0;
89892   sqlite3ResetAllSchemasOfConnection(db);
89893   return;
89894
89895 detach_error:
89896   sqlite3_result_error(context, zErr, -1);
89897 }
89898
89899 /*
89900 ** This procedure generates VDBE code for a single invocation of either the
89901 ** sqlite_detach() or sqlite_attach() SQL user functions.
89902 */
89903 static void codeAttach(
89904   Parse *pParse,       /* The parser context */
89905   int type,            /* Either SQLITE_ATTACH or SQLITE_DETACH */
89906   FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
89907   Expr *pAuthArg,      /* Expression to pass to authorization callback */
89908   Expr *pFilename,     /* Name of database file */
89909   Expr *pDbname,       /* Name of the database to use internally */
89910   Expr *pKey           /* Database key for encryption extension */
89911 ){
89912   int rc;
89913   NameContext sName;
89914   Vdbe *v;
89915   sqlite3* db = pParse->db;
89916   int regArgs;
89917
89918   memset(&sName, 0, sizeof(NameContext));
89919   sName.pParse = pParse;
89920
89921   if( 
89922       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
89923       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
89924       SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
89925   ){
89926     pParse->nErr++;
89927     goto attach_end;
89928   }
89929
89930 #ifndef SQLITE_OMIT_AUTHORIZATION
89931   if( pAuthArg ){
89932     char *zAuthArg;
89933     if( pAuthArg->op==TK_STRING ){
89934       zAuthArg = pAuthArg->u.zToken;
89935     }else{
89936       zAuthArg = 0;
89937     }
89938     rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
89939     if(rc!=SQLITE_OK ){
89940       goto attach_end;
89941     }
89942   }
89943 #endif /* SQLITE_OMIT_AUTHORIZATION */
89944
89945
89946   v = sqlite3GetVdbe(pParse);
89947   regArgs = sqlite3GetTempRange(pParse, 4);
89948   sqlite3ExprCode(pParse, pFilename, regArgs);
89949   sqlite3ExprCode(pParse, pDbname, regArgs+1);
89950   sqlite3ExprCode(pParse, pKey, regArgs+2);
89951
89952   assert( v || db->mallocFailed );
89953   if( v ){
89954     sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
89955     assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
89956     sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
89957     sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
89958
89959     /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
89960     ** statement only). For DETACH, set it to false (expire all existing
89961     ** statements).
89962     */
89963     sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
89964   }
89965   
89966 attach_end:
89967   sqlite3ExprDelete(db, pFilename);
89968   sqlite3ExprDelete(db, pDbname);
89969   sqlite3ExprDelete(db, pKey);
89970 }
89971
89972 /*
89973 ** Called by the parser to compile a DETACH statement.
89974 **
89975 **     DETACH pDbname
89976 */
89977 SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
89978   static const FuncDef detach_func = {
89979     1,                /* nArg */
89980     SQLITE_UTF8,      /* funcFlags */
89981     0,                /* pUserData */
89982     0,                /* pNext */
89983     detachFunc,       /* xFunc */
89984     0,                /* xStep */
89985     0,                /* xFinalize */
89986     "sqlite_detach",  /* zName */
89987     0,                /* pHash */
89988     0                 /* pDestructor */
89989   };
89990   codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
89991 }
89992
89993 /*
89994 ** Called by the parser to compile an ATTACH statement.
89995 **
89996 **     ATTACH p AS pDbname KEY pKey
89997 */
89998 SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
89999   static const FuncDef attach_func = {
90000     3,                /* nArg */
90001     SQLITE_UTF8,      /* funcFlags */
90002     0,                /* pUserData */
90003     0,                /* pNext */
90004     attachFunc,       /* xFunc */
90005     0,                /* xStep */
90006     0,                /* xFinalize */
90007     "sqlite_attach",  /* zName */
90008     0,                /* pHash */
90009     0                 /* pDestructor */
90010   };
90011   codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
90012 }
90013 #endif /* SQLITE_OMIT_ATTACH */
90014
90015 /*
90016 ** Initialize a DbFixer structure.  This routine must be called prior
90017 ** to passing the structure to one of the sqliteFixAAAA() routines below.
90018 */
90019 SQLITE_PRIVATE void sqlite3FixInit(
90020   DbFixer *pFix,      /* The fixer to be initialized */
90021   Parse *pParse,      /* Error messages will be written here */
90022   int iDb,            /* This is the database that must be used */
90023   const char *zType,  /* "view", "trigger", or "index" */
90024   const Token *pName  /* Name of the view, trigger, or index */
90025 ){
90026   sqlite3 *db;
90027
90028   db = pParse->db;
90029   assert( db->nDb>iDb );
90030   pFix->pParse = pParse;
90031   pFix->zDb = db->aDb[iDb].zName;
90032   pFix->pSchema = db->aDb[iDb].pSchema;
90033   pFix->zType = zType;
90034   pFix->pName = pName;
90035   pFix->bVarOnly = (iDb==1);
90036 }
90037
90038 /*
90039 ** The following set of routines walk through the parse tree and assign
90040 ** a specific database to all table references where the database name
90041 ** was left unspecified in the original SQL statement.  The pFix structure
90042 ** must have been initialized by a prior call to sqlite3FixInit().
90043 **
90044 ** These routines are used to make sure that an index, trigger, or
90045 ** view in one database does not refer to objects in a different database.
90046 ** (Exception: indices, triggers, and views in the TEMP database are
90047 ** allowed to refer to anything.)  If a reference is explicitly made
90048 ** to an object in a different database, an error message is added to
90049 ** pParse->zErrMsg and these routines return non-zero.  If everything
90050 ** checks out, these routines return 0.
90051 */
90052 SQLITE_PRIVATE int sqlite3FixSrcList(
90053   DbFixer *pFix,       /* Context of the fixation */
90054   SrcList *pList       /* The Source list to check and modify */
90055 ){
90056   int i;
90057   const char *zDb;
90058   struct SrcList_item *pItem;
90059
90060   if( NEVER(pList==0) ) return 0;
90061   zDb = pFix->zDb;
90062   for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
90063     if( pFix->bVarOnly==0 ){
90064       if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
90065         sqlite3ErrorMsg(pFix->pParse,
90066             "%s %T cannot reference objects in database %s",
90067             pFix->zType, pFix->pName, pItem->zDatabase);
90068         return 1;
90069       }
90070       sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
90071       pItem->zDatabase = 0;
90072       pItem->pSchema = pFix->pSchema;
90073     }
90074 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
90075     if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
90076     if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
90077 #endif
90078   }
90079   return 0;
90080 }
90081 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
90082 SQLITE_PRIVATE int sqlite3FixSelect(
90083   DbFixer *pFix,       /* Context of the fixation */
90084   Select *pSelect      /* The SELECT statement to be fixed to one database */
90085 ){
90086   while( pSelect ){
90087     if( sqlite3FixExprList(pFix, pSelect->pEList) ){
90088       return 1;
90089     }
90090     if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
90091       return 1;
90092     }
90093     if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
90094       return 1;
90095     }
90096     if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
90097       return 1;
90098     }
90099     if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
90100       return 1;
90101     }
90102     if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
90103       return 1;
90104     }
90105     if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
90106       return 1;
90107     }
90108     if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
90109       return 1;
90110     }
90111     pSelect = pSelect->pPrior;
90112   }
90113   return 0;
90114 }
90115 SQLITE_PRIVATE int sqlite3FixExpr(
90116   DbFixer *pFix,     /* Context of the fixation */
90117   Expr *pExpr        /* The expression to be fixed to one database */
90118 ){
90119   while( pExpr ){
90120     if( pExpr->op==TK_VARIABLE ){
90121       if( pFix->pParse->db->init.busy ){
90122         pExpr->op = TK_NULL;
90123       }else{
90124         sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
90125         return 1;
90126       }
90127     }
90128     if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
90129     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
90130       if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
90131     }else{
90132       if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
90133     }
90134     if( sqlite3FixExpr(pFix, pExpr->pRight) ){
90135       return 1;
90136     }
90137     pExpr = pExpr->pLeft;
90138   }
90139   return 0;
90140 }
90141 SQLITE_PRIVATE int sqlite3FixExprList(
90142   DbFixer *pFix,     /* Context of the fixation */
90143   ExprList *pList    /* The expression to be fixed to one database */
90144 ){
90145   int i;
90146   struct ExprList_item *pItem;
90147   if( pList==0 ) return 0;
90148   for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
90149     if( sqlite3FixExpr(pFix, pItem->pExpr) ){
90150       return 1;
90151     }
90152   }
90153   return 0;
90154 }
90155 #endif
90156
90157 #ifndef SQLITE_OMIT_TRIGGER
90158 SQLITE_PRIVATE int sqlite3FixTriggerStep(
90159   DbFixer *pFix,     /* Context of the fixation */
90160   TriggerStep *pStep /* The trigger step be fixed to one database */
90161 ){
90162   while( pStep ){
90163     if( sqlite3FixSelect(pFix, pStep->pSelect) ){
90164       return 1;
90165     }
90166     if( sqlite3FixExpr(pFix, pStep->pWhere) ){
90167       return 1;
90168     }
90169     if( sqlite3FixExprList(pFix, pStep->pExprList) ){
90170       return 1;
90171     }
90172     pStep = pStep->pNext;
90173   }
90174   return 0;
90175 }
90176 #endif
90177
90178 /************** End of attach.c **********************************************/
90179 /************** Begin file auth.c ********************************************/
90180 /*
90181 ** 2003 January 11
90182 **
90183 ** The author disclaims copyright to this source code.  In place of
90184 ** a legal notice, here is a blessing:
90185 **
90186 **    May you do good and not evil.
90187 **    May you find forgiveness for yourself and forgive others.
90188 **    May you share freely, never taking more than you give.
90189 **
90190 *************************************************************************
90191 ** This file contains code used to implement the sqlite3_set_authorizer()
90192 ** API.  This facility is an optional feature of the library.  Embedded
90193 ** systems that do not need this facility may omit it by recompiling
90194 ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
90195 */
90196
90197 /*
90198 ** All of the code in this file may be omitted by defining a single
90199 ** macro.
90200 */
90201 #ifndef SQLITE_OMIT_AUTHORIZATION
90202
90203 /*
90204 ** Set or clear the access authorization function.
90205 **
90206 ** The access authorization function is be called during the compilation
90207 ** phase to verify that the user has read and/or write access permission on
90208 ** various fields of the database.  The first argument to the auth function
90209 ** is a copy of the 3rd argument to this routine.  The second argument
90210 ** to the auth function is one of these constants:
90211 **
90212 **       SQLITE_CREATE_INDEX
90213 **       SQLITE_CREATE_TABLE
90214 **       SQLITE_CREATE_TEMP_INDEX
90215 **       SQLITE_CREATE_TEMP_TABLE
90216 **       SQLITE_CREATE_TEMP_TRIGGER
90217 **       SQLITE_CREATE_TEMP_VIEW
90218 **       SQLITE_CREATE_TRIGGER
90219 **       SQLITE_CREATE_VIEW
90220 **       SQLITE_DELETE
90221 **       SQLITE_DROP_INDEX
90222 **       SQLITE_DROP_TABLE
90223 **       SQLITE_DROP_TEMP_INDEX
90224 **       SQLITE_DROP_TEMP_TABLE
90225 **       SQLITE_DROP_TEMP_TRIGGER
90226 **       SQLITE_DROP_TEMP_VIEW
90227 **       SQLITE_DROP_TRIGGER
90228 **       SQLITE_DROP_VIEW
90229 **       SQLITE_INSERT
90230 **       SQLITE_PRAGMA
90231 **       SQLITE_READ
90232 **       SQLITE_SELECT
90233 **       SQLITE_TRANSACTION
90234 **       SQLITE_UPDATE
90235 **
90236 ** The third and fourth arguments to the auth function are the name of
90237 ** the table and the column that are being accessed.  The auth function
90238 ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE.  If
90239 ** SQLITE_OK is returned, it means that access is allowed.  SQLITE_DENY
90240 ** means that the SQL statement will never-run - the sqlite3_exec() call
90241 ** will return with an error.  SQLITE_IGNORE means that the SQL statement
90242 ** should run but attempts to read the specified column will return NULL
90243 ** and attempts to write the column will be ignored.
90244 **
90245 ** Setting the auth function to NULL disables this hook.  The default
90246 ** setting of the auth function is NULL.
90247 */
90248 SQLITE_API int SQLITE_STDCALL sqlite3_set_authorizer(
90249   sqlite3 *db,
90250   int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
90251   void *pArg
90252 ){
90253 #ifdef SQLITE_ENABLE_API_ARMOR
90254   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
90255 #endif
90256   sqlite3_mutex_enter(db->mutex);
90257   db->xAuth = (sqlite3_xauth)xAuth;
90258   db->pAuthArg = pArg;
90259   sqlite3ExpirePreparedStatements(db);
90260   sqlite3_mutex_leave(db->mutex);
90261   return SQLITE_OK;
90262 }
90263
90264 /*
90265 ** Write an error message into pParse->zErrMsg that explains that the
90266 ** user-supplied authorization function returned an illegal value.
90267 */
90268 static void sqliteAuthBadReturnCode(Parse *pParse){
90269   sqlite3ErrorMsg(pParse, "authorizer malfunction");
90270   pParse->rc = SQLITE_ERROR;
90271 }
90272
90273 /*
90274 ** Invoke the authorization callback for permission to read column zCol from
90275 ** table zTab in database zDb. This function assumes that an authorization
90276 ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
90277 **
90278 ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
90279 ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
90280 ** is treated as SQLITE_DENY. In this case an error is left in pParse.
90281 */
90282 SQLITE_PRIVATE int sqlite3AuthReadCol(
90283   Parse *pParse,                  /* The parser context */
90284   const char *zTab,               /* Table name */
90285   const char *zCol,               /* Column name */
90286   int iDb                         /* Index of containing database. */
90287 ){
90288   sqlite3 *db = pParse->db;       /* Database handle */
90289   char *zDb = db->aDb[iDb].zName; /* Name of attached database */
90290   int rc;                         /* Auth callback return code */
90291
90292   rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
90293 #ifdef SQLITE_USER_AUTHENTICATION
90294                  ,db->auth.zAuthUser
90295 #endif
90296                 );
90297   if( rc==SQLITE_DENY ){
90298     if( db->nDb>2 || iDb!=0 ){
90299       sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
90300     }else{
90301       sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
90302     }
90303     pParse->rc = SQLITE_AUTH;
90304   }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
90305     sqliteAuthBadReturnCode(pParse);
90306   }
90307   return rc;
90308 }
90309
90310 /*
90311 ** The pExpr should be a TK_COLUMN expression.  The table referred to
90312 ** is in pTabList or else it is the NEW or OLD table of a trigger.  
90313 ** Check to see if it is OK to read this particular column.
90314 **
90315 ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN 
90316 ** instruction into a TK_NULL.  If the auth function returns SQLITE_DENY,
90317 ** then generate an error.
90318 */
90319 SQLITE_PRIVATE void sqlite3AuthRead(
90320   Parse *pParse,        /* The parser context */
90321   Expr *pExpr,          /* The expression to check authorization on */
90322   Schema *pSchema,      /* The schema of the expression */
90323   SrcList *pTabList     /* All table that pExpr might refer to */
90324 ){
90325   sqlite3 *db = pParse->db;
90326   Table *pTab = 0;      /* The table being read */
90327   const char *zCol;     /* Name of the column of the table */
90328   int iSrc;             /* Index in pTabList->a[] of table being read */
90329   int iDb;              /* The index of the database the expression refers to */
90330   int iCol;             /* Index of column in table */
90331
90332   if( db->xAuth==0 ) return;
90333   iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
90334   if( iDb<0 ){
90335     /* An attempt to read a column out of a subquery or other
90336     ** temporary table. */
90337     return;
90338   }
90339
90340   assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
90341   if( pExpr->op==TK_TRIGGER ){
90342     pTab = pParse->pTriggerTab;
90343   }else{
90344     assert( pTabList );
90345     for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
90346       if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
90347         pTab = pTabList->a[iSrc].pTab;
90348         break;
90349       }
90350     }
90351   }
90352   iCol = pExpr->iColumn;
90353   if( NEVER(pTab==0) ) return;
90354
90355   if( iCol>=0 ){
90356     assert( iCol<pTab->nCol );
90357     zCol = pTab->aCol[iCol].zName;
90358   }else if( pTab->iPKey>=0 ){
90359     assert( pTab->iPKey<pTab->nCol );
90360     zCol = pTab->aCol[pTab->iPKey].zName;
90361   }else{
90362     zCol = "ROWID";
90363   }
90364   assert( iDb>=0 && iDb<db->nDb );
90365   if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
90366     pExpr->op = TK_NULL;
90367   }
90368 }
90369
90370 /*
90371 ** Do an authorization check using the code and arguments given.  Return
90372 ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY.  If SQLITE_DENY
90373 ** is returned, then the error count and error message in pParse are
90374 ** modified appropriately.
90375 */
90376 SQLITE_PRIVATE int sqlite3AuthCheck(
90377   Parse *pParse,
90378   int code,
90379   const char *zArg1,
90380   const char *zArg2,
90381   const char *zArg3
90382 ){
90383   sqlite3 *db = pParse->db;
90384   int rc;
90385
90386   /* Don't do any authorization checks if the database is initialising
90387   ** or if the parser is being invoked from within sqlite3_declare_vtab.
90388   */
90389   if( db->init.busy || IN_DECLARE_VTAB ){
90390     return SQLITE_OK;
90391   }
90392
90393   if( db->xAuth==0 ){
90394     return SQLITE_OK;
90395   }
90396   rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
90397 #ifdef SQLITE_USER_AUTHENTICATION
90398                  ,db->auth.zAuthUser
90399 #endif
90400                 );
90401   if( rc==SQLITE_DENY ){
90402     sqlite3ErrorMsg(pParse, "not authorized");
90403     pParse->rc = SQLITE_AUTH;
90404   }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
90405     rc = SQLITE_DENY;
90406     sqliteAuthBadReturnCode(pParse);
90407   }
90408   return rc;
90409 }
90410
90411 /*
90412 ** Push an authorization context.  After this routine is called, the
90413 ** zArg3 argument to authorization callbacks will be zContext until
90414 ** popped.  Or if pParse==0, this routine is a no-op.
90415 */
90416 SQLITE_PRIVATE void sqlite3AuthContextPush(
90417   Parse *pParse,
90418   AuthContext *pContext, 
90419   const char *zContext
90420 ){
90421   assert( pParse );
90422   pContext->pParse = pParse;
90423   pContext->zAuthContext = pParse->zAuthContext;
90424   pParse->zAuthContext = zContext;
90425 }
90426
90427 /*
90428 ** Pop an authorization context that was previously pushed
90429 ** by sqlite3AuthContextPush
90430 */
90431 SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
90432   if( pContext->pParse ){
90433     pContext->pParse->zAuthContext = pContext->zAuthContext;
90434     pContext->pParse = 0;
90435   }
90436 }
90437
90438 #endif /* SQLITE_OMIT_AUTHORIZATION */
90439
90440 /************** End of auth.c ************************************************/
90441 /************** Begin file build.c *******************************************/
90442 /*
90443 ** 2001 September 15
90444 **
90445 ** The author disclaims copyright to this source code.  In place of
90446 ** a legal notice, here is a blessing:
90447 **
90448 **    May you do good and not evil.
90449 **    May you find forgiveness for yourself and forgive others.
90450 **    May you share freely, never taking more than you give.
90451 **
90452 *************************************************************************
90453 ** This file contains C code routines that are called by the SQLite parser
90454 ** when syntax rules are reduced.  The routines in this file handle the
90455 ** following kinds of SQL syntax:
90456 **
90457 **     CREATE TABLE
90458 **     DROP TABLE
90459 **     CREATE INDEX
90460 **     DROP INDEX
90461 **     creating ID lists
90462 **     BEGIN TRANSACTION
90463 **     COMMIT
90464 **     ROLLBACK
90465 */
90466
90467 /*
90468 ** This routine is called when a new SQL statement is beginning to
90469 ** be parsed.  Initialize the pParse structure as needed.
90470 */
90471 SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
90472   pParse->explain = (u8)explainFlag;
90473   pParse->nVar = 0;
90474 }
90475
90476 #ifndef SQLITE_OMIT_SHARED_CACHE
90477 /*
90478 ** The TableLock structure is only used by the sqlite3TableLock() and
90479 ** codeTableLocks() functions.
90480 */
90481 struct TableLock {
90482   int iDb;             /* The database containing the table to be locked */
90483   int iTab;            /* The root page of the table to be locked */
90484   u8 isWriteLock;      /* True for write lock.  False for a read lock */
90485   const char *zName;   /* Name of the table */
90486 };
90487
90488 /*
90489 ** Record the fact that we want to lock a table at run-time.  
90490 **
90491 ** The table to be locked has root page iTab and is found in database iDb.
90492 ** A read or a write lock can be taken depending on isWritelock.
90493 **
90494 ** This routine just records the fact that the lock is desired.  The
90495 ** code to make the lock occur is generated by a later call to
90496 ** codeTableLocks() which occurs during sqlite3FinishCoding().
90497 */
90498 SQLITE_PRIVATE void sqlite3TableLock(
90499   Parse *pParse,     /* Parsing context */
90500   int iDb,           /* Index of the database containing the table to lock */
90501   int iTab,          /* Root page number of the table to be locked */
90502   u8 isWriteLock,    /* True for a write lock */
90503   const char *zName  /* Name of the table to be locked */
90504 ){
90505   Parse *pToplevel = sqlite3ParseToplevel(pParse);
90506   int i;
90507   int nBytes;
90508   TableLock *p;
90509   assert( iDb>=0 );
90510
90511   for(i=0; i<pToplevel->nTableLock; i++){
90512     p = &pToplevel->aTableLock[i];
90513     if( p->iDb==iDb && p->iTab==iTab ){
90514       p->isWriteLock = (p->isWriteLock || isWriteLock);
90515       return;
90516     }
90517   }
90518
90519   nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
90520   pToplevel->aTableLock =
90521       sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
90522   if( pToplevel->aTableLock ){
90523     p = &pToplevel->aTableLock[pToplevel->nTableLock++];
90524     p->iDb = iDb;
90525     p->iTab = iTab;
90526     p->isWriteLock = isWriteLock;
90527     p->zName = zName;
90528   }else{
90529     pToplevel->nTableLock = 0;
90530     pToplevel->db->mallocFailed = 1;
90531   }
90532 }
90533
90534 /*
90535 ** Code an OP_TableLock instruction for each table locked by the
90536 ** statement (configured by calls to sqlite3TableLock()).
90537 */
90538 static void codeTableLocks(Parse *pParse){
90539   int i;
90540   Vdbe *pVdbe; 
90541
90542   pVdbe = sqlite3GetVdbe(pParse);
90543   assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
90544
90545   for(i=0; i<pParse->nTableLock; i++){
90546     TableLock *p = &pParse->aTableLock[i];
90547     int p1 = p->iDb;
90548     sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
90549                       p->zName, P4_STATIC);
90550   }
90551 }
90552 #else
90553   #define codeTableLocks(x)
90554 #endif
90555
90556 /*
90557 ** Return TRUE if the given yDbMask object is empty - if it contains no
90558 ** 1 bits.  This routine is used by the DbMaskAllZero() and DbMaskNotZero()
90559 ** macros when SQLITE_MAX_ATTACHED is greater than 30.
90560 */
90561 #if SQLITE_MAX_ATTACHED>30
90562 SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
90563   int i;
90564   for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
90565   return 1;
90566 }
90567 #endif
90568
90569 /*
90570 ** This routine is called after a single SQL statement has been
90571 ** parsed and a VDBE program to execute that statement has been
90572 ** prepared.  This routine puts the finishing touches on the
90573 ** VDBE program and resets the pParse structure for the next
90574 ** parse.
90575 **
90576 ** Note that if an error occurred, it might be the case that
90577 ** no VDBE code was generated.
90578 */
90579 SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
90580   sqlite3 *db;
90581   Vdbe *v;
90582
90583   assert( pParse->pToplevel==0 );
90584   db = pParse->db;
90585   if( db->mallocFailed ) return;
90586   if( pParse->nested ) return;
90587   if( pParse->nErr ) return;
90588
90589   /* Begin by generating some termination code at the end of the
90590   ** vdbe program
90591   */
90592   v = sqlite3GetVdbe(pParse);
90593   assert( !pParse->isMultiWrite 
90594        || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
90595   if( v ){
90596     while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
90597     sqlite3VdbeAddOp0(v, OP_Halt);
90598
90599 #if SQLITE_USER_AUTHENTICATION
90600     if( pParse->nTableLock>0 && db->init.busy==0 ){
90601       sqlite3UserAuthInit(db);
90602       if( db->auth.authLevel<UAUTH_User ){
90603         pParse->rc = SQLITE_AUTH_USER;
90604         sqlite3ErrorMsg(pParse, "user not authenticated");
90605         return;
90606       }
90607     }
90608 #endif
90609
90610     /* The cookie mask contains one bit for each database file open.
90611     ** (Bit 0 is for main, bit 1 is for temp, and so forth.)  Bits are
90612     ** set for each database that is used.  Generate code to start a
90613     ** transaction on each used database and to verify the schema cookie
90614     ** on each used database.
90615     */
90616     if( db->mallocFailed==0 
90617      && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
90618     ){
90619       int iDb, i;
90620       assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
90621       sqlite3VdbeJumpHere(v, 0);
90622       for(iDb=0; iDb<db->nDb; iDb++){
90623         if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
90624         sqlite3VdbeUsesBtree(v, iDb);
90625         sqlite3VdbeAddOp4Int(v,
90626           OP_Transaction,                    /* Opcode */
90627           iDb,                               /* P1 */
90628           DbMaskTest(pParse->writeMask,iDb), /* P2 */
90629           pParse->cookieValue[iDb],          /* P3 */
90630           db->aDb[iDb].pSchema->iGeneration  /* P4 */
90631         );
90632         if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
90633       }
90634 #ifndef SQLITE_OMIT_VIRTUALTABLE
90635       for(i=0; i<pParse->nVtabLock; i++){
90636         char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
90637         sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
90638       }
90639       pParse->nVtabLock = 0;
90640 #endif
90641
90642       /* Once all the cookies have been verified and transactions opened, 
90643       ** obtain the required table-locks. This is a no-op unless the 
90644       ** shared-cache feature is enabled.
90645       */
90646       codeTableLocks(pParse);
90647
90648       /* Initialize any AUTOINCREMENT data structures required.
90649       */
90650       sqlite3AutoincrementBegin(pParse);
90651
90652       /* Code constant expressions that where factored out of inner loops */
90653       if( pParse->pConstExpr ){
90654         ExprList *pEL = pParse->pConstExpr;
90655         pParse->okConstFactor = 0;
90656         for(i=0; i<pEL->nExpr; i++){
90657           sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
90658         }
90659       }
90660
90661       /* Finally, jump back to the beginning of the executable code. */
90662       sqlite3VdbeAddOp2(v, OP_Goto, 0, 1);
90663     }
90664   }
90665
90666
90667   /* Get the VDBE program ready for execution
90668   */
90669   if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
90670     assert( pParse->iCacheLevel==0 );  /* Disables and re-enables match */
90671     /* A minimum of one cursor is required if autoincrement is used
90672     *  See ticket [a696379c1f08866] */
90673     if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
90674     sqlite3VdbeMakeReady(v, pParse);
90675     pParse->rc = SQLITE_DONE;
90676     pParse->colNamesSet = 0;
90677   }else{
90678     pParse->rc = SQLITE_ERROR;
90679   }
90680   pParse->nTab = 0;
90681   pParse->nMem = 0;
90682   pParse->nSet = 0;
90683   pParse->nVar = 0;
90684   DbMaskZero(pParse->cookieMask);
90685 }
90686
90687 /*
90688 ** Run the parser and code generator recursively in order to generate
90689 ** code for the SQL statement given onto the end of the pParse context
90690 ** currently under construction.  When the parser is run recursively
90691 ** this way, the final OP_Halt is not appended and other initialization
90692 ** and finalization steps are omitted because those are handling by the
90693 ** outermost parser.
90694 **
90695 ** Not everything is nestable.  This facility is designed to permit
90696 ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER.  Use
90697 ** care if you decide to try to use this routine for some other purposes.
90698 */
90699 SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
90700   va_list ap;
90701   char *zSql;
90702   char *zErrMsg = 0;
90703   sqlite3 *db = pParse->db;
90704 # define SAVE_SZ  (sizeof(Parse) - offsetof(Parse,nVar))
90705   char saveBuf[SAVE_SZ];
90706
90707   if( pParse->nErr ) return;
90708   assert( pParse->nested<10 );  /* Nesting should only be of limited depth */
90709   va_start(ap, zFormat);
90710   zSql = sqlite3VMPrintf(db, zFormat, ap);
90711   va_end(ap);
90712   if( zSql==0 ){
90713     return;   /* A malloc must have failed */
90714   }
90715   pParse->nested++;
90716   memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
90717   memset(&pParse->nVar, 0, SAVE_SZ);
90718   sqlite3RunParser(pParse, zSql, &zErrMsg);
90719   sqlite3DbFree(db, zErrMsg);
90720   sqlite3DbFree(db, zSql);
90721   memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
90722   pParse->nested--;
90723 }
90724
90725 #if SQLITE_USER_AUTHENTICATION
90726 /*
90727 ** Return TRUE if zTable is the name of the system table that stores the
90728 ** list of users and their access credentials.
90729 */
90730 SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
90731   return sqlite3_stricmp(zTable, "sqlite_user")==0;
90732 }
90733 #endif
90734
90735 /*
90736 ** Locate the in-memory structure that describes a particular database
90737 ** table given the name of that table and (optionally) the name of the
90738 ** database containing the table.  Return NULL if not found.
90739 **
90740 ** If zDatabase is 0, all databases are searched for the table and the
90741 ** first matching table is returned.  (No checking for duplicate table
90742 ** names is done.)  The search order is TEMP first, then MAIN, then any
90743 ** auxiliary databases added using the ATTACH command.
90744 **
90745 ** See also sqlite3LocateTable().
90746 */
90747 SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
90748   Table *p = 0;
90749   int i;
90750
90751   /* All mutexes are required for schema access.  Make sure we hold them. */
90752   assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
90753 #if SQLITE_USER_AUTHENTICATION
90754   /* Only the admin user is allowed to know that the sqlite_user table
90755   ** exists */
90756   if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
90757     return 0;
90758   }
90759 #endif
90760   for(i=OMIT_TEMPDB; i<db->nDb; i++){
90761     int j = (i<2) ? i^1 : i;   /* Search TEMP before MAIN */
90762     if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
90763     assert( sqlite3SchemaMutexHeld(db, j, 0) );
90764     p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
90765     if( p ) break;
90766   }
90767   return p;
90768 }
90769
90770 /*
90771 ** Locate the in-memory structure that describes a particular database
90772 ** table given the name of that table and (optionally) the name of the
90773 ** database containing the table.  Return NULL if not found.  Also leave an
90774 ** error message in pParse->zErrMsg.
90775 **
90776 ** The difference between this routine and sqlite3FindTable() is that this
90777 ** routine leaves an error message in pParse->zErrMsg where
90778 ** sqlite3FindTable() does not.
90779 */
90780 SQLITE_PRIVATE Table *sqlite3LocateTable(
90781   Parse *pParse,         /* context in which to report errors */
90782   int isView,            /* True if looking for a VIEW rather than a TABLE */
90783   const char *zName,     /* Name of the table we are looking for */
90784   const char *zDbase     /* Name of the database.  Might be NULL */
90785 ){
90786   Table *p;
90787
90788   /* Read the database schema. If an error occurs, leave an error message
90789   ** and code in pParse and return NULL. */
90790   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
90791     return 0;
90792   }
90793
90794   p = sqlite3FindTable(pParse->db, zName, zDbase);
90795   if( p==0 ){
90796     const char *zMsg = isView ? "no such view" : "no such table";
90797     if( zDbase ){
90798       sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
90799     }else{
90800       sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
90801     }
90802     pParse->checkSchema = 1;
90803   }
90804 #if SQLITE_USER_AUTHENICATION
90805   else if( pParse->db->auth.authLevel<UAUTH_User ){
90806     sqlite3ErrorMsg(pParse, "user not authenticated");
90807     p = 0;
90808   }
90809 #endif
90810   return p;
90811 }
90812
90813 /*
90814 ** Locate the table identified by *p.
90815 **
90816 ** This is a wrapper around sqlite3LocateTable(). The difference between
90817 ** sqlite3LocateTable() and this function is that this function restricts
90818 ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
90819 ** non-NULL if it is part of a view or trigger program definition. See
90820 ** sqlite3FixSrcList() for details.
90821 */
90822 SQLITE_PRIVATE Table *sqlite3LocateTableItem(
90823   Parse *pParse, 
90824   int isView, 
90825   struct SrcList_item *p
90826 ){
90827   const char *zDb;
90828   assert( p->pSchema==0 || p->zDatabase==0 );
90829   if( p->pSchema ){
90830     int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
90831     zDb = pParse->db->aDb[iDb].zName;
90832   }else{
90833     zDb = p->zDatabase;
90834   }
90835   return sqlite3LocateTable(pParse, isView, p->zName, zDb);
90836 }
90837
90838 /*
90839 ** Locate the in-memory structure that describes 
90840 ** a particular index given the name of that index
90841 ** and the name of the database that contains the index.
90842 ** Return NULL if not found.
90843 **
90844 ** If zDatabase is 0, all databases are searched for the
90845 ** table and the first matching index is returned.  (No checking
90846 ** for duplicate index names is done.)  The search order is
90847 ** TEMP first, then MAIN, then any auxiliary databases added
90848 ** using the ATTACH command.
90849 */
90850 SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
90851   Index *p = 0;
90852   int i;
90853   /* All mutexes are required for schema access.  Make sure we hold them. */
90854   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
90855   for(i=OMIT_TEMPDB; i<db->nDb; i++){
90856     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
90857     Schema *pSchema = db->aDb[j].pSchema;
90858     assert( pSchema );
90859     if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
90860     assert( sqlite3SchemaMutexHeld(db, j, 0) );
90861     p = sqlite3HashFind(&pSchema->idxHash, zName);
90862     if( p ) break;
90863   }
90864   return p;
90865 }
90866
90867 /*
90868 ** Reclaim the memory used by an index
90869 */
90870 static void freeIndex(sqlite3 *db, Index *p){
90871 #ifndef SQLITE_OMIT_ANALYZE
90872   sqlite3DeleteIndexSamples(db, p);
90873 #endif
90874   sqlite3ExprDelete(db, p->pPartIdxWhere);
90875   sqlite3DbFree(db, p->zColAff);
90876   if( p->isResized ) sqlite3DbFree(db, p->azColl);
90877 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
90878   sqlite3_free(p->aiRowEst);
90879 #endif
90880   sqlite3DbFree(db, p);
90881 }
90882
90883 /*
90884 ** For the index called zIdxName which is found in the database iDb,
90885 ** unlike that index from its Table then remove the index from
90886 ** the index hash table and free all memory structures associated
90887 ** with the index.
90888 */
90889 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
90890   Index *pIndex;
90891   Hash *pHash;
90892
90893   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
90894   pHash = &db->aDb[iDb].pSchema->idxHash;
90895   pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
90896   if( ALWAYS(pIndex) ){
90897     if( pIndex->pTable->pIndex==pIndex ){
90898       pIndex->pTable->pIndex = pIndex->pNext;
90899     }else{
90900       Index *p;
90901       /* Justification of ALWAYS();  The index must be on the list of
90902       ** indices. */
90903       p = pIndex->pTable->pIndex;
90904       while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
90905       if( ALWAYS(p && p->pNext==pIndex) ){
90906         p->pNext = pIndex->pNext;
90907       }
90908     }
90909     freeIndex(db, pIndex);
90910   }
90911   db->flags |= SQLITE_InternChanges;
90912 }
90913
90914 /*
90915 ** Look through the list of open database files in db->aDb[] and if
90916 ** any have been closed, remove them from the list.  Reallocate the
90917 ** db->aDb[] structure to a smaller size, if possible.
90918 **
90919 ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
90920 ** are never candidates for being collapsed.
90921 */
90922 SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
90923   int i, j;
90924   for(i=j=2; i<db->nDb; i++){
90925     struct Db *pDb = &db->aDb[i];
90926     if( pDb->pBt==0 ){
90927       sqlite3DbFree(db, pDb->zName);
90928       pDb->zName = 0;
90929       continue;
90930     }
90931     if( j<i ){
90932       db->aDb[j] = db->aDb[i];
90933     }
90934     j++;
90935   }
90936   memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
90937   db->nDb = j;
90938   if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
90939     memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
90940     sqlite3DbFree(db, db->aDb);
90941     db->aDb = db->aDbStatic;
90942   }
90943 }
90944
90945 /*
90946 ** Reset the schema for the database at index iDb.  Also reset the
90947 ** TEMP schema.
90948 */
90949 SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
90950   Db *pDb;
90951   assert( iDb<db->nDb );
90952
90953   /* Case 1:  Reset the single schema identified by iDb */
90954   pDb = &db->aDb[iDb];
90955   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
90956   assert( pDb->pSchema!=0 );
90957   sqlite3SchemaClear(pDb->pSchema);
90958
90959   /* If any database other than TEMP is reset, then also reset TEMP
90960   ** since TEMP might be holding triggers that reference tables in the
90961   ** other database.
90962   */
90963   if( iDb!=1 ){
90964     pDb = &db->aDb[1];
90965     assert( pDb->pSchema!=0 );
90966     sqlite3SchemaClear(pDb->pSchema);
90967   }
90968   return;
90969 }
90970
90971 /*
90972 ** Erase all schema information from all attached databases (including
90973 ** "main" and "temp") for a single database connection.
90974 */
90975 SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
90976   int i;
90977   sqlite3BtreeEnterAll(db);
90978   for(i=0; i<db->nDb; i++){
90979     Db *pDb = &db->aDb[i];
90980     if( pDb->pSchema ){
90981       sqlite3SchemaClear(pDb->pSchema);
90982     }
90983   }
90984   db->flags &= ~SQLITE_InternChanges;
90985   sqlite3VtabUnlockList(db);
90986   sqlite3BtreeLeaveAll(db);
90987   sqlite3CollapseDatabaseArray(db);
90988 }
90989
90990 /*
90991 ** This routine is called when a commit occurs.
90992 */
90993 SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
90994   db->flags &= ~SQLITE_InternChanges;
90995 }
90996
90997 /*
90998 ** Delete memory allocated for the column names of a table or view (the
90999 ** Table.aCol[] array).
91000 */
91001 static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
91002   int i;
91003   Column *pCol;
91004   assert( pTable!=0 );
91005   if( (pCol = pTable->aCol)!=0 ){
91006     for(i=0; i<pTable->nCol; i++, pCol++){
91007       sqlite3DbFree(db, pCol->zName);
91008       sqlite3ExprDelete(db, pCol->pDflt);
91009       sqlite3DbFree(db, pCol->zDflt);
91010       sqlite3DbFree(db, pCol->zType);
91011       sqlite3DbFree(db, pCol->zColl);
91012     }
91013     sqlite3DbFree(db, pTable->aCol);
91014   }
91015 }
91016
91017 /*
91018 ** Remove the memory data structures associated with the given
91019 ** Table.  No changes are made to disk by this routine.
91020 **
91021 ** This routine just deletes the data structure.  It does not unlink
91022 ** the table data structure from the hash table.  But it does destroy
91023 ** memory structures of the indices and foreign keys associated with 
91024 ** the table.
91025 **
91026 ** The db parameter is optional.  It is needed if the Table object 
91027 ** contains lookaside memory.  (Table objects in the schema do not use
91028 ** lookaside memory, but some ephemeral Table objects do.)  Or the
91029 ** db parameter can be used with db->pnBytesFreed to measure the memory
91030 ** used by the Table object.
91031 */
91032 SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
91033   Index *pIndex, *pNext;
91034   TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
91035
91036   assert( !pTable || pTable->nRef>0 );
91037
91038   /* Do not delete the table until the reference count reaches zero. */
91039   if( !pTable ) return;
91040   if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
91041
91042   /* Record the number of outstanding lookaside allocations in schema Tables
91043   ** prior to doing any free() operations.  Since schema Tables do not use
91044   ** lookaside, this number should not change. */
91045   TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
91046                          db->lookaside.nOut : 0 );
91047
91048   /* Delete all indices associated with this table. */
91049   for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
91050     pNext = pIndex->pNext;
91051     assert( pIndex->pSchema==pTable->pSchema );
91052     if( !db || db->pnBytesFreed==0 ){
91053       char *zName = pIndex->zName; 
91054       TESTONLY ( Index *pOld = ) sqlite3HashInsert(
91055          &pIndex->pSchema->idxHash, zName, 0
91056       );
91057       assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
91058       assert( pOld==pIndex || pOld==0 );
91059     }
91060     freeIndex(db, pIndex);
91061   }
91062
91063   /* Delete any foreign keys attached to this table. */
91064   sqlite3FkDelete(db, pTable);
91065
91066   /* Delete the Table structure itself.
91067   */
91068   sqliteDeleteColumnNames(db, pTable);
91069   sqlite3DbFree(db, pTable->zName);
91070   sqlite3DbFree(db, pTable->zColAff);
91071   sqlite3SelectDelete(db, pTable->pSelect);
91072 #ifndef SQLITE_OMIT_CHECK
91073   sqlite3ExprListDelete(db, pTable->pCheck);
91074 #endif
91075 #ifndef SQLITE_OMIT_VIRTUALTABLE
91076   sqlite3VtabClear(db, pTable);
91077 #endif
91078   sqlite3DbFree(db, pTable);
91079
91080   /* Verify that no lookaside memory was used by schema tables */
91081   assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
91082 }
91083
91084 /*
91085 ** Unlink the given table from the hash tables and the delete the
91086 ** table structure with all its indices and foreign keys.
91087 */
91088 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
91089   Table *p;
91090   Db *pDb;
91091
91092   assert( db!=0 );
91093   assert( iDb>=0 && iDb<db->nDb );
91094   assert( zTabName );
91095   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
91096   testcase( zTabName[0]==0 );  /* Zero-length table names are allowed */
91097   pDb = &db->aDb[iDb];
91098   p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
91099   sqlite3DeleteTable(db, p);
91100   db->flags |= SQLITE_InternChanges;
91101 }
91102
91103 /*
91104 ** Given a token, return a string that consists of the text of that
91105 ** token.  Space to hold the returned string
91106 ** is obtained from sqliteMalloc() and must be freed by the calling
91107 ** function.
91108 **
91109 ** Any quotation marks (ex:  "name", 'name', [name], or `name`) that
91110 ** surround the body of the token are removed.
91111 **
91112 ** Tokens are often just pointers into the original SQL text and so
91113 ** are not \000 terminated and are not persistent.  The returned string
91114 ** is \000 terminated and is persistent.
91115 */
91116 SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
91117   char *zName;
91118   if( pName ){
91119     zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
91120     sqlite3Dequote(zName);
91121   }else{
91122     zName = 0;
91123   }
91124   return zName;
91125 }
91126
91127 /*
91128 ** Open the sqlite_master table stored in database number iDb for
91129 ** writing. The table is opened using cursor 0.
91130 */
91131 SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
91132   Vdbe *v = sqlite3GetVdbe(p);
91133   sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
91134   sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
91135   if( p->nTab==0 ){
91136     p->nTab = 1;
91137   }
91138 }
91139
91140 /*
91141 ** Parameter zName points to a nul-terminated buffer containing the name
91142 ** of a database ("main", "temp" or the name of an attached db). This
91143 ** function returns the index of the named database in db->aDb[], or
91144 ** -1 if the named db cannot be found.
91145 */
91146 SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
91147   int i = -1;         /* Database number */
91148   if( zName ){
91149     Db *pDb;
91150     int n = sqlite3Strlen30(zName);
91151     for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
91152       if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) && 
91153           0==sqlite3StrICmp(pDb->zName, zName) ){
91154         break;
91155       }
91156     }
91157   }
91158   return i;
91159 }
91160
91161 /*
91162 ** The token *pName contains the name of a database (either "main" or
91163 ** "temp" or the name of an attached db). This routine returns the
91164 ** index of the named database in db->aDb[], or -1 if the named db 
91165 ** does not exist.
91166 */
91167 SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
91168   int i;                               /* Database number */
91169   char *zName;                         /* Name we are searching for */
91170   zName = sqlite3NameFromToken(db, pName);
91171   i = sqlite3FindDbName(db, zName);
91172   sqlite3DbFree(db, zName);
91173   return i;
91174 }
91175
91176 /* The table or view or trigger name is passed to this routine via tokens
91177 ** pName1 and pName2. If the table name was fully qualified, for example:
91178 **
91179 ** CREATE TABLE xxx.yyy (...);
91180 ** 
91181 ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
91182 ** the table name is not fully qualified, i.e.:
91183 **
91184 ** CREATE TABLE yyy(...);
91185 **
91186 ** Then pName1 is set to "yyy" and pName2 is "".
91187 **
91188 ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
91189 ** pName2) that stores the unqualified table name.  The index of the
91190 ** database "xxx" is returned.
91191 */
91192 SQLITE_PRIVATE int sqlite3TwoPartName(
91193   Parse *pParse,      /* Parsing and code generating context */
91194   Token *pName1,      /* The "xxx" in the name "xxx.yyy" or "xxx" */
91195   Token *pName2,      /* The "yyy" in the name "xxx.yyy" */
91196   Token **pUnqual     /* Write the unqualified object name here */
91197 ){
91198   int iDb;                    /* Database holding the object */
91199   sqlite3 *db = pParse->db;
91200
91201   if( ALWAYS(pName2!=0) && pName2->n>0 ){
91202     if( db->init.busy ) {
91203       sqlite3ErrorMsg(pParse, "corrupt database");
91204       pParse->nErr++;
91205       return -1;
91206     }
91207     *pUnqual = pName2;
91208     iDb = sqlite3FindDb(db, pName1);
91209     if( iDb<0 ){
91210       sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
91211       pParse->nErr++;
91212       return -1;
91213     }
91214   }else{
91215     assert( db->init.iDb==0 || db->init.busy );
91216     iDb = db->init.iDb;
91217     *pUnqual = pName1;
91218   }
91219   return iDb;
91220 }
91221
91222 /*
91223 ** This routine is used to check if the UTF-8 string zName is a legal
91224 ** unqualified name for a new schema object (table, index, view or
91225 ** trigger). All names are legal except those that begin with the string
91226 ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
91227 ** is reserved for internal use.
91228 */
91229 SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
91230   if( !pParse->db->init.busy && pParse->nested==0 
91231           && (pParse->db->flags & SQLITE_WriteSchema)==0
91232           && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
91233     sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
91234     return SQLITE_ERROR;
91235   }
91236   return SQLITE_OK;
91237 }
91238
91239 /*
91240 ** Return the PRIMARY KEY index of a table
91241 */
91242 SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
91243   Index *p;
91244   for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
91245   return p;
91246 }
91247
91248 /*
91249 ** Return the column of index pIdx that corresponds to table
91250 ** column iCol.  Return -1 if not found.
91251 */
91252 SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
91253   int i;
91254   for(i=0; i<pIdx->nColumn; i++){
91255     if( iCol==pIdx->aiColumn[i] ) return i;
91256   }
91257   return -1;
91258 }
91259
91260 /*
91261 ** Begin constructing a new table representation in memory.  This is
91262 ** the first of several action routines that get called in response
91263 ** to a CREATE TABLE statement.  In particular, this routine is called
91264 ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
91265 ** flag is true if the table should be stored in the auxiliary database
91266 ** file instead of in the main database file.  This is normally the case
91267 ** when the "TEMP" or "TEMPORARY" keyword occurs in between
91268 ** CREATE and TABLE.
91269 **
91270 ** The new table record is initialized and put in pParse->pNewTable.
91271 ** As more of the CREATE TABLE statement is parsed, additional action
91272 ** routines will be called to add more information to this record.
91273 ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
91274 ** is called to complete the construction of the new table record.
91275 */
91276 SQLITE_PRIVATE void sqlite3StartTable(
91277   Parse *pParse,   /* Parser context */
91278   Token *pName1,   /* First part of the name of the table or view */
91279   Token *pName2,   /* Second part of the name of the table or view */
91280   int isTemp,      /* True if this is a TEMP table */
91281   int isView,      /* True if this is a VIEW */
91282   int isVirtual,   /* True if this is a VIRTUAL table */
91283   int noErr        /* Do nothing if table already exists */
91284 ){
91285   Table *pTable;
91286   char *zName = 0; /* The name of the new table */
91287   sqlite3 *db = pParse->db;
91288   Vdbe *v;
91289   int iDb;         /* Database number to create the table in */
91290   Token *pName;    /* Unqualified name of the table to create */
91291
91292   /* The table or view name to create is passed to this routine via tokens
91293   ** pName1 and pName2. If the table name was fully qualified, for example:
91294   **
91295   ** CREATE TABLE xxx.yyy (...);
91296   ** 
91297   ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
91298   ** the table name is not fully qualified, i.e.:
91299   **
91300   ** CREATE TABLE yyy(...);
91301   **
91302   ** Then pName1 is set to "yyy" and pName2 is "".
91303   **
91304   ** The call below sets the pName pointer to point at the token (pName1 or
91305   ** pName2) that stores the unqualified table name. The variable iDb is
91306   ** set to the index of the database that the table or view is to be
91307   ** created in.
91308   */
91309   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
91310   if( iDb<0 ) return;
91311   if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
91312     /* If creating a temp table, the name may not be qualified. Unless 
91313     ** the database name is "temp" anyway.  */
91314     sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
91315     return;
91316   }
91317   if( !OMIT_TEMPDB && isTemp ) iDb = 1;
91318
91319   pParse->sNameToken = *pName;
91320   zName = sqlite3NameFromToken(db, pName);
91321   if( zName==0 ) return;
91322   if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
91323     goto begin_table_error;
91324   }
91325   if( db->init.iDb==1 ) isTemp = 1;
91326 #ifndef SQLITE_OMIT_AUTHORIZATION
91327   assert( (isTemp & 1)==isTemp );
91328   {
91329     int code;
91330     char *zDb = db->aDb[iDb].zName;
91331     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
91332       goto begin_table_error;
91333     }
91334     if( isView ){
91335       if( !OMIT_TEMPDB && isTemp ){
91336         code = SQLITE_CREATE_TEMP_VIEW;
91337       }else{
91338         code = SQLITE_CREATE_VIEW;
91339       }
91340     }else{
91341       if( !OMIT_TEMPDB && isTemp ){
91342         code = SQLITE_CREATE_TEMP_TABLE;
91343       }else{
91344         code = SQLITE_CREATE_TABLE;
91345       }
91346     }
91347     if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
91348       goto begin_table_error;
91349     }
91350   }
91351 #endif
91352
91353   /* Make sure the new table name does not collide with an existing
91354   ** index or table name in the same database.  Issue an error message if
91355   ** it does. The exception is if the statement being parsed was passed
91356   ** to an sqlite3_declare_vtab() call. In that case only the column names
91357   ** and types will be used, so there is no need to test for namespace
91358   ** collisions.
91359   */
91360   if( !IN_DECLARE_VTAB ){
91361     char *zDb = db->aDb[iDb].zName;
91362     if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
91363       goto begin_table_error;
91364     }
91365     pTable = sqlite3FindTable(db, zName, zDb);
91366     if( pTable ){
91367       if( !noErr ){
91368         sqlite3ErrorMsg(pParse, "table %T already exists", pName);
91369       }else{
91370         assert( !db->init.busy );
91371         sqlite3CodeVerifySchema(pParse, iDb);
91372       }
91373       goto begin_table_error;
91374     }
91375     if( sqlite3FindIndex(db, zName, zDb)!=0 ){
91376       sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
91377       goto begin_table_error;
91378     }
91379   }
91380
91381   pTable = sqlite3DbMallocZero(db, sizeof(Table));
91382   if( pTable==0 ){
91383     db->mallocFailed = 1;
91384     pParse->rc = SQLITE_NOMEM;
91385     pParse->nErr++;
91386     goto begin_table_error;
91387   }
91388   pTable->zName = zName;
91389   pTable->iPKey = -1;
91390   pTable->pSchema = db->aDb[iDb].pSchema;
91391   pTable->nRef = 1;
91392   pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
91393   assert( pParse->pNewTable==0 );
91394   pParse->pNewTable = pTable;
91395
91396   /* If this is the magic sqlite_sequence table used by autoincrement,
91397   ** then record a pointer to this table in the main database structure
91398   ** so that INSERT can find the table easily.
91399   */
91400 #ifndef SQLITE_OMIT_AUTOINCREMENT
91401   if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
91402     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
91403     pTable->pSchema->pSeqTab = pTable;
91404   }
91405 #endif
91406
91407   /* Begin generating the code that will insert the table record into
91408   ** the SQLITE_MASTER table.  Note in particular that we must go ahead
91409   ** and allocate the record number for the table entry now.  Before any
91410   ** PRIMARY KEY or UNIQUE keywords are parsed.  Those keywords will cause
91411   ** indices to be created and the table record must come before the 
91412   ** indices.  Hence, the record number for the table must be allocated
91413   ** now.
91414   */
91415   if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
91416     int j1;
91417     int fileFormat;
91418     int reg1, reg2, reg3;
91419     sqlite3BeginWriteOperation(pParse, 0, iDb);
91420
91421 #ifndef SQLITE_OMIT_VIRTUALTABLE
91422     if( isVirtual ){
91423       sqlite3VdbeAddOp0(v, OP_VBegin);
91424     }
91425 #endif
91426
91427     /* If the file format and encoding in the database have not been set, 
91428     ** set them now.
91429     */
91430     reg1 = pParse->regRowid = ++pParse->nMem;
91431     reg2 = pParse->regRoot = ++pParse->nMem;
91432     reg3 = ++pParse->nMem;
91433     sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
91434     sqlite3VdbeUsesBtree(v, iDb);
91435     j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
91436     fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
91437                   1 : SQLITE_MAX_FILE_FORMAT;
91438     sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
91439     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
91440     sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
91441     sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
91442     sqlite3VdbeJumpHere(v, j1);
91443
91444     /* This just creates a place-holder record in the sqlite_master table.
91445     ** The record created does not contain anything yet.  It will be replaced
91446     ** by the real entry in code generated at sqlite3EndTable().
91447     **
91448     ** The rowid for the new entry is left in register pParse->regRowid.
91449     ** The root page number of the new table is left in reg pParse->regRoot.
91450     ** The rowid and root page number values are needed by the code that
91451     ** sqlite3EndTable will generate.
91452     */
91453 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
91454     if( isView || isVirtual ){
91455       sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
91456     }else
91457 #endif
91458     {
91459       pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
91460     }
91461     sqlite3OpenMasterTable(pParse, iDb);
91462     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
91463     sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
91464     sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
91465     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
91466     sqlite3VdbeAddOp0(v, OP_Close);
91467   }
91468
91469   /* Normal (non-error) return. */
91470   return;
91471
91472   /* If an error occurs, we jump here */
91473 begin_table_error:
91474   sqlite3DbFree(db, zName);
91475   return;
91476 }
91477
91478 /*
91479 ** This macro is used to compare two strings in a case-insensitive manner.
91480 ** It is slightly faster than calling sqlite3StrICmp() directly, but
91481 ** produces larger code.
91482 **
91483 ** WARNING: This macro is not compatible with the strcmp() family. It
91484 ** returns true if the two strings are equal, otherwise false.
91485 */
91486 #define STRICMP(x, y) (\
91487 sqlite3UpperToLower[*(unsigned char *)(x)]==   \
91488 sqlite3UpperToLower[*(unsigned char *)(y)]     \
91489 && sqlite3StrICmp((x)+1,(y)+1)==0 )
91490
91491 /*
91492 ** Add a new column to the table currently being constructed.
91493 **
91494 ** The parser calls this routine once for each column declaration
91495 ** in a CREATE TABLE statement.  sqlite3StartTable() gets called
91496 ** first to get things going.  Then this routine is called for each
91497 ** column.
91498 */
91499 SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
91500   Table *p;
91501   int i;
91502   char *z;
91503   Column *pCol;
91504   sqlite3 *db = pParse->db;
91505   if( (p = pParse->pNewTable)==0 ) return;
91506 #if SQLITE_MAX_COLUMN
91507   if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
91508     sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
91509     return;
91510   }
91511 #endif
91512   z = sqlite3NameFromToken(db, pName);
91513   if( z==0 ) return;
91514   for(i=0; i<p->nCol; i++){
91515     if( STRICMP(z, p->aCol[i].zName) ){
91516       sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
91517       sqlite3DbFree(db, z);
91518       return;
91519     }
91520   }
91521   if( (p->nCol & 0x7)==0 ){
91522     Column *aNew;
91523     aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
91524     if( aNew==0 ){
91525       sqlite3DbFree(db, z);
91526       return;
91527     }
91528     p->aCol = aNew;
91529   }
91530   pCol = &p->aCol[p->nCol];
91531   memset(pCol, 0, sizeof(p->aCol[0]));
91532   pCol->zName = z;
91533  
91534   /* If there is no type specified, columns have the default affinity
91535   ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
91536   ** be called next to set pCol->affinity correctly.
91537   */
91538   pCol->affinity = SQLITE_AFF_NONE;
91539   pCol->szEst = 1;
91540   p->nCol++;
91541 }
91542
91543 /*
91544 ** This routine is called by the parser while in the middle of
91545 ** parsing a CREATE TABLE statement.  A "NOT NULL" constraint has
91546 ** been seen on a column.  This routine sets the notNull flag on
91547 ** the column currently under construction.
91548 */
91549 SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
91550   Table *p;
91551   p = pParse->pNewTable;
91552   if( p==0 || NEVER(p->nCol<1) ) return;
91553   p->aCol[p->nCol-1].notNull = (u8)onError;
91554 }
91555
91556 /*
91557 ** Scan the column type name zType (length nType) and return the
91558 ** associated affinity type.
91559 **
91560 ** This routine does a case-independent search of zType for the 
91561 ** substrings in the following table. If one of the substrings is
91562 ** found, the corresponding affinity is returned. If zType contains
91563 ** more than one of the substrings, entries toward the top of 
91564 ** the table take priority. For example, if zType is 'BLOBINT', 
91565 ** SQLITE_AFF_INTEGER is returned.
91566 **
91567 ** Substring     | Affinity
91568 ** --------------------------------
91569 ** 'INT'         | SQLITE_AFF_INTEGER
91570 ** 'CHAR'        | SQLITE_AFF_TEXT
91571 ** 'CLOB'        | SQLITE_AFF_TEXT
91572 ** 'TEXT'        | SQLITE_AFF_TEXT
91573 ** 'BLOB'        | SQLITE_AFF_NONE
91574 ** 'REAL'        | SQLITE_AFF_REAL
91575 ** 'FLOA'        | SQLITE_AFF_REAL
91576 ** 'DOUB'        | SQLITE_AFF_REAL
91577 **
91578 ** If none of the substrings in the above table are found,
91579 ** SQLITE_AFF_NUMERIC is returned.
91580 */
91581 SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
91582   u32 h = 0;
91583   char aff = SQLITE_AFF_NUMERIC;
91584   const char *zChar = 0;
91585
91586   if( zIn==0 ) return aff;
91587   while( zIn[0] ){
91588     h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
91589     zIn++;
91590     if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){             /* CHAR */
91591       aff = SQLITE_AFF_TEXT;
91592       zChar = zIn;
91593     }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){       /* CLOB */
91594       aff = SQLITE_AFF_TEXT;
91595     }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){       /* TEXT */
91596       aff = SQLITE_AFF_TEXT;
91597     }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b')          /* BLOB */
91598         && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
91599       aff = SQLITE_AFF_NONE;
91600       if( zIn[0]=='(' ) zChar = zIn;
91601 #ifndef SQLITE_OMIT_FLOATING_POINT
91602     }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l')          /* REAL */
91603         && aff==SQLITE_AFF_NUMERIC ){
91604       aff = SQLITE_AFF_REAL;
91605     }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a')          /* FLOA */
91606         && aff==SQLITE_AFF_NUMERIC ){
91607       aff = SQLITE_AFF_REAL;
91608     }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b')          /* DOUB */
91609         && aff==SQLITE_AFF_NUMERIC ){
91610       aff = SQLITE_AFF_REAL;
91611 #endif
91612     }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){    /* INT */
91613       aff = SQLITE_AFF_INTEGER;
91614       break;
91615     }
91616   }
91617
91618   /* If pszEst is not NULL, store an estimate of the field size.  The
91619   ** estimate is scaled so that the size of an integer is 1.  */
91620   if( pszEst ){
91621     *pszEst = 1;   /* default size is approx 4 bytes */
91622     if( aff<SQLITE_AFF_NUMERIC ){
91623       if( zChar ){
91624         while( zChar[0] ){
91625           if( sqlite3Isdigit(zChar[0]) ){
91626             int v = 0;
91627             sqlite3GetInt32(zChar, &v);
91628             v = v/4 + 1;
91629             if( v>255 ) v = 255;
91630             *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
91631             break;
91632           }
91633           zChar++;
91634         }
91635       }else{
91636         *pszEst = 5;   /* BLOB, TEXT, CLOB -> r=5  (approx 20 bytes)*/
91637       }
91638     }
91639   }
91640   return aff;
91641 }
91642
91643 /*
91644 ** This routine is called by the parser while in the middle of
91645 ** parsing a CREATE TABLE statement.  The pFirst token is the first
91646 ** token in the sequence of tokens that describe the type of the
91647 ** column currently under construction.   pLast is the last token
91648 ** in the sequence.  Use this information to construct a string
91649 ** that contains the typename of the column and store that string
91650 ** in zType.
91651 */ 
91652 SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
91653   Table *p;
91654   Column *pCol;
91655
91656   p = pParse->pNewTable;
91657   if( p==0 || NEVER(p->nCol<1) ) return;
91658   pCol = &p->aCol[p->nCol-1];
91659   assert( pCol->zType==0 );
91660   pCol->zType = sqlite3NameFromToken(pParse->db, pType);
91661   pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
91662 }
91663
91664 /*
91665 ** The expression is the default value for the most recently added column
91666 ** of the table currently under construction.
91667 **
91668 ** Default value expressions must be constant.  Raise an exception if this
91669 ** is not the case.
91670 **
91671 ** This routine is called by the parser while in the middle of
91672 ** parsing a CREATE TABLE statement.
91673 */
91674 SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
91675   Table *p;
91676   Column *pCol;
91677   sqlite3 *db = pParse->db;
91678   p = pParse->pNewTable;
91679   if( p!=0 ){
91680     pCol = &(p->aCol[p->nCol-1]);
91681     if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
91682       sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
91683           pCol->zName);
91684     }else{
91685       /* A copy of pExpr is used instead of the original, as pExpr contains
91686       ** tokens that point to volatile memory. The 'span' of the expression
91687       ** is required by pragma table_info.
91688       */
91689       sqlite3ExprDelete(db, pCol->pDflt);
91690       pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
91691       sqlite3DbFree(db, pCol->zDflt);
91692       pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
91693                                      (int)(pSpan->zEnd - pSpan->zStart));
91694     }
91695   }
91696   sqlite3ExprDelete(db, pSpan->pExpr);
91697 }
91698
91699 /*
91700 ** Designate the PRIMARY KEY for the table.  pList is a list of names 
91701 ** of columns that form the primary key.  If pList is NULL, then the
91702 ** most recently added column of the table is the primary key.
91703 **
91704 ** A table can have at most one primary key.  If the table already has
91705 ** a primary key (and this is the second primary key) then create an
91706 ** error.
91707 **
91708 ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
91709 ** then we will try to use that column as the rowid.  Set the Table.iPKey
91710 ** field of the table under construction to be the index of the
91711 ** INTEGER PRIMARY KEY column.  Table.iPKey is set to -1 if there is
91712 ** no INTEGER PRIMARY KEY.
91713 **
91714 ** If the key is not an INTEGER PRIMARY KEY, then create a unique
91715 ** index for the key.  No index is created for INTEGER PRIMARY KEYs.
91716 */
91717 SQLITE_PRIVATE void sqlite3AddPrimaryKey(
91718   Parse *pParse,    /* Parsing context */
91719   ExprList *pList,  /* List of field names to be indexed */
91720   int onError,      /* What to do with a uniqueness conflict */
91721   int autoInc,      /* True if the AUTOINCREMENT keyword is present */
91722   int sortOrder     /* SQLITE_SO_ASC or SQLITE_SO_DESC */
91723 ){
91724   Table *pTab = pParse->pNewTable;
91725   char *zType = 0;
91726   int iCol = -1, i;
91727   int nTerm;
91728   if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
91729   if( pTab->tabFlags & TF_HasPrimaryKey ){
91730     sqlite3ErrorMsg(pParse, 
91731       "table \"%s\" has more than one primary key", pTab->zName);
91732     goto primary_key_exit;
91733   }
91734   pTab->tabFlags |= TF_HasPrimaryKey;
91735   if( pList==0 ){
91736     iCol = pTab->nCol - 1;
91737     pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
91738     zType = pTab->aCol[iCol].zType;
91739     nTerm = 1;
91740   }else{
91741     nTerm = pList->nExpr;
91742     for(i=0; i<nTerm; i++){
91743       for(iCol=0; iCol<pTab->nCol; iCol++){
91744         if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
91745           pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
91746           zType = pTab->aCol[iCol].zType;
91747           break;
91748         }
91749       }
91750     }
91751   }
91752   if( nTerm==1
91753    && zType && sqlite3StrICmp(zType, "INTEGER")==0
91754    && sortOrder==SQLITE_SO_ASC
91755   ){
91756     pTab->iPKey = iCol;
91757     pTab->keyConf = (u8)onError;
91758     assert( autoInc==0 || autoInc==1 );
91759     pTab->tabFlags |= autoInc*TF_Autoincrement;
91760     if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
91761   }else if( autoInc ){
91762 #ifndef SQLITE_OMIT_AUTOINCREMENT
91763     sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
91764        "INTEGER PRIMARY KEY");
91765 #endif
91766   }else{
91767     Vdbe *v = pParse->pVdbe;
91768     Index *p;
91769     if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop);
91770     p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
91771                            0, sortOrder, 0);
91772     if( p ){
91773       p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
91774       if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK);
91775     }
91776     pList = 0;
91777   }
91778
91779 primary_key_exit:
91780   sqlite3ExprListDelete(pParse->db, pList);
91781   return;
91782 }
91783
91784 /*
91785 ** Add a new CHECK constraint to the table currently under construction.
91786 */
91787 SQLITE_PRIVATE void sqlite3AddCheckConstraint(
91788   Parse *pParse,    /* Parsing context */
91789   Expr *pCheckExpr  /* The check expression */
91790 ){
91791 #ifndef SQLITE_OMIT_CHECK
91792   Table *pTab = pParse->pNewTable;
91793   sqlite3 *db = pParse->db;
91794   if( pTab && !IN_DECLARE_VTAB
91795    && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
91796   ){
91797     pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
91798     if( pParse->constraintName.n ){
91799       sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
91800     }
91801   }else
91802 #endif
91803   {
91804     sqlite3ExprDelete(pParse->db, pCheckExpr);
91805   }
91806 }
91807
91808 /*
91809 ** Set the collation function of the most recently parsed table column
91810 ** to the CollSeq given.
91811 */
91812 SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
91813   Table *p;
91814   int i;
91815   char *zColl;              /* Dequoted name of collation sequence */
91816   sqlite3 *db;
91817
91818   if( (p = pParse->pNewTable)==0 ) return;
91819   i = p->nCol-1;
91820   db = pParse->db;
91821   zColl = sqlite3NameFromToken(db, pToken);
91822   if( !zColl ) return;
91823
91824   if( sqlite3LocateCollSeq(pParse, zColl) ){
91825     Index *pIdx;
91826     sqlite3DbFree(db, p->aCol[i].zColl);
91827     p->aCol[i].zColl = zColl;
91828   
91829     /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
91830     ** then an index may have been created on this column before the
91831     ** collation type was added. Correct this if it is the case.
91832     */
91833     for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
91834       assert( pIdx->nKeyCol==1 );
91835       if( pIdx->aiColumn[0]==i ){
91836         pIdx->azColl[0] = p->aCol[i].zColl;
91837       }
91838     }
91839   }else{
91840     sqlite3DbFree(db, zColl);
91841   }
91842 }
91843
91844 /*
91845 ** This function returns the collation sequence for database native text
91846 ** encoding identified by the string zName, length nName.
91847 **
91848 ** If the requested collation sequence is not available, or not available
91849 ** in the database native encoding, the collation factory is invoked to
91850 ** request it. If the collation factory does not supply such a sequence,
91851 ** and the sequence is available in another text encoding, then that is
91852 ** returned instead.
91853 **
91854 ** If no versions of the requested collations sequence are available, or
91855 ** another error occurs, NULL is returned and an error message written into
91856 ** pParse.
91857 **
91858 ** This routine is a wrapper around sqlite3FindCollSeq().  This routine
91859 ** invokes the collation factory if the named collation cannot be found
91860 ** and generates an error message.
91861 **
91862 ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
91863 */
91864 SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
91865   sqlite3 *db = pParse->db;
91866   u8 enc = ENC(db);
91867   u8 initbusy = db->init.busy;
91868   CollSeq *pColl;
91869
91870   pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
91871   if( !initbusy && (!pColl || !pColl->xCmp) ){
91872     pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
91873   }
91874
91875   return pColl;
91876 }
91877
91878
91879 /*
91880 ** Generate code that will increment the schema cookie.
91881 **
91882 ** The schema cookie is used to determine when the schema for the
91883 ** database changes.  After each schema change, the cookie value
91884 ** changes.  When a process first reads the schema it records the
91885 ** cookie.  Thereafter, whenever it goes to access the database,
91886 ** it checks the cookie to make sure the schema has not changed
91887 ** since it was last read.
91888 **
91889 ** This plan is not completely bullet-proof.  It is possible for
91890 ** the schema to change multiple times and for the cookie to be
91891 ** set back to prior value.  But schema changes are infrequent
91892 ** and the probability of hitting the same cookie value is only
91893 ** 1 chance in 2^32.  So we're safe enough.
91894 */
91895 SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
91896   int r1 = sqlite3GetTempReg(pParse);
91897   sqlite3 *db = pParse->db;
91898   Vdbe *v = pParse->pVdbe;
91899   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
91900   sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
91901   sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
91902   sqlite3ReleaseTempReg(pParse, r1);
91903 }
91904
91905 /*
91906 ** Measure the number of characters needed to output the given
91907 ** identifier.  The number returned includes any quotes used
91908 ** but does not include the null terminator.
91909 **
91910 ** The estimate is conservative.  It might be larger that what is
91911 ** really needed.
91912 */
91913 static int identLength(const char *z){
91914   int n;
91915   for(n=0; *z; n++, z++){
91916     if( *z=='"' ){ n++; }
91917   }
91918   return n + 2;
91919 }
91920
91921 /*
91922 ** The first parameter is a pointer to an output buffer. The second 
91923 ** parameter is a pointer to an integer that contains the offset at
91924 ** which to write into the output buffer. This function copies the
91925 ** nul-terminated string pointed to by the third parameter, zSignedIdent,
91926 ** to the specified offset in the buffer and updates *pIdx to refer
91927 ** to the first byte after the last byte written before returning.
91928 ** 
91929 ** If the string zSignedIdent consists entirely of alpha-numeric
91930 ** characters, does not begin with a digit and is not an SQL keyword,
91931 ** then it is copied to the output buffer exactly as it is. Otherwise,
91932 ** it is quoted using double-quotes.
91933 */
91934 static void identPut(char *z, int *pIdx, char *zSignedIdent){
91935   unsigned char *zIdent = (unsigned char*)zSignedIdent;
91936   int i, j, needQuote;
91937   i = *pIdx;
91938
91939   for(j=0; zIdent[j]; j++){
91940     if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
91941   }
91942   needQuote = sqlite3Isdigit(zIdent[0])
91943             || sqlite3KeywordCode(zIdent, j)!=TK_ID
91944             || zIdent[j]!=0
91945             || j==0;
91946
91947   if( needQuote ) z[i++] = '"';
91948   for(j=0; zIdent[j]; j++){
91949     z[i++] = zIdent[j];
91950     if( zIdent[j]=='"' ) z[i++] = '"';
91951   }
91952   if( needQuote ) z[i++] = '"';
91953   z[i] = 0;
91954   *pIdx = i;
91955 }
91956
91957 /*
91958 ** Generate a CREATE TABLE statement appropriate for the given
91959 ** table.  Memory to hold the text of the statement is obtained
91960 ** from sqliteMalloc() and must be freed by the calling function.
91961 */
91962 static char *createTableStmt(sqlite3 *db, Table *p){
91963   int i, k, n;
91964   char *zStmt;
91965   char *zSep, *zSep2, *zEnd;
91966   Column *pCol;
91967   n = 0;
91968   for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
91969     n += identLength(pCol->zName) + 5;
91970   }
91971   n += identLength(p->zName);
91972   if( n<50 ){ 
91973     zSep = "";
91974     zSep2 = ",";
91975     zEnd = ")";
91976   }else{
91977     zSep = "\n  ";
91978     zSep2 = ",\n  ";
91979     zEnd = "\n)";
91980   }
91981   n += 35 + 6*p->nCol;
91982   zStmt = sqlite3DbMallocRaw(0, n);
91983   if( zStmt==0 ){
91984     db->mallocFailed = 1;
91985     return 0;
91986   }
91987   sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
91988   k = sqlite3Strlen30(zStmt);
91989   identPut(zStmt, &k, p->zName);
91990   zStmt[k++] = '(';
91991   for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
91992     static const char * const azType[] = {
91993         /* SQLITE_AFF_NONE    */ "",
91994         /* SQLITE_AFF_TEXT    */ " TEXT",
91995         /* SQLITE_AFF_NUMERIC */ " NUM",
91996         /* SQLITE_AFF_INTEGER */ " INT",
91997         /* SQLITE_AFF_REAL    */ " REAL"
91998     };
91999     int len;
92000     const char *zType;
92001
92002     sqlite3_snprintf(n-k, &zStmt[k], zSep);
92003     k += sqlite3Strlen30(&zStmt[k]);
92004     zSep = zSep2;
92005     identPut(zStmt, &k, pCol->zName);
92006     assert( pCol->affinity-SQLITE_AFF_NONE >= 0 );
92007     assert( pCol->affinity-SQLITE_AFF_NONE < ArraySize(azType) );
92008     testcase( pCol->affinity==SQLITE_AFF_NONE );
92009     testcase( pCol->affinity==SQLITE_AFF_TEXT );
92010     testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
92011     testcase( pCol->affinity==SQLITE_AFF_INTEGER );
92012     testcase( pCol->affinity==SQLITE_AFF_REAL );
92013     
92014     zType = azType[pCol->affinity - SQLITE_AFF_NONE];
92015     len = sqlite3Strlen30(zType);
92016     assert( pCol->affinity==SQLITE_AFF_NONE 
92017             || pCol->affinity==sqlite3AffinityType(zType, 0) );
92018     memcpy(&zStmt[k], zType, len);
92019     k += len;
92020     assert( k<=n );
92021   }
92022   sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
92023   return zStmt;
92024 }
92025
92026 /*
92027 ** Resize an Index object to hold N columns total.  Return SQLITE_OK
92028 ** on success and SQLITE_NOMEM on an OOM error.
92029 */
92030 static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
92031   char *zExtra;
92032   int nByte;
92033   if( pIdx->nColumn>=N ) return SQLITE_OK;
92034   assert( pIdx->isResized==0 );
92035   nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
92036   zExtra = sqlite3DbMallocZero(db, nByte);
92037   if( zExtra==0 ) return SQLITE_NOMEM;
92038   memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
92039   pIdx->azColl = (char**)zExtra;
92040   zExtra += sizeof(char*)*N;
92041   memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
92042   pIdx->aiColumn = (i16*)zExtra;
92043   zExtra += sizeof(i16)*N;
92044   memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
92045   pIdx->aSortOrder = (u8*)zExtra;
92046   pIdx->nColumn = N;
92047   pIdx->isResized = 1;
92048   return SQLITE_OK;
92049 }
92050
92051 /*
92052 ** Estimate the total row width for a table.
92053 */
92054 static void estimateTableWidth(Table *pTab){
92055   unsigned wTable = 0;
92056   const Column *pTabCol;
92057   int i;
92058   for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
92059     wTable += pTabCol->szEst;
92060   }
92061   if( pTab->iPKey<0 ) wTable++;
92062   pTab->szTabRow = sqlite3LogEst(wTable*4);
92063 }
92064
92065 /*
92066 ** Estimate the average size of a row for an index.
92067 */
92068 static void estimateIndexWidth(Index *pIdx){
92069   unsigned wIndex = 0;
92070   int i;
92071   const Column *aCol = pIdx->pTable->aCol;
92072   for(i=0; i<pIdx->nColumn; i++){
92073     i16 x = pIdx->aiColumn[i];
92074     assert( x<pIdx->pTable->nCol );
92075     wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
92076   }
92077   pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
92078 }
92079
92080 /* Return true if value x is found any of the first nCol entries of aiCol[]
92081 */
92082 static int hasColumn(const i16 *aiCol, int nCol, int x){
92083   while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
92084   return 0;
92085 }
92086
92087 /*
92088 ** This routine runs at the end of parsing a CREATE TABLE statement that
92089 ** has a WITHOUT ROWID clause.  The job of this routine is to convert both
92090 ** internal schema data structures and the generated VDBE code so that they
92091 ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
92092 ** Changes include:
92093 **
92094 **     (1)  Convert the OP_CreateTable into an OP_CreateIndex.  There is
92095 **          no rowid btree for a WITHOUT ROWID.  Instead, the canonical
92096 **          data storage is a covering index btree.
92097 **     (2)  Bypass the creation of the sqlite_master table entry
92098 **          for the PRIMARY KEY as the primary key index is now
92099 **          identified by the sqlite_master table entry of the table itself.
92100 **     (3)  Set the Index.tnum of the PRIMARY KEY Index object in the
92101 **          schema to the rootpage from the main table.
92102 **     (4)  Set all columns of the PRIMARY KEY schema object to be NOT NULL.
92103 **     (5)  Add all table columns to the PRIMARY KEY Index object
92104 **          so that the PRIMARY KEY is a covering index.  The surplus
92105 **          columns are part of KeyInfo.nXField and are not used for
92106 **          sorting or lookup or uniqueness checks.
92107 **     (6)  Replace the rowid tail on all automatically generated UNIQUE
92108 **          indices with the PRIMARY KEY columns.
92109 */
92110 static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
92111   Index *pIdx;
92112   Index *pPk;
92113   int nPk;
92114   int i, j;
92115   sqlite3 *db = pParse->db;
92116   Vdbe *v = pParse->pVdbe;
92117
92118   /* Convert the OP_CreateTable opcode that would normally create the
92119   ** root-page for the table into an OP_CreateIndex opcode.  The index
92120   ** created will become the PRIMARY KEY index.
92121   */
92122   if( pParse->addrCrTab ){
92123     assert( v );
92124     sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
92125   }
92126
92127   /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
92128   ** table entry.
92129   */
92130   if( pParse->addrSkipPK ){
92131     assert( v );
92132     sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
92133   }
92134
92135   /* Locate the PRIMARY KEY index.  Or, if this table was originally
92136   ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index. 
92137   */
92138   if( pTab->iPKey>=0 ){
92139     ExprList *pList;
92140     pList = sqlite3ExprListAppend(pParse, 0, 0);
92141     if( pList==0 ) return;
92142     pList->a[0].zName = sqlite3DbStrDup(pParse->db,
92143                                         pTab->aCol[pTab->iPKey].zName);
92144     pList->a[0].sortOrder = pParse->iPkSortOrder;
92145     assert( pParse->pNewTable==pTab );
92146     pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
92147     if( pPk==0 ) return;
92148     pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
92149     pTab->iPKey = -1;
92150   }else{
92151     pPk = sqlite3PrimaryKeyIndex(pTab);
92152     /*
92153     ** Remove all redundant columns from the PRIMARY KEY.  For example, change
92154     ** "PRIMARY KEY(a,b,a,b,c,b,c,d)" into just "PRIMARY KEY(a,b,c,d)".  Later
92155     ** code assumes the PRIMARY KEY contains no repeated columns.
92156     */
92157     for(i=j=1; i<pPk->nKeyCol; i++){
92158       if( hasColumn(pPk->aiColumn, j, pPk->aiColumn[i]) ){
92159         pPk->nColumn--;
92160       }else{
92161         pPk->aiColumn[j++] = pPk->aiColumn[i];
92162       }
92163     }
92164     pPk->nKeyCol = j;
92165   }
92166   pPk->isCovering = 1;
92167   assert( pPk!=0 );
92168   nPk = pPk->nKeyCol;
92169
92170   /* Make sure every column of the PRIMARY KEY is NOT NULL.  (Except,
92171   ** do not enforce this for imposter tables.) */
92172   if( !db->init.imposterTable ){
92173     for(i=0; i<nPk; i++){
92174       pTab->aCol[pPk->aiColumn[i]].notNull = 1;
92175     }
92176     pPk->uniqNotNull = 1;
92177   }
92178
92179   /* The root page of the PRIMARY KEY is the table root page */
92180   pPk->tnum = pTab->tnum;
92181
92182   /* Update the in-memory representation of all UNIQUE indices by converting
92183   ** the final rowid column into one or more columns of the PRIMARY KEY.
92184   */
92185   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
92186     int n;
92187     if( IsPrimaryKeyIndex(pIdx) ) continue;
92188     for(i=n=0; i<nPk; i++){
92189       if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
92190     }
92191     if( n==0 ){
92192       /* This index is a superset of the primary key */
92193       pIdx->nColumn = pIdx->nKeyCol;
92194       continue;
92195     }
92196     if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
92197     for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
92198       if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
92199         pIdx->aiColumn[j] = pPk->aiColumn[i];
92200         pIdx->azColl[j] = pPk->azColl[i];
92201         j++;
92202       }
92203     }
92204     assert( pIdx->nColumn>=pIdx->nKeyCol+n );
92205     assert( pIdx->nColumn>=j );
92206   }
92207
92208   /* Add all table columns to the PRIMARY KEY index
92209   */
92210   if( nPk<pTab->nCol ){
92211     if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
92212     for(i=0, j=nPk; i<pTab->nCol; i++){
92213       if( !hasColumn(pPk->aiColumn, j, i) ){
92214         assert( j<pPk->nColumn );
92215         pPk->aiColumn[j] = i;
92216         pPk->azColl[j] = "BINARY";
92217         j++;
92218       }
92219     }
92220     assert( pPk->nColumn==j );
92221     assert( pTab->nCol==j );
92222   }else{
92223     pPk->nColumn = pTab->nCol;
92224   }
92225 }
92226
92227 /*
92228 ** This routine is called to report the final ")" that terminates
92229 ** a CREATE TABLE statement.
92230 **
92231 ** The table structure that other action routines have been building
92232 ** is added to the internal hash tables, assuming no errors have
92233 ** occurred.
92234 **
92235 ** An entry for the table is made in the master table on disk, unless
92236 ** this is a temporary table or db->init.busy==1.  When db->init.busy==1
92237 ** it means we are reading the sqlite_master table because we just
92238 ** connected to the database or because the sqlite_master table has
92239 ** recently changed, so the entry for this table already exists in
92240 ** the sqlite_master table.  We do not want to create it again.
92241 **
92242 ** If the pSelect argument is not NULL, it means that this routine
92243 ** was called to create a table generated from a 
92244 ** "CREATE TABLE ... AS SELECT ..." statement.  The column names of
92245 ** the new table will match the result set of the SELECT.
92246 */
92247 SQLITE_PRIVATE void sqlite3EndTable(
92248   Parse *pParse,          /* Parse context */
92249   Token *pCons,           /* The ',' token after the last column defn. */
92250   Token *pEnd,            /* The ')' before options in the CREATE TABLE */
92251   u8 tabOpts,             /* Extra table options. Usually 0. */
92252   Select *pSelect         /* Select from a "CREATE ... AS SELECT" */
92253 ){
92254   Table *p;                 /* The new table */
92255   sqlite3 *db = pParse->db; /* The database connection */
92256   int iDb;                  /* Database in which the table lives */
92257   Index *pIdx;              /* An implied index of the table */
92258
92259   if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
92260     return;
92261   }
92262   p = pParse->pNewTable;
92263   if( p==0 ) return;
92264
92265   assert( !db->init.busy || !pSelect );
92266
92267   /* If the db->init.busy is 1 it means we are reading the SQL off the
92268   ** "sqlite_master" or "sqlite_temp_master" table on the disk.
92269   ** So do not write to the disk again.  Extract the root page number
92270   ** for the table from the db->init.newTnum field.  (The page number
92271   ** should have been put there by the sqliteOpenCb routine.)
92272   */
92273   if( db->init.busy ){
92274     p->tnum = db->init.newTnum;
92275   }
92276
92277   /* Special processing for WITHOUT ROWID Tables */
92278   if( tabOpts & TF_WithoutRowid ){
92279     if( (p->tabFlags & TF_Autoincrement) ){
92280       sqlite3ErrorMsg(pParse,
92281           "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
92282       return;
92283     }
92284     if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
92285       sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
92286     }else{
92287       p->tabFlags |= TF_WithoutRowid;
92288       convertToWithoutRowidTable(pParse, p);
92289     }
92290   }
92291
92292   iDb = sqlite3SchemaToIndex(db, p->pSchema);
92293
92294 #ifndef SQLITE_OMIT_CHECK
92295   /* Resolve names in all CHECK constraint expressions.
92296   */
92297   if( p->pCheck ){
92298     sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
92299   }
92300 #endif /* !defined(SQLITE_OMIT_CHECK) */
92301
92302   /* Estimate the average row size for the table and for all implied indices */
92303   estimateTableWidth(p);
92304   for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
92305     estimateIndexWidth(pIdx);
92306   }
92307
92308   /* If not initializing, then create a record for the new table
92309   ** in the SQLITE_MASTER table of the database.
92310   **
92311   ** If this is a TEMPORARY table, write the entry into the auxiliary
92312   ** file instead of into the main database file.
92313   */
92314   if( !db->init.busy ){
92315     int n;
92316     Vdbe *v;
92317     char *zType;    /* "view" or "table" */
92318     char *zType2;   /* "VIEW" or "TABLE" */
92319     char *zStmt;    /* Text of the CREATE TABLE or CREATE VIEW statement */
92320
92321     v = sqlite3GetVdbe(pParse);
92322     if( NEVER(v==0) ) return;
92323
92324     sqlite3VdbeAddOp1(v, OP_Close, 0);
92325
92326     /* 
92327     ** Initialize zType for the new view or table.
92328     */
92329     if( p->pSelect==0 ){
92330       /* A regular table */
92331       zType = "table";
92332       zType2 = "TABLE";
92333 #ifndef SQLITE_OMIT_VIEW
92334     }else{
92335       /* A view */
92336       zType = "view";
92337       zType2 = "VIEW";
92338 #endif
92339     }
92340
92341     /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
92342     ** statement to populate the new table. The root-page number for the
92343     ** new table is in register pParse->regRoot.
92344     **
92345     ** Once the SELECT has been coded by sqlite3Select(), it is in a
92346     ** suitable state to query for the column names and types to be used
92347     ** by the new table.
92348     **
92349     ** A shared-cache write-lock is not required to write to the new table,
92350     ** as a schema-lock must have already been obtained to create it. Since
92351     ** a schema-lock excludes all other database users, the write-lock would
92352     ** be redundant.
92353     */
92354     if( pSelect ){
92355       SelectDest dest;
92356       Table *pSelTab;
92357
92358       assert(pParse->nTab==1);
92359       sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
92360       sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
92361       pParse->nTab = 2;
92362       sqlite3SelectDestInit(&dest, SRT_Table, 1);
92363       sqlite3Select(pParse, pSelect, &dest);
92364       sqlite3VdbeAddOp1(v, OP_Close, 1);
92365       if( pParse->nErr==0 ){
92366         pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
92367         if( pSelTab==0 ) return;
92368         assert( p->aCol==0 );
92369         p->nCol = pSelTab->nCol;
92370         p->aCol = pSelTab->aCol;
92371         pSelTab->nCol = 0;
92372         pSelTab->aCol = 0;
92373         sqlite3DeleteTable(db, pSelTab);
92374       }
92375     }
92376
92377     /* Compute the complete text of the CREATE statement */
92378     if( pSelect ){
92379       zStmt = createTableStmt(db, p);
92380     }else{
92381       Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
92382       n = (int)(pEnd2->z - pParse->sNameToken.z);
92383       if( pEnd2->z[0]!=';' ) n += pEnd2->n;
92384       zStmt = sqlite3MPrintf(db, 
92385           "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
92386       );
92387     }
92388
92389     /* A slot for the record has already been allocated in the 
92390     ** SQLITE_MASTER table.  We just need to update that slot with all
92391     ** the information we've collected.
92392     */
92393     sqlite3NestedParse(pParse,
92394       "UPDATE %Q.%s "
92395          "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
92396        "WHERE rowid=#%d",
92397       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
92398       zType,
92399       p->zName,
92400       p->zName,
92401       pParse->regRoot,
92402       zStmt,
92403       pParse->regRowid
92404     );
92405     sqlite3DbFree(db, zStmt);
92406     sqlite3ChangeCookie(pParse, iDb);
92407
92408 #ifndef SQLITE_OMIT_AUTOINCREMENT
92409     /* Check to see if we need to create an sqlite_sequence table for
92410     ** keeping track of autoincrement keys.
92411     */
92412     if( p->tabFlags & TF_Autoincrement ){
92413       Db *pDb = &db->aDb[iDb];
92414       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
92415       if( pDb->pSchema->pSeqTab==0 ){
92416         sqlite3NestedParse(pParse,
92417           "CREATE TABLE %Q.sqlite_sequence(name,seq)",
92418           pDb->zName
92419         );
92420       }
92421     }
92422 #endif
92423
92424     /* Reparse everything to update our internal data structures */
92425     sqlite3VdbeAddParseSchemaOp(v, iDb,
92426            sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
92427   }
92428
92429
92430   /* Add the table to the in-memory representation of the database.
92431   */
92432   if( db->init.busy ){
92433     Table *pOld;
92434     Schema *pSchema = p->pSchema;
92435     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
92436     pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
92437     if( pOld ){
92438       assert( p==pOld );  /* Malloc must have failed inside HashInsert() */
92439       db->mallocFailed = 1;
92440       return;
92441     }
92442     pParse->pNewTable = 0;
92443     db->flags |= SQLITE_InternChanges;
92444
92445 #ifndef SQLITE_OMIT_ALTERTABLE
92446     if( !p->pSelect ){
92447       const char *zName = (const char *)pParse->sNameToken.z;
92448       int nName;
92449       assert( !pSelect && pCons && pEnd );
92450       if( pCons->z==0 ){
92451         pCons = pEnd;
92452       }
92453       nName = (int)((const char *)pCons->z - zName);
92454       p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
92455     }
92456 #endif
92457   }
92458 }
92459
92460 #ifndef SQLITE_OMIT_VIEW
92461 /*
92462 ** The parser calls this routine in order to create a new VIEW
92463 */
92464 SQLITE_PRIVATE void sqlite3CreateView(
92465   Parse *pParse,     /* The parsing context */
92466   Token *pBegin,     /* The CREATE token that begins the statement */
92467   Token *pName1,     /* The token that holds the name of the view */
92468   Token *pName2,     /* The token that holds the name of the view */
92469   Select *pSelect,   /* A SELECT statement that will become the new view */
92470   int isTemp,        /* TRUE for a TEMPORARY view */
92471   int noErr          /* Suppress error messages if VIEW already exists */
92472 ){
92473   Table *p;
92474   int n;
92475   const char *z;
92476   Token sEnd;
92477   DbFixer sFix;
92478   Token *pName = 0;
92479   int iDb;
92480   sqlite3 *db = pParse->db;
92481
92482   if( pParse->nVar>0 ){
92483     sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
92484     sqlite3SelectDelete(db, pSelect);
92485     return;
92486   }
92487   sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
92488   p = pParse->pNewTable;
92489   if( p==0 || pParse->nErr ){
92490     sqlite3SelectDelete(db, pSelect);
92491     return;
92492   }
92493   sqlite3TwoPartName(pParse, pName1, pName2, &pName);
92494   iDb = sqlite3SchemaToIndex(db, p->pSchema);
92495   sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
92496   if( sqlite3FixSelect(&sFix, pSelect) ){
92497     sqlite3SelectDelete(db, pSelect);
92498     return;
92499   }
92500
92501   /* Make a copy of the entire SELECT statement that defines the view.
92502   ** This will force all the Expr.token.z values to be dynamically
92503   ** allocated rather than point to the input string - which means that
92504   ** they will persist after the current sqlite3_exec() call returns.
92505   */
92506   p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
92507   sqlite3SelectDelete(db, pSelect);
92508   if( db->mallocFailed ){
92509     return;
92510   }
92511   if( !db->init.busy ){
92512     sqlite3ViewGetColumnNames(pParse, p);
92513   }
92514
92515   /* Locate the end of the CREATE VIEW statement.  Make sEnd point to
92516   ** the end.
92517   */
92518   sEnd = pParse->sLastToken;
92519   if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
92520     sEnd.z += sEnd.n;
92521   }
92522   sEnd.n = 0;
92523   n = (int)(sEnd.z - pBegin->z);
92524   z = pBegin->z;
92525   while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
92526   sEnd.z = &z[n-1];
92527   sEnd.n = 1;
92528
92529   /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
92530   sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
92531   return;
92532 }
92533 #endif /* SQLITE_OMIT_VIEW */
92534
92535 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
92536 /*
92537 ** The Table structure pTable is really a VIEW.  Fill in the names of
92538 ** the columns of the view in the pTable structure.  Return the number
92539 ** of errors.  If an error is seen leave an error message in pParse->zErrMsg.
92540 */
92541 SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
92542   Table *pSelTab;   /* A fake table from which we get the result set */
92543   Select *pSel;     /* Copy of the SELECT that implements the view */
92544   int nErr = 0;     /* Number of errors encountered */
92545   int n;            /* Temporarily holds the number of cursors assigned */
92546   sqlite3 *db = pParse->db;  /* Database connection for malloc errors */
92547   sqlite3_xauth xAuth;       /* Saved xAuth pointer */
92548
92549   assert( pTable );
92550
92551 #ifndef SQLITE_OMIT_VIRTUALTABLE
92552   if( sqlite3VtabCallConnect(pParse, pTable) ){
92553     return SQLITE_ERROR;
92554   }
92555   if( IsVirtual(pTable) ) return 0;
92556 #endif
92557
92558 #ifndef SQLITE_OMIT_VIEW
92559   /* A positive nCol means the columns names for this view are
92560   ** already known.
92561   */
92562   if( pTable->nCol>0 ) return 0;
92563
92564   /* A negative nCol is a special marker meaning that we are currently
92565   ** trying to compute the column names.  If we enter this routine with
92566   ** a negative nCol, it means two or more views form a loop, like this:
92567   **
92568   **     CREATE VIEW one AS SELECT * FROM two;
92569   **     CREATE VIEW two AS SELECT * FROM one;
92570   **
92571   ** Actually, the error above is now caught prior to reaching this point.
92572   ** But the following test is still important as it does come up
92573   ** in the following:
92574   ** 
92575   **     CREATE TABLE main.ex1(a);
92576   **     CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
92577   **     SELECT * FROM temp.ex1;
92578   */
92579   if( pTable->nCol<0 ){
92580     sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
92581     return 1;
92582   }
92583   assert( pTable->nCol>=0 );
92584
92585   /* If we get this far, it means we need to compute the table names.
92586   ** Note that the call to sqlite3ResultSetOfSelect() will expand any
92587   ** "*" elements in the results set of the view and will assign cursors
92588   ** to the elements of the FROM clause.  But we do not want these changes
92589   ** to be permanent.  So the computation is done on a copy of the SELECT
92590   ** statement that defines the view.
92591   */
92592   assert( pTable->pSelect );
92593   pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
92594   if( pSel ){
92595     u8 enableLookaside = db->lookaside.bEnabled;
92596     n = pParse->nTab;
92597     sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
92598     pTable->nCol = -1;
92599     db->lookaside.bEnabled = 0;
92600 #ifndef SQLITE_OMIT_AUTHORIZATION
92601     xAuth = db->xAuth;
92602     db->xAuth = 0;
92603     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
92604     db->xAuth = xAuth;
92605 #else
92606     pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
92607 #endif
92608     db->lookaside.bEnabled = enableLookaside;
92609     pParse->nTab = n;
92610     if( pSelTab ){
92611       assert( pTable->aCol==0 );
92612       pTable->nCol = pSelTab->nCol;
92613       pTable->aCol = pSelTab->aCol;
92614       pSelTab->nCol = 0;
92615       pSelTab->aCol = 0;
92616       sqlite3DeleteTable(db, pSelTab);
92617       assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
92618       pTable->pSchema->schemaFlags |= DB_UnresetViews;
92619     }else{
92620       pTable->nCol = 0;
92621       nErr++;
92622     }
92623     sqlite3SelectDelete(db, pSel);
92624   } else {
92625     nErr++;
92626   }
92627 #endif /* SQLITE_OMIT_VIEW */
92628   return nErr;  
92629 }
92630 #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
92631
92632 #ifndef SQLITE_OMIT_VIEW
92633 /*
92634 ** Clear the column names from every VIEW in database idx.
92635 */
92636 static void sqliteViewResetAll(sqlite3 *db, int idx){
92637   HashElem *i;
92638   assert( sqlite3SchemaMutexHeld(db, idx, 0) );
92639   if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
92640   for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
92641     Table *pTab = sqliteHashData(i);
92642     if( pTab->pSelect ){
92643       sqliteDeleteColumnNames(db, pTab);
92644       pTab->aCol = 0;
92645       pTab->nCol = 0;
92646     }
92647   }
92648   DbClearProperty(db, idx, DB_UnresetViews);
92649 }
92650 #else
92651 # define sqliteViewResetAll(A,B)
92652 #endif /* SQLITE_OMIT_VIEW */
92653
92654 /*
92655 ** This function is called by the VDBE to adjust the internal schema
92656 ** used by SQLite when the btree layer moves a table root page. The
92657 ** root-page of a table or index in database iDb has changed from iFrom
92658 ** to iTo.
92659 **
92660 ** Ticket #1728:  The symbol table might still contain information
92661 ** on tables and/or indices that are the process of being deleted.
92662 ** If you are unlucky, one of those deleted indices or tables might
92663 ** have the same rootpage number as the real table or index that is
92664 ** being moved.  So we cannot stop searching after the first match 
92665 ** because the first match might be for one of the deleted indices
92666 ** or tables and not the table/index that is actually being moved.
92667 ** We must continue looping until all tables and indices with
92668 ** rootpage==iFrom have been converted to have a rootpage of iTo
92669 ** in order to be certain that we got the right one.
92670 */
92671 #ifndef SQLITE_OMIT_AUTOVACUUM
92672 SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
92673   HashElem *pElem;
92674   Hash *pHash;
92675   Db *pDb;
92676
92677   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
92678   pDb = &db->aDb[iDb];
92679   pHash = &pDb->pSchema->tblHash;
92680   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
92681     Table *pTab = sqliteHashData(pElem);
92682     if( pTab->tnum==iFrom ){
92683       pTab->tnum = iTo;
92684     }
92685   }
92686   pHash = &pDb->pSchema->idxHash;
92687   for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
92688     Index *pIdx = sqliteHashData(pElem);
92689     if( pIdx->tnum==iFrom ){
92690       pIdx->tnum = iTo;
92691     }
92692   }
92693 }
92694 #endif
92695
92696 /*
92697 ** Write code to erase the table with root-page iTable from database iDb.
92698 ** Also write code to modify the sqlite_master table and internal schema
92699 ** if a root-page of another table is moved by the btree-layer whilst
92700 ** erasing iTable (this can happen with an auto-vacuum database).
92701 */ 
92702 static void destroyRootPage(Parse *pParse, int iTable, int iDb){
92703   Vdbe *v = sqlite3GetVdbe(pParse);
92704   int r1 = sqlite3GetTempReg(pParse);
92705   sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
92706   sqlite3MayAbort(pParse);
92707 #ifndef SQLITE_OMIT_AUTOVACUUM
92708   /* OP_Destroy stores an in integer r1. If this integer
92709   ** is non-zero, then it is the root page number of a table moved to
92710   ** location iTable. The following code modifies the sqlite_master table to
92711   ** reflect this.
92712   **
92713   ** The "#NNN" in the SQL is a special constant that means whatever value
92714   ** is in register NNN.  See grammar rules associated with the TK_REGISTER
92715   ** token for additional information.
92716   */
92717   sqlite3NestedParse(pParse, 
92718      "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
92719      pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
92720 #endif
92721   sqlite3ReleaseTempReg(pParse, r1);
92722 }
92723
92724 /*
92725 ** Write VDBE code to erase table pTab and all associated indices on disk.
92726 ** Code to update the sqlite_master tables and internal schema definitions
92727 ** in case a root-page belonging to another table is moved by the btree layer
92728 ** is also added (this can happen with an auto-vacuum database).
92729 */
92730 static void destroyTable(Parse *pParse, Table *pTab){
92731 #ifdef SQLITE_OMIT_AUTOVACUUM
92732   Index *pIdx;
92733   int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
92734   destroyRootPage(pParse, pTab->tnum, iDb);
92735   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
92736     destroyRootPage(pParse, pIdx->tnum, iDb);
92737   }
92738 #else
92739   /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
92740   ** is not defined), then it is important to call OP_Destroy on the
92741   ** table and index root-pages in order, starting with the numerically 
92742   ** largest root-page number. This guarantees that none of the root-pages
92743   ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
92744   ** following were coded:
92745   **
92746   ** OP_Destroy 4 0
92747   ** ...
92748   ** OP_Destroy 5 0
92749   **
92750   ** and root page 5 happened to be the largest root-page number in the
92751   ** database, then root page 5 would be moved to page 4 by the 
92752   ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
92753   ** a free-list page.
92754   */
92755   int iTab = pTab->tnum;
92756   int iDestroyed = 0;
92757
92758   while( 1 ){
92759     Index *pIdx;
92760     int iLargest = 0;
92761
92762     if( iDestroyed==0 || iTab<iDestroyed ){
92763       iLargest = iTab;
92764     }
92765     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
92766       int iIdx = pIdx->tnum;
92767       assert( pIdx->pSchema==pTab->pSchema );
92768       if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
92769         iLargest = iIdx;
92770       }
92771     }
92772     if( iLargest==0 ){
92773       return;
92774     }else{
92775       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
92776       assert( iDb>=0 && iDb<pParse->db->nDb );
92777       destroyRootPage(pParse, iLargest, iDb);
92778       iDestroyed = iLargest;
92779     }
92780   }
92781 #endif
92782 }
92783
92784 /*
92785 ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
92786 ** after a DROP INDEX or DROP TABLE command.
92787 */
92788 static void sqlite3ClearStatTables(
92789   Parse *pParse,         /* The parsing context */
92790   int iDb,               /* The database number */
92791   const char *zType,     /* "idx" or "tbl" */
92792   const char *zName      /* Name of index or table */
92793 ){
92794   int i;
92795   const char *zDbName = pParse->db->aDb[iDb].zName;
92796   for(i=1; i<=4; i++){
92797     char zTab[24];
92798     sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
92799     if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
92800       sqlite3NestedParse(pParse,
92801         "DELETE FROM %Q.%s WHERE %s=%Q",
92802         zDbName, zTab, zType, zName
92803       );
92804     }
92805   }
92806 }
92807
92808 /*
92809 ** Generate code to drop a table.
92810 */
92811 SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
92812   Vdbe *v;
92813   sqlite3 *db = pParse->db;
92814   Trigger *pTrigger;
92815   Db *pDb = &db->aDb[iDb];
92816
92817   v = sqlite3GetVdbe(pParse);
92818   assert( v!=0 );
92819   sqlite3BeginWriteOperation(pParse, 1, iDb);
92820
92821 #ifndef SQLITE_OMIT_VIRTUALTABLE
92822   if( IsVirtual(pTab) ){
92823     sqlite3VdbeAddOp0(v, OP_VBegin);
92824   }
92825 #endif
92826
92827   /* Drop all triggers associated with the table being dropped. Code
92828   ** is generated to remove entries from sqlite_master and/or
92829   ** sqlite_temp_master if required.
92830   */
92831   pTrigger = sqlite3TriggerList(pParse, pTab);
92832   while( pTrigger ){
92833     assert( pTrigger->pSchema==pTab->pSchema || 
92834         pTrigger->pSchema==db->aDb[1].pSchema );
92835     sqlite3DropTriggerPtr(pParse, pTrigger);
92836     pTrigger = pTrigger->pNext;
92837   }
92838
92839 #ifndef SQLITE_OMIT_AUTOINCREMENT
92840   /* Remove any entries of the sqlite_sequence table associated with
92841   ** the table being dropped. This is done before the table is dropped
92842   ** at the btree level, in case the sqlite_sequence table needs to
92843   ** move as a result of the drop (can happen in auto-vacuum mode).
92844   */
92845   if( pTab->tabFlags & TF_Autoincrement ){
92846     sqlite3NestedParse(pParse,
92847       "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
92848       pDb->zName, pTab->zName
92849     );
92850   }
92851 #endif
92852
92853   /* Drop all SQLITE_MASTER table and index entries that refer to the
92854   ** table. The program name loops through the master table and deletes
92855   ** every row that refers to a table of the same name as the one being
92856   ** dropped. Triggers are handled separately because a trigger can be
92857   ** created in the temp database that refers to a table in another
92858   ** database.
92859   */
92860   sqlite3NestedParse(pParse, 
92861       "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
92862       pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
92863   if( !isView && !IsVirtual(pTab) ){
92864     destroyTable(pParse, pTab);
92865   }
92866
92867   /* Remove the table entry from SQLite's internal schema and modify
92868   ** the schema cookie.
92869   */
92870   if( IsVirtual(pTab) ){
92871     sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
92872   }
92873   sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
92874   sqlite3ChangeCookie(pParse, iDb);
92875   sqliteViewResetAll(db, iDb);
92876 }
92877
92878 /*
92879 ** This routine is called to do the work of a DROP TABLE statement.
92880 ** pName is the name of the table to be dropped.
92881 */
92882 SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
92883   Table *pTab;
92884   Vdbe *v;
92885   sqlite3 *db = pParse->db;
92886   int iDb;
92887
92888   if( db->mallocFailed ){
92889     goto exit_drop_table;
92890   }
92891   assert( pParse->nErr==0 );
92892   assert( pName->nSrc==1 );
92893   if( noErr ) db->suppressErr++;
92894   pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
92895   if( noErr ) db->suppressErr--;
92896
92897   if( pTab==0 ){
92898     if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
92899     goto exit_drop_table;
92900   }
92901   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
92902   assert( iDb>=0 && iDb<db->nDb );
92903
92904   /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
92905   ** it is initialized.
92906   */
92907   if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
92908     goto exit_drop_table;
92909   }
92910 #ifndef SQLITE_OMIT_AUTHORIZATION
92911   {
92912     int code;
92913     const char *zTab = SCHEMA_TABLE(iDb);
92914     const char *zDb = db->aDb[iDb].zName;
92915     const char *zArg2 = 0;
92916     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
92917       goto exit_drop_table;
92918     }
92919     if( isView ){
92920       if( !OMIT_TEMPDB && iDb==1 ){
92921         code = SQLITE_DROP_TEMP_VIEW;
92922       }else{
92923         code = SQLITE_DROP_VIEW;
92924       }
92925 #ifndef SQLITE_OMIT_VIRTUALTABLE
92926     }else if( IsVirtual(pTab) ){
92927       code = SQLITE_DROP_VTABLE;
92928       zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
92929 #endif
92930     }else{
92931       if( !OMIT_TEMPDB && iDb==1 ){
92932         code = SQLITE_DROP_TEMP_TABLE;
92933       }else{
92934         code = SQLITE_DROP_TABLE;
92935       }
92936     }
92937     if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
92938       goto exit_drop_table;
92939     }
92940     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
92941       goto exit_drop_table;
92942     }
92943   }
92944 #endif
92945   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
92946     && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
92947     sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
92948     goto exit_drop_table;
92949   }
92950
92951 #ifndef SQLITE_OMIT_VIEW
92952   /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
92953   ** on a table.
92954   */
92955   if( isView && pTab->pSelect==0 ){
92956     sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
92957     goto exit_drop_table;
92958   }
92959   if( !isView && pTab->pSelect ){
92960     sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
92961     goto exit_drop_table;
92962   }
92963 #endif
92964
92965   /* Generate code to remove the table from the master table
92966   ** on disk.
92967   */
92968   v = sqlite3GetVdbe(pParse);
92969   if( v ){
92970     sqlite3BeginWriteOperation(pParse, 1, iDb);
92971     sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
92972     sqlite3FkDropTable(pParse, pName, pTab);
92973     sqlite3CodeDropTable(pParse, pTab, iDb, isView);
92974   }
92975
92976 exit_drop_table:
92977   sqlite3SrcListDelete(db, pName);
92978 }
92979
92980 /*
92981 ** This routine is called to create a new foreign key on the table
92982 ** currently under construction.  pFromCol determines which columns
92983 ** in the current table point to the foreign key.  If pFromCol==0 then
92984 ** connect the key to the last column inserted.  pTo is the name of
92985 ** the table referred to (a.k.a the "parent" table).  pToCol is a list
92986 ** of tables in the parent pTo table.  flags contains all
92987 ** information about the conflict resolution algorithms specified
92988 ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
92989 **
92990 ** An FKey structure is created and added to the table currently
92991 ** under construction in the pParse->pNewTable field.
92992 **
92993 ** The foreign key is set for IMMEDIATE processing.  A subsequent call
92994 ** to sqlite3DeferForeignKey() might change this to DEFERRED.
92995 */
92996 SQLITE_PRIVATE void sqlite3CreateForeignKey(
92997   Parse *pParse,       /* Parsing context */
92998   ExprList *pFromCol,  /* Columns in this table that point to other table */
92999   Token *pTo,          /* Name of the other table */
93000   ExprList *pToCol,    /* Columns in the other table */
93001   int flags            /* Conflict resolution algorithms. */
93002 ){
93003   sqlite3 *db = pParse->db;
93004 #ifndef SQLITE_OMIT_FOREIGN_KEY
93005   FKey *pFKey = 0;
93006   FKey *pNextTo;
93007   Table *p = pParse->pNewTable;
93008   int nByte;
93009   int i;
93010   int nCol;
93011   char *z;
93012
93013   assert( pTo!=0 );
93014   if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
93015   if( pFromCol==0 ){
93016     int iCol = p->nCol-1;
93017     if( NEVER(iCol<0) ) goto fk_end;
93018     if( pToCol && pToCol->nExpr!=1 ){
93019       sqlite3ErrorMsg(pParse, "foreign key on %s"
93020          " should reference only one column of table %T",
93021          p->aCol[iCol].zName, pTo);
93022       goto fk_end;
93023     }
93024     nCol = 1;
93025   }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
93026     sqlite3ErrorMsg(pParse,
93027         "number of columns in foreign key does not match the number of "
93028         "columns in the referenced table");
93029     goto fk_end;
93030   }else{
93031     nCol = pFromCol->nExpr;
93032   }
93033   nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
93034   if( pToCol ){
93035     for(i=0; i<pToCol->nExpr; i++){
93036       nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
93037     }
93038   }
93039   pFKey = sqlite3DbMallocZero(db, nByte );
93040   if( pFKey==0 ){
93041     goto fk_end;
93042   }
93043   pFKey->pFrom = p;
93044   pFKey->pNextFrom = p->pFKey;
93045   z = (char*)&pFKey->aCol[nCol];
93046   pFKey->zTo = z;
93047   memcpy(z, pTo->z, pTo->n);
93048   z[pTo->n] = 0;
93049   sqlite3Dequote(z);
93050   z += pTo->n+1;
93051   pFKey->nCol = nCol;
93052   if( pFromCol==0 ){
93053     pFKey->aCol[0].iFrom = p->nCol-1;
93054   }else{
93055     for(i=0; i<nCol; i++){
93056       int j;
93057       for(j=0; j<p->nCol; j++){
93058         if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
93059           pFKey->aCol[i].iFrom = j;
93060           break;
93061         }
93062       }
93063       if( j>=p->nCol ){
93064         sqlite3ErrorMsg(pParse, 
93065           "unknown column \"%s\" in foreign key definition", 
93066           pFromCol->a[i].zName);
93067         goto fk_end;
93068       }
93069     }
93070   }
93071   if( pToCol ){
93072     for(i=0; i<nCol; i++){
93073       int n = sqlite3Strlen30(pToCol->a[i].zName);
93074       pFKey->aCol[i].zCol = z;
93075       memcpy(z, pToCol->a[i].zName, n);
93076       z[n] = 0;
93077       z += n+1;
93078     }
93079   }
93080   pFKey->isDeferred = 0;
93081   pFKey->aAction[0] = (u8)(flags & 0xff);            /* ON DELETE action */
93082   pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff);    /* ON UPDATE action */
93083
93084   assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
93085   pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash, 
93086       pFKey->zTo, (void *)pFKey
93087   );
93088   if( pNextTo==pFKey ){
93089     db->mallocFailed = 1;
93090     goto fk_end;
93091   }
93092   if( pNextTo ){
93093     assert( pNextTo->pPrevTo==0 );
93094     pFKey->pNextTo = pNextTo;
93095     pNextTo->pPrevTo = pFKey;
93096   }
93097
93098   /* Link the foreign key to the table as the last step.
93099   */
93100   p->pFKey = pFKey;
93101   pFKey = 0;
93102
93103 fk_end:
93104   sqlite3DbFree(db, pFKey);
93105 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
93106   sqlite3ExprListDelete(db, pFromCol);
93107   sqlite3ExprListDelete(db, pToCol);
93108 }
93109
93110 /*
93111 ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
93112 ** clause is seen as part of a foreign key definition.  The isDeferred
93113 ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
93114 ** The behavior of the most recently created foreign key is adjusted
93115 ** accordingly.
93116 */
93117 SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
93118 #ifndef SQLITE_OMIT_FOREIGN_KEY
93119   Table *pTab;
93120   FKey *pFKey;
93121   if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
93122   assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
93123   pFKey->isDeferred = (u8)isDeferred;
93124 #endif
93125 }
93126
93127 /*
93128 ** Generate code that will erase and refill index *pIdx.  This is
93129 ** used to initialize a newly created index or to recompute the
93130 ** content of an index in response to a REINDEX command.
93131 **
93132 ** if memRootPage is not negative, it means that the index is newly
93133 ** created.  The register specified by memRootPage contains the
93134 ** root page number of the index.  If memRootPage is negative, then
93135 ** the index already exists and must be cleared before being refilled and
93136 ** the root page number of the index is taken from pIndex->tnum.
93137 */
93138 static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
93139   Table *pTab = pIndex->pTable;  /* The table that is indexed */
93140   int iTab = pParse->nTab++;     /* Btree cursor used for pTab */
93141   int iIdx = pParse->nTab++;     /* Btree cursor used for pIndex */
93142   int iSorter;                   /* Cursor opened by OpenSorter (if in use) */
93143   int addr1;                     /* Address of top of loop */
93144   int addr2;                     /* Address to jump to for next iteration */
93145   int tnum;                      /* Root page of index */
93146   int iPartIdxLabel;             /* Jump to this label to skip a row */
93147   Vdbe *v;                       /* Generate code into this virtual machine */
93148   KeyInfo *pKey;                 /* KeyInfo for index */
93149   int regRecord;                 /* Register holding assembled index record */
93150   sqlite3 *db = pParse->db;      /* The database connection */
93151   int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
93152
93153 #ifndef SQLITE_OMIT_AUTHORIZATION
93154   if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
93155       db->aDb[iDb].zName ) ){
93156     return;
93157   }
93158 #endif
93159
93160   /* Require a write-lock on the table to perform this operation */
93161   sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
93162
93163   v = sqlite3GetVdbe(pParse);
93164   if( v==0 ) return;
93165   if( memRootPage>=0 ){
93166     tnum = memRootPage;
93167   }else{
93168     tnum = pIndex->tnum;
93169   }
93170   pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
93171
93172   /* Open the sorter cursor if we are to use one. */
93173   iSorter = pParse->nTab++;
93174   sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
93175                     sqlite3KeyInfoRef(pKey), P4_KEYINFO);
93176
93177   /* Open the table. Loop through all rows of the table, inserting index
93178   ** records into the sorter. */
93179   sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
93180   addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
93181   regRecord = sqlite3GetTempReg(pParse);
93182
93183   sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
93184   sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
93185   sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
93186   sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
93187   sqlite3VdbeJumpHere(v, addr1);
93188   if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
93189   sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb, 
93190                     (char *)pKey, P4_KEYINFO);
93191   sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
93192
93193   addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
93194   assert( pKey!=0 || db->mallocFailed || pParse->nErr );
93195   if( IsUniqueIndex(pIndex) && pKey!=0 ){
93196     int j2 = sqlite3VdbeCurrentAddr(v) + 3;
93197     sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
93198     addr2 = sqlite3VdbeCurrentAddr(v);
93199     sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
93200                          pIndex->nKeyCol); VdbeCoverage(v);
93201     sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
93202   }else{
93203     addr2 = sqlite3VdbeCurrentAddr(v);
93204   }
93205   sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
93206   sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
93207   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
93208   sqlite3ReleaseTempReg(pParse, regRecord);
93209   sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
93210   sqlite3VdbeJumpHere(v, addr1);
93211
93212   sqlite3VdbeAddOp1(v, OP_Close, iTab);
93213   sqlite3VdbeAddOp1(v, OP_Close, iIdx);
93214   sqlite3VdbeAddOp1(v, OP_Close, iSorter);
93215 }
93216
93217 /*
93218 ** Allocate heap space to hold an Index object with nCol columns.
93219 **
93220 ** Increase the allocation size to provide an extra nExtra bytes
93221 ** of 8-byte aligned space after the Index object and return a
93222 ** pointer to this extra space in *ppExtra.
93223 */
93224 SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
93225   sqlite3 *db,         /* Database connection */
93226   i16 nCol,            /* Total number of columns in the index */
93227   int nExtra,          /* Number of bytes of extra space to alloc */
93228   char **ppExtra       /* Pointer to the "extra" space */
93229 ){
93230   Index *p;            /* Allocated index object */
93231   int nByte;           /* Bytes of space for Index object + arrays */
93232
93233   nByte = ROUND8(sizeof(Index)) +              /* Index structure  */
93234           ROUND8(sizeof(char*)*nCol) +         /* Index.azColl     */
93235           ROUND8(sizeof(LogEst)*(nCol+1) +     /* Index.aiRowLogEst   */
93236                  sizeof(i16)*nCol +            /* Index.aiColumn   */
93237                  sizeof(u8)*nCol);             /* Index.aSortOrder */
93238   p = sqlite3DbMallocZero(db, nByte + nExtra);
93239   if( p ){
93240     char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
93241     p->azColl = (char**)pExtra;       pExtra += ROUND8(sizeof(char*)*nCol);
93242     p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
93243     p->aiColumn = (i16*)pExtra;       pExtra += sizeof(i16)*nCol;
93244     p->aSortOrder = (u8*)pExtra;
93245     p->nColumn = nCol;
93246     p->nKeyCol = nCol - 1;
93247     *ppExtra = ((char*)p) + nByte;
93248   }
93249   return p;
93250 }
93251
93252 /*
93253 ** Create a new index for an SQL table.  pName1.pName2 is the name of the index 
93254 ** and pTblList is the name of the table that is to be indexed.  Both will 
93255 ** be NULL for a primary key or an index that is created to satisfy a
93256 ** UNIQUE constraint.  If pTable and pIndex are NULL, use pParse->pNewTable
93257 ** as the table to be indexed.  pParse->pNewTable is a table that is
93258 ** currently being constructed by a CREATE TABLE statement.
93259 **
93260 ** pList is a list of columns to be indexed.  pList will be NULL if this
93261 ** is a primary key or unique-constraint on the most recent column added
93262 ** to the table currently under construction.  
93263 **
93264 ** If the index is created successfully, return a pointer to the new Index
93265 ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
93266 ** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
93267 */
93268 SQLITE_PRIVATE Index *sqlite3CreateIndex(
93269   Parse *pParse,     /* All information about this parse */
93270   Token *pName1,     /* First part of index name. May be NULL */
93271   Token *pName2,     /* Second part of index name. May be NULL */
93272   SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
93273   ExprList *pList,   /* A list of columns to be indexed */
93274   int onError,       /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
93275   Token *pStart,     /* The CREATE token that begins this statement */
93276   Expr *pPIWhere,    /* WHERE clause for partial indices */
93277   int sortOrder,     /* Sort order of primary key when pList==NULL */
93278   int ifNotExist     /* Omit error if index already exists */
93279 ){
93280   Index *pRet = 0;     /* Pointer to return */
93281   Table *pTab = 0;     /* Table to be indexed */
93282   Index *pIndex = 0;   /* The index to be created */
93283   char *zName = 0;     /* Name of the index */
93284   int nName;           /* Number of characters in zName */
93285   int i, j;
93286   DbFixer sFix;        /* For assigning database names to pTable */
93287   int sortOrderMask;   /* 1 to honor DESC in index.  0 to ignore. */
93288   sqlite3 *db = pParse->db;
93289   Db *pDb;             /* The specific table containing the indexed database */
93290   int iDb;             /* Index of the database that is being written */
93291   Token *pName = 0;    /* Unqualified name of the index to create */
93292   struct ExprList_item *pListItem; /* For looping over pList */
93293   const Column *pTabCol;           /* A column in the table */
93294   int nExtra = 0;                  /* Space allocated for zExtra[] */
93295   int nExtraCol;                   /* Number of extra columns needed */
93296   char *zExtra = 0;                /* Extra space after the Index object */
93297   Index *pPk = 0;      /* PRIMARY KEY index for WITHOUT ROWID tables */
93298
93299   assert( pParse->nErr==0 );      /* Never called with prior errors */
93300   if( db->mallocFailed || IN_DECLARE_VTAB ){
93301     goto exit_create_index;
93302   }
93303   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
93304     goto exit_create_index;
93305   }
93306
93307   /*
93308   ** Find the table that is to be indexed.  Return early if not found.
93309   */
93310   if( pTblName!=0 ){
93311
93312     /* Use the two-part index name to determine the database 
93313     ** to search for the table. 'Fix' the table name to this db
93314     ** before looking up the table.
93315     */
93316     assert( pName1 && pName2 );
93317     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
93318     if( iDb<0 ) goto exit_create_index;
93319     assert( pName && pName->z );
93320
93321 #ifndef SQLITE_OMIT_TEMPDB
93322     /* If the index name was unqualified, check if the table
93323     ** is a temp table. If so, set the database to 1. Do not do this
93324     ** if initialising a database schema.
93325     */
93326     if( !db->init.busy ){
93327       pTab = sqlite3SrcListLookup(pParse, pTblName);
93328       if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
93329         iDb = 1;
93330       }
93331     }
93332 #endif
93333
93334     sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
93335     if( sqlite3FixSrcList(&sFix, pTblName) ){
93336       /* Because the parser constructs pTblName from a single identifier,
93337       ** sqlite3FixSrcList can never fail. */
93338       assert(0);
93339     }
93340     pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
93341     assert( db->mallocFailed==0 || pTab==0 );
93342     if( pTab==0 ) goto exit_create_index;
93343     if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
93344       sqlite3ErrorMsg(pParse, 
93345            "cannot create a TEMP index on non-TEMP table \"%s\"",
93346            pTab->zName);
93347       goto exit_create_index;
93348     }
93349     if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
93350   }else{
93351     assert( pName==0 );
93352     assert( pStart==0 );
93353     pTab = pParse->pNewTable;
93354     if( !pTab ) goto exit_create_index;
93355     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
93356   }
93357   pDb = &db->aDb[iDb];
93358
93359   assert( pTab!=0 );
93360   assert( pParse->nErr==0 );
93361   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 
93362        && db->init.busy==0
93363 #if SQLITE_USER_AUTHENTICATION
93364        && sqlite3UserAuthTable(pTab->zName)==0
93365 #endif
93366        && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
93367     sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
93368     goto exit_create_index;
93369   }
93370 #ifndef SQLITE_OMIT_VIEW
93371   if( pTab->pSelect ){
93372     sqlite3ErrorMsg(pParse, "views may not be indexed");
93373     goto exit_create_index;
93374   }
93375 #endif
93376 #ifndef SQLITE_OMIT_VIRTUALTABLE
93377   if( IsVirtual(pTab) ){
93378     sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
93379     goto exit_create_index;
93380   }
93381 #endif
93382
93383   /*
93384   ** Find the name of the index.  Make sure there is not already another
93385   ** index or table with the same name.  
93386   **
93387   ** Exception:  If we are reading the names of permanent indices from the
93388   ** sqlite_master table (because some other process changed the schema) and
93389   ** one of the index names collides with the name of a temporary table or
93390   ** index, then we will continue to process this index.
93391   **
93392   ** If pName==0 it means that we are
93393   ** dealing with a primary key or UNIQUE constraint.  We have to invent our
93394   ** own name.
93395   */
93396   if( pName ){
93397     zName = sqlite3NameFromToken(db, pName);
93398     if( zName==0 ) goto exit_create_index;
93399     assert( pName->z!=0 );
93400     if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
93401       goto exit_create_index;
93402     }
93403     if( !db->init.busy ){
93404       if( sqlite3FindTable(db, zName, 0)!=0 ){
93405         sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
93406         goto exit_create_index;
93407       }
93408     }
93409     if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
93410       if( !ifNotExist ){
93411         sqlite3ErrorMsg(pParse, "index %s already exists", zName);
93412       }else{
93413         assert( !db->init.busy );
93414         sqlite3CodeVerifySchema(pParse, iDb);
93415       }
93416       goto exit_create_index;
93417     }
93418   }else{
93419     int n;
93420     Index *pLoop;
93421     for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
93422     zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
93423     if( zName==0 ){
93424       goto exit_create_index;
93425     }
93426   }
93427
93428   /* Check for authorization to create an index.
93429   */
93430 #ifndef SQLITE_OMIT_AUTHORIZATION
93431   {
93432     const char *zDb = pDb->zName;
93433     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
93434       goto exit_create_index;
93435     }
93436     i = SQLITE_CREATE_INDEX;
93437     if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
93438     if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
93439       goto exit_create_index;
93440     }
93441   }
93442 #endif
93443
93444   /* If pList==0, it means this routine was called to make a primary
93445   ** key out of the last column added to the table under construction.
93446   ** So create a fake list to simulate this.
93447   */
93448   if( pList==0 ){
93449     pList = sqlite3ExprListAppend(pParse, 0, 0);
93450     if( pList==0 ) goto exit_create_index;
93451     pList->a[0].zName = sqlite3DbStrDup(pParse->db,
93452                                         pTab->aCol[pTab->nCol-1].zName);
93453     pList->a[0].sortOrder = (u8)sortOrder;
93454   }
93455
93456   /* Figure out how many bytes of space are required to store explicitly
93457   ** specified collation sequence names.
93458   */
93459   for(i=0; i<pList->nExpr; i++){
93460     Expr *pExpr = pList->a[i].pExpr;
93461     if( pExpr ){
93462       assert( pExpr->op==TK_COLLATE );
93463       nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
93464     }
93465   }
93466
93467   /* 
93468   ** Allocate the index structure. 
93469   */
93470   nName = sqlite3Strlen30(zName);
93471   nExtraCol = pPk ? pPk->nKeyCol : 1;
93472   pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
93473                                       nName + nExtra + 1, &zExtra);
93474   if( db->mallocFailed ){
93475     goto exit_create_index;
93476   }
93477   assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
93478   assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
93479   pIndex->zName = zExtra;
93480   zExtra += nName + 1;
93481   memcpy(pIndex->zName, zName, nName+1);
93482   pIndex->pTable = pTab;
93483   pIndex->onError = (u8)onError;
93484   pIndex->uniqNotNull = onError!=OE_None;
93485   pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
93486   pIndex->pSchema = db->aDb[iDb].pSchema;
93487   pIndex->nKeyCol = pList->nExpr;
93488   if( pPIWhere ){
93489     sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
93490     pIndex->pPartIdxWhere = pPIWhere;
93491     pPIWhere = 0;
93492   }
93493   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
93494
93495   /* Check to see if we should honor DESC requests on index columns
93496   */
93497   if( pDb->pSchema->file_format>=4 ){
93498     sortOrderMask = -1;   /* Honor DESC */
93499   }else{
93500     sortOrderMask = 0;    /* Ignore DESC */
93501   }
93502
93503   /* Scan the names of the columns of the table to be indexed and
93504   ** load the column indices into the Index structure.  Report an error
93505   ** if any column is not found.
93506   **
93507   ** TODO:  Add a test to make sure that the same column is not named
93508   ** more than once within the same index.  Only the first instance of
93509   ** the column will ever be used by the optimizer.  Note that using the
93510   ** same column more than once cannot be an error because that would 
93511   ** break backwards compatibility - it needs to be a warning.
93512   */
93513   for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
93514     const char *zColName = pListItem->zName;
93515     int requestedSortOrder;
93516     char *zColl;                   /* Collation sequence name */
93517
93518     for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
93519       if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
93520     }
93521     if( j>=pTab->nCol ){
93522       sqlite3ErrorMsg(pParse, "table %s has no column named %s",
93523         pTab->zName, zColName);
93524       pParse->checkSchema = 1;
93525       goto exit_create_index;
93526     }
93527     assert( j<=0x7fff );
93528     pIndex->aiColumn[i] = (i16)j;
93529     if( pListItem->pExpr ){
93530       int nColl;
93531       assert( pListItem->pExpr->op==TK_COLLATE );
93532       zColl = pListItem->pExpr->u.zToken;
93533       nColl = sqlite3Strlen30(zColl) + 1;
93534       assert( nExtra>=nColl );
93535       memcpy(zExtra, zColl, nColl);
93536       zColl = zExtra;
93537       zExtra += nColl;
93538       nExtra -= nColl;
93539     }else{
93540       zColl = pTab->aCol[j].zColl;
93541       if( !zColl ) zColl = "BINARY";
93542     }
93543     if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
93544       goto exit_create_index;
93545     }
93546     pIndex->azColl[i] = zColl;
93547     requestedSortOrder = pListItem->sortOrder & sortOrderMask;
93548     pIndex->aSortOrder[i] = (u8)requestedSortOrder;
93549     if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
93550   }
93551   if( pPk ){
93552     for(j=0; j<pPk->nKeyCol; j++){
93553       int x = pPk->aiColumn[j];
93554       if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
93555         pIndex->nColumn--; 
93556       }else{
93557         pIndex->aiColumn[i] = x;
93558         pIndex->azColl[i] = pPk->azColl[j];
93559         pIndex->aSortOrder[i] = pPk->aSortOrder[j];
93560         i++;
93561       }
93562     }
93563     assert( i==pIndex->nColumn );
93564   }else{
93565     pIndex->aiColumn[i] = -1;
93566     pIndex->azColl[i] = "BINARY";
93567   }
93568   sqlite3DefaultRowEst(pIndex);
93569   if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
93570
93571   if( pTab==pParse->pNewTable ){
93572     /* This routine has been called to create an automatic index as a
93573     ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
93574     ** a PRIMARY KEY or UNIQUE clause following the column definitions.
93575     ** i.e. one of:
93576     **
93577     ** CREATE TABLE t(x PRIMARY KEY, y);
93578     ** CREATE TABLE t(x, y, UNIQUE(x, y));
93579     **
93580     ** Either way, check to see if the table already has such an index. If
93581     ** so, don't bother creating this one. This only applies to
93582     ** automatically created indices. Users can do as they wish with
93583     ** explicit indices.
93584     **
93585     ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
93586     ** (and thus suppressing the second one) even if they have different
93587     ** sort orders.
93588     **
93589     ** If there are different collating sequences or if the columns of
93590     ** the constraint occur in different orders, then the constraints are
93591     ** considered distinct and both result in separate indices.
93592     */
93593     Index *pIdx;
93594     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
93595       int k;
93596       assert( IsUniqueIndex(pIdx) );
93597       assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
93598       assert( IsUniqueIndex(pIndex) );
93599
93600       if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
93601       for(k=0; k<pIdx->nKeyCol; k++){
93602         const char *z1;
93603         const char *z2;
93604         if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
93605         z1 = pIdx->azColl[k];
93606         z2 = pIndex->azColl[k];
93607         if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
93608       }
93609       if( k==pIdx->nKeyCol ){
93610         if( pIdx->onError!=pIndex->onError ){
93611           /* This constraint creates the same index as a previous
93612           ** constraint specified somewhere in the CREATE TABLE statement.
93613           ** However the ON CONFLICT clauses are different. If both this 
93614           ** constraint and the previous equivalent constraint have explicit
93615           ** ON CONFLICT clauses this is an error. Otherwise, use the
93616           ** explicitly specified behavior for the index.
93617           */
93618           if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
93619             sqlite3ErrorMsg(pParse, 
93620                 "conflicting ON CONFLICT clauses specified", 0);
93621           }
93622           if( pIdx->onError==OE_Default ){
93623             pIdx->onError = pIndex->onError;
93624           }
93625         }
93626         pRet = pIdx;
93627         goto exit_create_index;
93628       }
93629     }
93630   }
93631
93632   /* Link the new Index structure to its table and to the other
93633   ** in-memory database structures. 
93634   */
93635   if( db->init.busy ){
93636     Index *p;
93637     assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
93638     p = sqlite3HashInsert(&pIndex->pSchema->idxHash, 
93639                           pIndex->zName, pIndex);
93640     if( p ){
93641       assert( p==pIndex );  /* Malloc must have failed */
93642       db->mallocFailed = 1;
93643       goto exit_create_index;
93644     }
93645     db->flags |= SQLITE_InternChanges;
93646     if( pTblName!=0 ){
93647       pIndex->tnum = db->init.newTnum;
93648     }
93649   }
93650
93651   /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
93652   ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
93653   ** emit code to allocate the index rootpage on disk and make an entry for
93654   ** the index in the sqlite_master table and populate the index with
93655   ** content.  But, do not do this if we are simply reading the sqlite_master
93656   ** table to parse the schema, or if this index is the PRIMARY KEY index
93657   ** of a WITHOUT ROWID table.
93658   **
93659   ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
93660   ** or UNIQUE index in a CREATE TABLE statement.  Since the table
93661   ** has just been created, it contains no data and the index initialization
93662   ** step can be skipped.
93663   */
93664   else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
93665     Vdbe *v;
93666     char *zStmt;
93667     int iMem = ++pParse->nMem;
93668
93669     v = sqlite3GetVdbe(pParse);
93670     if( v==0 ) goto exit_create_index;
93671
93672
93673     /* Create the rootpage for the index
93674     */
93675     sqlite3BeginWriteOperation(pParse, 1, iDb);
93676     sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
93677
93678     /* Gather the complete text of the CREATE INDEX statement into
93679     ** the zStmt variable
93680     */
93681     if( pStart ){
93682       int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
93683       if( pName->z[n-1]==';' ) n--;
93684       /* A named index with an explicit CREATE INDEX statement */
93685       zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
93686         onError==OE_None ? "" : " UNIQUE", n, pName->z);
93687     }else{
93688       /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
93689       /* zStmt = sqlite3MPrintf(""); */
93690       zStmt = 0;
93691     }
93692
93693     /* Add an entry in sqlite_master for this index
93694     */
93695     sqlite3NestedParse(pParse, 
93696         "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
93697         db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
93698         pIndex->zName,
93699         pTab->zName,
93700         iMem,
93701         zStmt
93702     );
93703     sqlite3DbFree(db, zStmt);
93704
93705     /* Fill the index with data and reparse the schema. Code an OP_Expire
93706     ** to invalidate all pre-compiled statements.
93707     */
93708     if( pTblName ){
93709       sqlite3RefillIndex(pParse, pIndex, iMem);
93710       sqlite3ChangeCookie(pParse, iDb);
93711       sqlite3VdbeAddParseSchemaOp(v, iDb,
93712          sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
93713       sqlite3VdbeAddOp1(v, OP_Expire, 0);
93714     }
93715   }
93716
93717   /* When adding an index to the list of indices for a table, make
93718   ** sure all indices labeled OE_Replace come after all those labeled
93719   ** OE_Ignore.  This is necessary for the correct constraint check
93720   ** processing (in sqlite3GenerateConstraintChecks()) as part of
93721   ** UPDATE and INSERT statements.  
93722   */
93723   if( db->init.busy || pTblName==0 ){
93724     if( onError!=OE_Replace || pTab->pIndex==0
93725          || pTab->pIndex->onError==OE_Replace){
93726       pIndex->pNext = pTab->pIndex;
93727       pTab->pIndex = pIndex;
93728     }else{
93729       Index *pOther = pTab->pIndex;
93730       while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
93731         pOther = pOther->pNext;
93732       }
93733       pIndex->pNext = pOther->pNext;
93734       pOther->pNext = pIndex;
93735     }
93736     pRet = pIndex;
93737     pIndex = 0;
93738   }
93739
93740   /* Clean up before exiting */
93741 exit_create_index:
93742   if( pIndex ) freeIndex(db, pIndex);
93743   sqlite3ExprDelete(db, pPIWhere);
93744   sqlite3ExprListDelete(db, pList);
93745   sqlite3SrcListDelete(db, pTblName);
93746   sqlite3DbFree(db, zName);
93747   return pRet;
93748 }
93749
93750 /*
93751 ** Fill the Index.aiRowEst[] array with default information - information
93752 ** to be used when we have not run the ANALYZE command.
93753 **
93754 ** aiRowEst[0] is supposed to contain the number of elements in the index.
93755 ** Since we do not know, guess 1 million.  aiRowEst[1] is an estimate of the
93756 ** number of rows in the table that match any particular value of the
93757 ** first column of the index.  aiRowEst[2] is an estimate of the number
93758 ** of rows that match any particular combination of the first 2 columns
93759 ** of the index.  And so forth.  It must always be the case that
93760 *
93761 **           aiRowEst[N]<=aiRowEst[N-1]
93762 **           aiRowEst[N]>=1
93763 **
93764 ** Apart from that, we have little to go on besides intuition as to
93765 ** how aiRowEst[] should be initialized.  The numbers generated here
93766 ** are based on typical values found in actual indices.
93767 */
93768 SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
93769   /*                10,  9,  8,  7,  6 */
93770   LogEst aVal[] = { 33, 32, 30, 28, 26 };
93771   LogEst *a = pIdx->aiRowLogEst;
93772   int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
93773   int i;
93774
93775   /* Set the first entry (number of rows in the index) to the estimated 
93776   ** number of rows in the table. Or 10, if the estimated number of rows 
93777   ** in the table is less than that.  */
93778   a[0] = pIdx->pTable->nRowLogEst;
93779   if( a[0]<33 ) a[0] = 33;        assert( 33==sqlite3LogEst(10) );
93780
93781   /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
93782   ** 6 and each subsequent value (if any) is 5.  */
93783   memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
93784   for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
93785     a[i] = 23;                    assert( 23==sqlite3LogEst(5) );
93786   }
93787
93788   assert( 0==sqlite3LogEst(1) );
93789   if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
93790 }
93791
93792 /*
93793 ** This routine will drop an existing named index.  This routine
93794 ** implements the DROP INDEX statement.
93795 */
93796 SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
93797   Index *pIndex;
93798   Vdbe *v;
93799   sqlite3 *db = pParse->db;
93800   int iDb;
93801
93802   assert( pParse->nErr==0 );   /* Never called with prior errors */
93803   if( db->mallocFailed ){
93804     goto exit_drop_index;
93805   }
93806   assert( pName->nSrc==1 );
93807   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
93808     goto exit_drop_index;
93809   }
93810   pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
93811   if( pIndex==0 ){
93812     if( !ifExists ){
93813       sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
93814     }else{
93815       sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
93816     }
93817     pParse->checkSchema = 1;
93818     goto exit_drop_index;
93819   }
93820   if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
93821     sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
93822       "or PRIMARY KEY constraint cannot be dropped", 0);
93823     goto exit_drop_index;
93824   }
93825   iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
93826 #ifndef SQLITE_OMIT_AUTHORIZATION
93827   {
93828     int code = SQLITE_DROP_INDEX;
93829     Table *pTab = pIndex->pTable;
93830     const char *zDb = db->aDb[iDb].zName;
93831     const char *zTab = SCHEMA_TABLE(iDb);
93832     if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
93833       goto exit_drop_index;
93834     }
93835     if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
93836     if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
93837       goto exit_drop_index;
93838     }
93839   }
93840 #endif
93841
93842   /* Generate code to remove the index and from the master table */
93843   v = sqlite3GetVdbe(pParse);
93844   if( v ){
93845     sqlite3BeginWriteOperation(pParse, 1, iDb);
93846     sqlite3NestedParse(pParse,
93847        "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
93848        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
93849     );
93850     sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
93851     sqlite3ChangeCookie(pParse, iDb);
93852     destroyRootPage(pParse, pIndex->tnum, iDb);
93853     sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
93854   }
93855
93856 exit_drop_index:
93857   sqlite3SrcListDelete(db, pName);
93858 }
93859
93860 /*
93861 ** pArray is a pointer to an array of objects. Each object in the
93862 ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
93863 ** to extend the array so that there is space for a new object at the end.
93864 **
93865 ** When this function is called, *pnEntry contains the current size of
93866 ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
93867 ** in total).
93868 **
93869 ** If the realloc() is successful (i.e. if no OOM condition occurs), the
93870 ** space allocated for the new object is zeroed, *pnEntry updated to
93871 ** reflect the new size of the array and a pointer to the new allocation
93872 ** returned. *pIdx is set to the index of the new array entry in this case.
93873 **
93874 ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
93875 ** unchanged and a copy of pArray returned.
93876 */
93877 SQLITE_PRIVATE void *sqlite3ArrayAllocate(
93878   sqlite3 *db,      /* Connection to notify of malloc failures */
93879   void *pArray,     /* Array of objects.  Might be reallocated */
93880   int szEntry,      /* Size of each object in the array */
93881   int *pnEntry,     /* Number of objects currently in use */
93882   int *pIdx         /* Write the index of a new slot here */
93883 ){
93884   char *z;
93885   int n = *pnEntry;
93886   if( (n & (n-1))==0 ){
93887     int sz = (n==0) ? 1 : 2*n;
93888     void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
93889     if( pNew==0 ){
93890       *pIdx = -1;
93891       return pArray;
93892     }
93893     pArray = pNew;
93894   }
93895   z = (char*)pArray;
93896   memset(&z[n * szEntry], 0, szEntry);
93897   *pIdx = n;
93898   ++*pnEntry;
93899   return pArray;
93900 }
93901
93902 /*
93903 ** Append a new element to the given IdList.  Create a new IdList if
93904 ** need be.
93905 **
93906 ** A new IdList is returned, or NULL if malloc() fails.
93907 */
93908 SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
93909   int i;
93910   if( pList==0 ){
93911     pList = sqlite3DbMallocZero(db, sizeof(IdList) );
93912     if( pList==0 ) return 0;
93913   }
93914   pList->a = sqlite3ArrayAllocate(
93915       db,
93916       pList->a,
93917       sizeof(pList->a[0]),
93918       &pList->nId,
93919       &i
93920   );
93921   if( i<0 ){
93922     sqlite3IdListDelete(db, pList);
93923     return 0;
93924   }
93925   pList->a[i].zName = sqlite3NameFromToken(db, pToken);
93926   return pList;
93927 }
93928
93929 /*
93930 ** Delete an IdList.
93931 */
93932 SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
93933   int i;
93934   if( pList==0 ) return;
93935   for(i=0; i<pList->nId; i++){
93936     sqlite3DbFree(db, pList->a[i].zName);
93937   }
93938   sqlite3DbFree(db, pList->a);
93939   sqlite3DbFree(db, pList);
93940 }
93941
93942 /*
93943 ** Return the index in pList of the identifier named zId.  Return -1
93944 ** if not found.
93945 */
93946 SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
93947   int i;
93948   if( pList==0 ) return -1;
93949   for(i=0; i<pList->nId; i++){
93950     if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
93951   }
93952   return -1;
93953 }
93954
93955 /*
93956 ** Expand the space allocated for the given SrcList object by
93957 ** creating nExtra new slots beginning at iStart.  iStart is zero based.
93958 ** New slots are zeroed.
93959 **
93960 ** For example, suppose a SrcList initially contains two entries: A,B.
93961 ** To append 3 new entries onto the end, do this:
93962 **
93963 **    sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
93964 **
93965 ** After the call above it would contain:  A, B, nil, nil, nil.
93966 ** If the iStart argument had been 1 instead of 2, then the result
93967 ** would have been:  A, nil, nil, nil, B.  To prepend the new slots,
93968 ** the iStart value would be 0.  The result then would
93969 ** be: nil, nil, nil, A, B.
93970 **
93971 ** If a memory allocation fails the SrcList is unchanged.  The
93972 ** db->mallocFailed flag will be set to true.
93973 */
93974 SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
93975   sqlite3 *db,       /* Database connection to notify of OOM errors */
93976   SrcList *pSrc,     /* The SrcList to be enlarged */
93977   int nExtra,        /* Number of new slots to add to pSrc->a[] */
93978   int iStart         /* Index in pSrc->a[] of first new slot */
93979 ){
93980   int i;
93981
93982   /* Sanity checking on calling parameters */
93983   assert( iStart>=0 );
93984   assert( nExtra>=1 );
93985   assert( pSrc!=0 );
93986   assert( iStart<=pSrc->nSrc );
93987
93988   /* Allocate additional space if needed */
93989   if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
93990     SrcList *pNew;
93991     int nAlloc = pSrc->nSrc+nExtra;
93992     int nGot;
93993     pNew = sqlite3DbRealloc(db, pSrc,
93994                sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
93995     if( pNew==0 ){
93996       assert( db->mallocFailed );
93997       return pSrc;
93998     }
93999     pSrc = pNew;
94000     nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
94001     pSrc->nAlloc = nGot;
94002   }
94003
94004   /* Move existing slots that come after the newly inserted slots
94005   ** out of the way */
94006   for(i=pSrc->nSrc-1; i>=iStart; i--){
94007     pSrc->a[i+nExtra] = pSrc->a[i];
94008   }
94009   pSrc->nSrc += nExtra;
94010
94011   /* Zero the newly allocated slots */
94012   memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
94013   for(i=iStart; i<iStart+nExtra; i++){
94014     pSrc->a[i].iCursor = -1;
94015   }
94016
94017   /* Return a pointer to the enlarged SrcList */
94018   return pSrc;
94019 }
94020
94021
94022 /*
94023 ** Append a new table name to the given SrcList.  Create a new SrcList if
94024 ** need be.  A new entry is created in the SrcList even if pTable is NULL.
94025 **
94026 ** A SrcList is returned, or NULL if there is an OOM error.  The returned
94027 ** SrcList might be the same as the SrcList that was input or it might be
94028 ** a new one.  If an OOM error does occurs, then the prior value of pList
94029 ** that is input to this routine is automatically freed.
94030 **
94031 ** If pDatabase is not null, it means that the table has an optional
94032 ** database name prefix.  Like this:  "database.table".  The pDatabase
94033 ** points to the table name and the pTable points to the database name.
94034 ** The SrcList.a[].zName field is filled with the table name which might
94035 ** come from pTable (if pDatabase is NULL) or from pDatabase.  
94036 ** SrcList.a[].zDatabase is filled with the database name from pTable,
94037 ** or with NULL if no database is specified.
94038 **
94039 ** In other words, if call like this:
94040 **
94041 **         sqlite3SrcListAppend(D,A,B,0);
94042 **
94043 ** Then B is a table name and the database name is unspecified.  If called
94044 ** like this:
94045 **
94046 **         sqlite3SrcListAppend(D,A,B,C);
94047 **
94048 ** Then C is the table name and B is the database name.  If C is defined
94049 ** then so is B.  In other words, we never have a case where:
94050 **
94051 **         sqlite3SrcListAppend(D,A,0,C);
94052 **
94053 ** Both pTable and pDatabase are assumed to be quoted.  They are dequoted
94054 ** before being added to the SrcList.
94055 */
94056 SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
94057   sqlite3 *db,        /* Connection to notify of malloc failures */
94058   SrcList *pList,     /* Append to this SrcList. NULL creates a new SrcList */
94059   Token *pTable,      /* Table to append */
94060   Token *pDatabase    /* Database of the table */
94061 ){
94062   struct SrcList_item *pItem;
94063   assert( pDatabase==0 || pTable!=0 );  /* Cannot have C without B */
94064   if( pList==0 ){
94065     pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
94066     if( pList==0 ) return 0;
94067     pList->nAlloc = 1;
94068   }
94069   pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
94070   if( db->mallocFailed ){
94071     sqlite3SrcListDelete(db, pList);
94072     return 0;
94073   }
94074   pItem = &pList->a[pList->nSrc-1];
94075   if( pDatabase && pDatabase->z==0 ){
94076     pDatabase = 0;
94077   }
94078   if( pDatabase ){
94079     Token *pTemp = pDatabase;
94080     pDatabase = pTable;
94081     pTable = pTemp;
94082   }
94083   pItem->zName = sqlite3NameFromToken(db, pTable);
94084   pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
94085   return pList;
94086 }
94087
94088 /*
94089 ** Assign VdbeCursor index numbers to all tables in a SrcList
94090 */
94091 SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
94092   int i;
94093   struct SrcList_item *pItem;
94094   assert(pList || pParse->db->mallocFailed );
94095   if( pList ){
94096     for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
94097       if( pItem->iCursor>=0 ) break;
94098       pItem->iCursor = pParse->nTab++;
94099       if( pItem->pSelect ){
94100         sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
94101       }
94102     }
94103   }
94104 }
94105
94106 /*
94107 ** Delete an entire SrcList including all its substructure.
94108 */
94109 SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
94110   int i;
94111   struct SrcList_item *pItem;
94112   if( pList==0 ) return;
94113   for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
94114     sqlite3DbFree(db, pItem->zDatabase);
94115     sqlite3DbFree(db, pItem->zName);
94116     sqlite3DbFree(db, pItem->zAlias);
94117     sqlite3DbFree(db, pItem->zIndex);
94118     sqlite3DeleteTable(db, pItem->pTab);
94119     sqlite3SelectDelete(db, pItem->pSelect);
94120     sqlite3ExprDelete(db, pItem->pOn);
94121     sqlite3IdListDelete(db, pItem->pUsing);
94122   }
94123   sqlite3DbFree(db, pList);
94124 }
94125
94126 /*
94127 ** This routine is called by the parser to add a new term to the
94128 ** end of a growing FROM clause.  The "p" parameter is the part of
94129 ** the FROM clause that has already been constructed.  "p" is NULL
94130 ** if this is the first term of the FROM clause.  pTable and pDatabase
94131 ** are the name of the table and database named in the FROM clause term.
94132 ** pDatabase is NULL if the database name qualifier is missing - the
94133 ** usual case.  If the term has an alias, then pAlias points to the
94134 ** alias token.  If the term is a subquery, then pSubquery is the
94135 ** SELECT statement that the subquery encodes.  The pTable and
94136 ** pDatabase parameters are NULL for subqueries.  The pOn and pUsing
94137 ** parameters are the content of the ON and USING clauses.
94138 **
94139 ** Return a new SrcList which encodes is the FROM with the new
94140 ** term added.
94141 */
94142 SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
94143   Parse *pParse,          /* Parsing context */
94144   SrcList *p,             /* The left part of the FROM clause already seen */
94145   Token *pTable,          /* Name of the table to add to the FROM clause */
94146   Token *pDatabase,       /* Name of the database containing pTable */
94147   Token *pAlias,          /* The right-hand side of the AS subexpression */
94148   Select *pSubquery,      /* A subquery used in place of a table name */
94149   Expr *pOn,              /* The ON clause of a join */
94150   IdList *pUsing          /* The USING clause of a join */
94151 ){
94152   struct SrcList_item *pItem;
94153   sqlite3 *db = pParse->db;
94154   if( !p && (pOn || pUsing) ){
94155     sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s", 
94156       (pOn ? "ON" : "USING")
94157     );
94158     goto append_from_error;
94159   }
94160   p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
94161   if( p==0 || NEVER(p->nSrc==0) ){
94162     goto append_from_error;
94163   }
94164   pItem = &p->a[p->nSrc-1];
94165   assert( pAlias!=0 );
94166   if( pAlias->n ){
94167     pItem->zAlias = sqlite3NameFromToken(db, pAlias);
94168   }
94169   pItem->pSelect = pSubquery;
94170   pItem->pOn = pOn;
94171   pItem->pUsing = pUsing;
94172   return p;
94173
94174  append_from_error:
94175   assert( p==0 );
94176   sqlite3ExprDelete(db, pOn);
94177   sqlite3IdListDelete(db, pUsing);
94178   sqlite3SelectDelete(db, pSubquery);
94179   return 0;
94180 }
94181
94182 /*
94183 ** Add an INDEXED BY or NOT INDEXED clause to the most recently added 
94184 ** element of the source-list passed as the second argument.
94185 */
94186 SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
94187   assert( pIndexedBy!=0 );
94188   if( p && ALWAYS(p->nSrc>0) ){
94189     struct SrcList_item *pItem = &p->a[p->nSrc-1];
94190     assert( pItem->notIndexed==0 && pItem->zIndex==0 );
94191     if( pIndexedBy->n==1 && !pIndexedBy->z ){
94192       /* A "NOT INDEXED" clause was supplied. See parse.y 
94193       ** construct "indexed_opt" for details. */
94194       pItem->notIndexed = 1;
94195     }else{
94196       pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
94197     }
94198   }
94199 }
94200
94201 /*
94202 ** When building up a FROM clause in the parser, the join operator
94203 ** is initially attached to the left operand.  But the code generator
94204 ** expects the join operator to be on the right operand.  This routine
94205 ** Shifts all join operators from left to right for an entire FROM
94206 ** clause.
94207 **
94208 ** Example: Suppose the join is like this:
94209 **
94210 **           A natural cross join B
94211 **
94212 ** The operator is "natural cross join".  The A and B operands are stored
94213 ** in p->a[0] and p->a[1], respectively.  The parser initially stores the
94214 ** operator with A.  This routine shifts that operator over to B.
94215 */
94216 SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
94217   if( p ){
94218     int i;
94219     assert( p->a || p->nSrc==0 );
94220     for(i=p->nSrc-1; i>0; i--){
94221       p->a[i].jointype = p->a[i-1].jointype;
94222     }
94223     p->a[0].jointype = 0;
94224   }
94225 }
94226
94227 /*
94228 ** Begin a transaction
94229 */
94230 SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
94231   sqlite3 *db;
94232   Vdbe *v;
94233   int i;
94234
94235   assert( pParse!=0 );
94236   db = pParse->db;
94237   assert( db!=0 );
94238 /*  if( db->aDb[0].pBt==0 ) return; */
94239   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
94240     return;
94241   }
94242   v = sqlite3GetVdbe(pParse);
94243   if( !v ) return;
94244   if( type!=TK_DEFERRED ){
94245     for(i=0; i<db->nDb; i++){
94246       sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
94247       sqlite3VdbeUsesBtree(v, i);
94248     }
94249   }
94250   sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
94251 }
94252
94253 /*
94254 ** Commit a transaction
94255 */
94256 SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
94257   Vdbe *v;
94258
94259   assert( pParse!=0 );
94260   assert( pParse->db!=0 );
94261   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
94262     return;
94263   }
94264   v = sqlite3GetVdbe(pParse);
94265   if( v ){
94266     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
94267   }
94268 }
94269
94270 /*
94271 ** Rollback a transaction
94272 */
94273 SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
94274   Vdbe *v;
94275
94276   assert( pParse!=0 );
94277   assert( pParse->db!=0 );
94278   if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
94279     return;
94280   }
94281   v = sqlite3GetVdbe(pParse);
94282   if( v ){
94283     sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
94284   }
94285 }
94286
94287 /*
94288 ** This function is called by the parser when it parses a command to create,
94289 ** release or rollback an SQL savepoint. 
94290 */
94291 SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
94292   char *zName = sqlite3NameFromToken(pParse->db, pName);
94293   if( zName ){
94294     Vdbe *v = sqlite3GetVdbe(pParse);
94295 #ifndef SQLITE_OMIT_AUTHORIZATION
94296     static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
94297     assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
94298 #endif
94299     if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
94300       sqlite3DbFree(pParse->db, zName);
94301       return;
94302     }
94303     sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
94304   }
94305 }
94306
94307 /*
94308 ** Make sure the TEMP database is open and available for use.  Return
94309 ** the number of errors.  Leave any error messages in the pParse structure.
94310 */
94311 SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
94312   sqlite3 *db = pParse->db;
94313   if( db->aDb[1].pBt==0 && !pParse->explain ){
94314     int rc;
94315     Btree *pBt;
94316     static const int flags = 
94317           SQLITE_OPEN_READWRITE |
94318           SQLITE_OPEN_CREATE |
94319           SQLITE_OPEN_EXCLUSIVE |
94320           SQLITE_OPEN_DELETEONCLOSE |
94321           SQLITE_OPEN_TEMP_DB;
94322
94323     rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
94324     if( rc!=SQLITE_OK ){
94325       sqlite3ErrorMsg(pParse, "unable to open a temporary database "
94326         "file for storing temporary tables");
94327       pParse->rc = rc;
94328       return 1;
94329     }
94330     db->aDb[1].pBt = pBt;
94331     assert( db->aDb[1].pSchema );
94332     if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
94333       db->mallocFailed = 1;
94334       return 1;
94335     }
94336   }
94337   return 0;
94338 }
94339
94340 /*
94341 ** Record the fact that the schema cookie will need to be verified
94342 ** for database iDb.  The code to actually verify the schema cookie
94343 ** will occur at the end of the top-level VDBE and will be generated
94344 ** later, by sqlite3FinishCoding().
94345 */
94346 SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
94347   Parse *pToplevel = sqlite3ParseToplevel(pParse);
94348   sqlite3 *db = pToplevel->db;
94349
94350   assert( iDb>=0 && iDb<db->nDb );
94351   assert( db->aDb[iDb].pBt!=0 || iDb==1 );
94352   assert( iDb<SQLITE_MAX_ATTACHED+2 );
94353   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
94354   if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
94355     DbMaskSet(pToplevel->cookieMask, iDb);
94356     pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
94357     if( !OMIT_TEMPDB && iDb==1 ){
94358       sqlite3OpenTempDatabase(pToplevel);
94359     }
94360   }
94361 }
94362
94363 /*
94364 ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each 
94365 ** attached database. Otherwise, invoke it for the database named zDb only.
94366 */
94367 SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
94368   sqlite3 *db = pParse->db;
94369   int i;
94370   for(i=0; i<db->nDb; i++){
94371     Db *pDb = &db->aDb[i];
94372     if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
94373       sqlite3CodeVerifySchema(pParse, i);
94374     }
94375   }
94376 }
94377
94378 /*
94379 ** Generate VDBE code that prepares for doing an operation that
94380 ** might change the database.
94381 **
94382 ** This routine starts a new transaction if we are not already within
94383 ** a transaction.  If we are already within a transaction, then a checkpoint
94384 ** is set if the setStatement parameter is true.  A checkpoint should
94385 ** be set for operations that might fail (due to a constraint) part of
94386 ** the way through and which will need to undo some writes without having to
94387 ** rollback the whole transaction.  For operations where all constraints
94388 ** can be checked before any changes are made to the database, it is never
94389 ** necessary to undo a write and the checkpoint should not be set.
94390 */
94391 SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
94392   Parse *pToplevel = sqlite3ParseToplevel(pParse);
94393   sqlite3CodeVerifySchema(pParse, iDb);
94394   DbMaskSet(pToplevel->writeMask, iDb);
94395   pToplevel->isMultiWrite |= setStatement;
94396 }
94397
94398 /*
94399 ** Indicate that the statement currently under construction might write
94400 ** more than one entry (example: deleting one row then inserting another,
94401 ** inserting multiple rows in a table, or inserting a row and index entries.)
94402 ** If an abort occurs after some of these writes have completed, then it will
94403 ** be necessary to undo the completed writes.
94404 */
94405 SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
94406   Parse *pToplevel = sqlite3ParseToplevel(pParse);
94407   pToplevel->isMultiWrite = 1;
94408 }
94409
94410 /* 
94411 ** The code generator calls this routine if is discovers that it is
94412 ** possible to abort a statement prior to completion.  In order to 
94413 ** perform this abort without corrupting the database, we need to make
94414 ** sure that the statement is protected by a statement transaction.
94415 **
94416 ** Technically, we only need to set the mayAbort flag if the
94417 ** isMultiWrite flag was previously set.  There is a time dependency
94418 ** such that the abort must occur after the multiwrite.  This makes
94419 ** some statements involving the REPLACE conflict resolution algorithm
94420 ** go a little faster.  But taking advantage of this time dependency
94421 ** makes it more difficult to prove that the code is correct (in 
94422 ** particular, it prevents us from writing an effective
94423 ** implementation of sqlite3AssertMayAbort()) and so we have chosen
94424 ** to take the safe route and skip the optimization.
94425 */
94426 SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
94427   Parse *pToplevel = sqlite3ParseToplevel(pParse);
94428   pToplevel->mayAbort = 1;
94429 }
94430
94431 /*
94432 ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
94433 ** error. The onError parameter determines which (if any) of the statement
94434 ** and/or current transaction is rolled back.
94435 */
94436 SQLITE_PRIVATE void sqlite3HaltConstraint(
94437   Parse *pParse,    /* Parsing context */
94438   int errCode,      /* extended error code */
94439   int onError,      /* Constraint type */
94440   char *p4,         /* Error message */
94441   i8 p4type,        /* P4_STATIC or P4_TRANSIENT */
94442   u8 p5Errmsg       /* P5_ErrMsg type */
94443 ){
94444   Vdbe *v = sqlite3GetVdbe(pParse);
94445   assert( (errCode&0xff)==SQLITE_CONSTRAINT );
94446   if( onError==OE_Abort ){
94447     sqlite3MayAbort(pParse);
94448   }
94449   sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
94450   if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
94451 }
94452
94453 /*
94454 ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
94455 */
94456 SQLITE_PRIVATE void sqlite3UniqueConstraint(
94457   Parse *pParse,    /* Parsing context */
94458   int onError,      /* Constraint type */
94459   Index *pIdx       /* The index that triggers the constraint */
94460 ){
94461   char *zErr;
94462   int j;
94463   StrAccum errMsg;
94464   Table *pTab = pIdx->pTable;
94465
94466   sqlite3StrAccumInit(&errMsg, 0, 0, 200);
94467   errMsg.db = pParse->db;
94468   for(j=0; j<pIdx->nKeyCol; j++){
94469     char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
94470     if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
94471     sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
94472     sqlite3StrAccumAppend(&errMsg, ".", 1);
94473     sqlite3StrAccumAppendAll(&errMsg, zCol);
94474   }
94475   zErr = sqlite3StrAccumFinish(&errMsg);
94476   sqlite3HaltConstraint(pParse, 
94477     IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY 
94478                             : SQLITE_CONSTRAINT_UNIQUE,
94479     onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
94480 }
94481
94482
94483 /*
94484 ** Code an OP_Halt due to non-unique rowid.
94485 */
94486 SQLITE_PRIVATE void sqlite3RowidConstraint(
94487   Parse *pParse,    /* Parsing context */
94488   int onError,      /* Conflict resolution algorithm */
94489   Table *pTab       /* The table with the non-unique rowid */ 
94490 ){
94491   char *zMsg;
94492   int rc;
94493   if( pTab->iPKey>=0 ){
94494     zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
94495                           pTab->aCol[pTab->iPKey].zName);
94496     rc = SQLITE_CONSTRAINT_PRIMARYKEY;
94497   }else{
94498     zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
94499     rc = SQLITE_CONSTRAINT_ROWID;
94500   }
94501   sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
94502                         P5_ConstraintUnique);
94503 }
94504
94505 /*
94506 ** Check to see if pIndex uses the collating sequence pColl.  Return
94507 ** true if it does and false if it does not.
94508 */
94509 #ifndef SQLITE_OMIT_REINDEX
94510 static int collationMatch(const char *zColl, Index *pIndex){
94511   int i;
94512   assert( zColl!=0 );
94513   for(i=0; i<pIndex->nColumn; i++){
94514     const char *z = pIndex->azColl[i];
94515     assert( z!=0 || pIndex->aiColumn[i]<0 );
94516     if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
94517       return 1;
94518     }
94519   }
94520   return 0;
94521 }
94522 #endif
94523
94524 /*
94525 ** Recompute all indices of pTab that use the collating sequence pColl.
94526 ** If pColl==0 then recompute all indices of pTab.
94527 */
94528 #ifndef SQLITE_OMIT_REINDEX
94529 static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
94530   Index *pIndex;              /* An index associated with pTab */
94531
94532   for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
94533     if( zColl==0 || collationMatch(zColl, pIndex) ){
94534       int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
94535       sqlite3BeginWriteOperation(pParse, 0, iDb);
94536       sqlite3RefillIndex(pParse, pIndex, -1);
94537     }
94538   }
94539 }
94540 #endif
94541
94542 /*
94543 ** Recompute all indices of all tables in all databases where the
94544 ** indices use the collating sequence pColl.  If pColl==0 then recompute
94545 ** all indices everywhere.
94546 */
94547 #ifndef SQLITE_OMIT_REINDEX
94548 static void reindexDatabases(Parse *pParse, char const *zColl){
94549   Db *pDb;                    /* A single database */
94550   int iDb;                    /* The database index number */
94551   sqlite3 *db = pParse->db;   /* The database connection */
94552   HashElem *k;                /* For looping over tables in pDb */
94553   Table *pTab;                /* A table in the database */
94554
94555   assert( sqlite3BtreeHoldsAllMutexes(db) );  /* Needed for schema access */
94556   for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
94557     assert( pDb!=0 );
94558     for(k=sqliteHashFirst(&pDb->pSchema->tblHash);  k; k=sqliteHashNext(k)){
94559       pTab = (Table*)sqliteHashData(k);
94560       reindexTable(pParse, pTab, zColl);
94561     }
94562   }
94563 }
94564 #endif
94565
94566 /*
94567 ** Generate code for the REINDEX command.
94568 **
94569 **        REINDEX                            -- 1
94570 **        REINDEX  <collation>               -- 2
94571 **        REINDEX  ?<database>.?<tablename>  -- 3
94572 **        REINDEX  ?<database>.?<indexname>  -- 4
94573 **
94574 ** Form 1 causes all indices in all attached databases to be rebuilt.
94575 ** Form 2 rebuilds all indices in all databases that use the named
94576 ** collating function.  Forms 3 and 4 rebuild the named index or all
94577 ** indices associated with the named table.
94578 */
94579 #ifndef SQLITE_OMIT_REINDEX
94580 SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
94581   CollSeq *pColl;             /* Collating sequence to be reindexed, or NULL */
94582   char *z;                    /* Name of a table or index */
94583   const char *zDb;            /* Name of the database */
94584   Table *pTab;                /* A table in the database */
94585   Index *pIndex;              /* An index associated with pTab */
94586   int iDb;                    /* The database index number */
94587   sqlite3 *db = pParse->db;   /* The database connection */
94588   Token *pObjName;            /* Name of the table or index to be reindexed */
94589
94590   /* Read the database schema. If an error occurs, leave an error message
94591   ** and code in pParse and return NULL. */
94592   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
94593     return;
94594   }
94595
94596   if( pName1==0 ){
94597     reindexDatabases(pParse, 0);
94598     return;
94599   }else if( NEVER(pName2==0) || pName2->z==0 ){
94600     char *zColl;
94601     assert( pName1->z );
94602     zColl = sqlite3NameFromToken(pParse->db, pName1);
94603     if( !zColl ) return;
94604     pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
94605     if( pColl ){
94606       reindexDatabases(pParse, zColl);
94607       sqlite3DbFree(db, zColl);
94608       return;
94609     }
94610     sqlite3DbFree(db, zColl);
94611   }
94612   iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
94613   if( iDb<0 ) return;
94614   z = sqlite3NameFromToken(db, pObjName);
94615   if( z==0 ) return;
94616   zDb = db->aDb[iDb].zName;
94617   pTab = sqlite3FindTable(db, z, zDb);
94618   if( pTab ){
94619     reindexTable(pParse, pTab, 0);
94620     sqlite3DbFree(db, z);
94621     return;
94622   }
94623   pIndex = sqlite3FindIndex(db, z, zDb);
94624   sqlite3DbFree(db, z);
94625   if( pIndex ){
94626     sqlite3BeginWriteOperation(pParse, 0, iDb);
94627     sqlite3RefillIndex(pParse, pIndex, -1);
94628     return;
94629   }
94630   sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
94631 }
94632 #endif
94633
94634 /*
94635 ** Return a KeyInfo structure that is appropriate for the given Index.
94636 **
94637 ** The KeyInfo structure for an index is cached in the Index object.
94638 ** So there might be multiple references to the returned pointer.  The
94639 ** caller should not try to modify the KeyInfo object.
94640 **
94641 ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
94642 ** when it has finished using it.
94643 */
94644 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
94645   int i;
94646   int nCol = pIdx->nColumn;
94647   int nKey = pIdx->nKeyCol;
94648   KeyInfo *pKey;
94649   if( pParse->nErr ) return 0;
94650   if( pIdx->uniqNotNull ){
94651     pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
94652   }else{
94653     pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
94654   }
94655   if( pKey ){
94656     assert( sqlite3KeyInfoIsWriteable(pKey) );
94657     for(i=0; i<nCol; i++){
94658       char *zColl = pIdx->azColl[i];
94659       assert( zColl!=0 );
94660       pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
94661                         sqlite3LocateCollSeq(pParse, zColl);
94662       pKey->aSortOrder[i] = pIdx->aSortOrder[i];
94663     }
94664     if( pParse->nErr ){
94665       sqlite3KeyInfoUnref(pKey);
94666       pKey = 0;
94667     }
94668   }
94669   return pKey;
94670 }
94671
94672 #ifndef SQLITE_OMIT_CTE
94673 /* 
94674 ** This routine is invoked once per CTE by the parser while parsing a 
94675 ** WITH clause. 
94676 */
94677 SQLITE_PRIVATE With *sqlite3WithAdd(
94678   Parse *pParse,          /* Parsing context */
94679   With *pWith,            /* Existing WITH clause, or NULL */
94680   Token *pName,           /* Name of the common-table */
94681   ExprList *pArglist,     /* Optional column name list for the table */
94682   Select *pQuery          /* Query used to initialize the table */
94683 ){
94684   sqlite3 *db = pParse->db;
94685   With *pNew;
94686   char *zName;
94687
94688   /* Check that the CTE name is unique within this WITH clause. If
94689   ** not, store an error in the Parse structure. */
94690   zName = sqlite3NameFromToken(pParse->db, pName);
94691   if( zName && pWith ){
94692     int i;
94693     for(i=0; i<pWith->nCte; i++){
94694       if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
94695         sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
94696       }
94697     }
94698   }
94699
94700   if( pWith ){
94701     int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
94702     pNew = sqlite3DbRealloc(db, pWith, nByte);
94703   }else{
94704     pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
94705   }
94706   assert( zName!=0 || pNew==0 );
94707   assert( db->mallocFailed==0 || pNew==0 );
94708
94709   if( pNew==0 ){
94710     sqlite3ExprListDelete(db, pArglist);
94711     sqlite3SelectDelete(db, pQuery);
94712     sqlite3DbFree(db, zName);
94713     pNew = pWith;
94714   }else{
94715     pNew->a[pNew->nCte].pSelect = pQuery;
94716     pNew->a[pNew->nCte].pCols = pArglist;
94717     pNew->a[pNew->nCte].zName = zName;
94718     pNew->a[pNew->nCte].zErr = 0;
94719     pNew->nCte++;
94720   }
94721
94722   return pNew;
94723 }
94724
94725 /*
94726 ** Free the contents of the With object passed as the second argument.
94727 */
94728 SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
94729   if( pWith ){
94730     int i;
94731     for(i=0; i<pWith->nCte; i++){
94732       struct Cte *pCte = &pWith->a[i];
94733       sqlite3ExprListDelete(db, pCte->pCols);
94734       sqlite3SelectDelete(db, pCte->pSelect);
94735       sqlite3DbFree(db, pCte->zName);
94736     }
94737     sqlite3DbFree(db, pWith);
94738   }
94739 }
94740 #endif /* !defined(SQLITE_OMIT_CTE) */
94741
94742 /************** End of build.c ***********************************************/
94743 /************** Begin file callback.c ****************************************/
94744 /*
94745 ** 2005 May 23 
94746 **
94747 ** The author disclaims copyright to this source code.  In place of
94748 ** a legal notice, here is a blessing:
94749 **
94750 **    May you do good and not evil.
94751 **    May you find forgiveness for yourself and forgive others.
94752 **    May you share freely, never taking more than you give.
94753 **
94754 *************************************************************************
94755 **
94756 ** This file contains functions used to access the internal hash tables
94757 ** of user defined functions and collation sequences.
94758 */
94759
94760
94761 /*
94762 ** Invoke the 'collation needed' callback to request a collation sequence
94763 ** in the encoding enc of name zName, length nName.
94764 */
94765 static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
94766   assert( !db->xCollNeeded || !db->xCollNeeded16 );
94767   if( db->xCollNeeded ){
94768     char *zExternal = sqlite3DbStrDup(db, zName);
94769     if( !zExternal ) return;
94770     db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
94771     sqlite3DbFree(db, zExternal);
94772   }
94773 #ifndef SQLITE_OMIT_UTF16
94774   if( db->xCollNeeded16 ){
94775     char const *zExternal;
94776     sqlite3_value *pTmp = sqlite3ValueNew(db);
94777     sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
94778     zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
94779     if( zExternal ){
94780       db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
94781     }
94782     sqlite3ValueFree(pTmp);
94783   }
94784 #endif
94785 }
94786
94787 /*
94788 ** This routine is called if the collation factory fails to deliver a
94789 ** collation function in the best encoding but there may be other versions
94790 ** of this collation function (for other text encodings) available. Use one
94791 ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
94792 ** possible.
94793 */
94794 static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
94795   CollSeq *pColl2;
94796   char *z = pColl->zName;
94797   int i;
94798   static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
94799   for(i=0; i<3; i++){
94800     pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
94801     if( pColl2->xCmp!=0 ){
94802       memcpy(pColl, pColl2, sizeof(CollSeq));
94803       pColl->xDel = 0;         /* Do not copy the destructor */
94804       return SQLITE_OK;
94805     }
94806   }
94807   return SQLITE_ERROR;
94808 }
94809
94810 /*
94811 ** This function is responsible for invoking the collation factory callback
94812 ** or substituting a collation sequence of a different encoding when the
94813 ** requested collation sequence is not available in the desired encoding.
94814 ** 
94815 ** If it is not NULL, then pColl must point to the database native encoding 
94816 ** collation sequence with name zName, length nName.
94817 **
94818 ** The return value is either the collation sequence to be used in database
94819 ** db for collation type name zName, length nName, or NULL, if no collation
94820 ** sequence can be found.  If no collation is found, leave an error message.
94821 **
94822 ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
94823 */
94824 SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
94825   Parse *pParse,        /* Parsing context */
94826   u8 enc,               /* The desired encoding for the collating sequence */
94827   CollSeq *pColl,       /* Collating sequence with native encoding, or NULL */
94828   const char *zName     /* Collating sequence name */
94829 ){
94830   CollSeq *p;
94831   sqlite3 *db = pParse->db;
94832
94833   p = pColl;
94834   if( !p ){
94835     p = sqlite3FindCollSeq(db, enc, zName, 0);
94836   }
94837   if( !p || !p->xCmp ){
94838     /* No collation sequence of this type for this encoding is registered.
94839     ** Call the collation factory to see if it can supply us with one.
94840     */
94841     callCollNeeded(db, enc, zName);
94842     p = sqlite3FindCollSeq(db, enc, zName, 0);
94843   }
94844   if( p && !p->xCmp && synthCollSeq(db, p) ){
94845     p = 0;
94846   }
94847   assert( !p || p->xCmp );
94848   if( p==0 ){
94849     sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
94850   }
94851   return p;
94852 }
94853
94854 /*
94855 ** This routine is called on a collation sequence before it is used to
94856 ** check that it is defined. An undefined collation sequence exists when
94857 ** a database is loaded that contains references to collation sequences
94858 ** that have not been defined by sqlite3_create_collation() etc.
94859 **
94860 ** If required, this routine calls the 'collation needed' callback to
94861 ** request a definition of the collating sequence. If this doesn't work, 
94862 ** an equivalent collating sequence that uses a text encoding different
94863 ** from the main database is substituted, if one is available.
94864 */
94865 SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
94866   if( pColl ){
94867     const char *zName = pColl->zName;
94868     sqlite3 *db = pParse->db;
94869     CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
94870     if( !p ){
94871       return SQLITE_ERROR;
94872     }
94873     assert( p==pColl );
94874   }
94875   return SQLITE_OK;
94876 }
94877
94878
94879
94880 /*
94881 ** Locate and return an entry from the db.aCollSeq hash table. If the entry
94882 ** specified by zName and nName is not found and parameter 'create' is
94883 ** true, then create a new entry. Otherwise return NULL.
94884 **
94885 ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
94886 ** array of three CollSeq structures. The first is the collation sequence
94887 ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
94888 **
94889 ** Stored immediately after the three collation sequences is a copy of
94890 ** the collation sequence name. A pointer to this string is stored in
94891 ** each collation sequence structure.
94892 */
94893 static CollSeq *findCollSeqEntry(
94894   sqlite3 *db,          /* Database connection */
94895   const char *zName,    /* Name of the collating sequence */
94896   int create            /* Create a new entry if true */
94897 ){
94898   CollSeq *pColl;
94899   pColl = sqlite3HashFind(&db->aCollSeq, zName);
94900
94901   if( 0==pColl && create ){
94902     int nName = sqlite3Strlen30(zName);
94903     pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1);
94904     if( pColl ){
94905       CollSeq *pDel = 0;
94906       pColl[0].zName = (char*)&pColl[3];
94907       pColl[0].enc = SQLITE_UTF8;
94908       pColl[1].zName = (char*)&pColl[3];
94909       pColl[1].enc = SQLITE_UTF16LE;
94910       pColl[2].zName = (char*)&pColl[3];
94911       pColl[2].enc = SQLITE_UTF16BE;
94912       memcpy(pColl[0].zName, zName, nName);
94913       pColl[0].zName[nName] = 0;
94914       pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
94915
94916       /* If a malloc() failure occurred in sqlite3HashInsert(), it will 
94917       ** return the pColl pointer to be deleted (because it wasn't added
94918       ** to the hash table).
94919       */
94920       assert( pDel==0 || pDel==pColl );
94921       if( pDel!=0 ){
94922         db->mallocFailed = 1;
94923         sqlite3DbFree(db, pDel);
94924         pColl = 0;
94925       }
94926     }
94927   }
94928   return pColl;
94929 }
94930
94931 /*
94932 ** Parameter zName points to a UTF-8 encoded string nName bytes long.
94933 ** Return the CollSeq* pointer for the collation sequence named zName
94934 ** for the encoding 'enc' from the database 'db'.
94935 **
94936 ** If the entry specified is not found and 'create' is true, then create a
94937 ** new entry.  Otherwise return NULL.
94938 **
94939 ** A separate function sqlite3LocateCollSeq() is a wrapper around
94940 ** this routine.  sqlite3LocateCollSeq() invokes the collation factory
94941 ** if necessary and generates an error message if the collating sequence
94942 ** cannot be found.
94943 **
94944 ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
94945 */
94946 SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
94947   sqlite3 *db,
94948   u8 enc,
94949   const char *zName,
94950   int create
94951 ){
94952   CollSeq *pColl;
94953   if( zName ){
94954     pColl = findCollSeqEntry(db, zName, create);
94955   }else{
94956     pColl = db->pDfltColl;
94957   }
94958   assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
94959   assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
94960   if( pColl ) pColl += enc-1;
94961   return pColl;
94962 }
94963
94964 /* During the search for the best function definition, this procedure
94965 ** is called to test how well the function passed as the first argument
94966 ** matches the request for a function with nArg arguments in a system
94967 ** that uses encoding enc. The value returned indicates how well the
94968 ** request is matched. A higher value indicates a better match.
94969 **
94970 ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
94971 ** is also -1.  In other words, we are searching for a function that
94972 ** takes a variable number of arguments.
94973 **
94974 ** If nArg is -2 that means that we are searching for any function 
94975 ** regardless of the number of arguments it uses, so return a positive
94976 ** match score for any
94977 **
94978 ** The returned value is always between 0 and 6, as follows:
94979 **
94980 ** 0: Not a match.
94981 ** 1: UTF8/16 conversion required and function takes any number of arguments.
94982 ** 2: UTF16 byte order change required and function takes any number of args.
94983 ** 3: encoding matches and function takes any number of arguments
94984 ** 4: UTF8/16 conversion required - argument count matches exactly
94985 ** 5: UTF16 byte order conversion required - argument count matches exactly
94986 ** 6: Perfect match:  encoding and argument count match exactly.
94987 **
94988 ** If nArg==(-2) then any function with a non-null xStep or xFunc is
94989 ** a perfect match and any function with both xStep and xFunc NULL is
94990 ** a non-match.
94991 */
94992 #define FUNC_PERFECT_MATCH 6  /* The score for a perfect match */
94993 static int matchQuality(
94994   FuncDef *p,     /* The function we are evaluating for match quality */
94995   int nArg,       /* Desired number of arguments.  (-1)==any */
94996   u8 enc          /* Desired text encoding */
94997 ){
94998   int match;
94999
95000   /* nArg of -2 is a special case */
95001   if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
95002
95003   /* Wrong number of arguments means "no match" */
95004   if( p->nArg!=nArg && p->nArg>=0 ) return 0;
95005
95006   /* Give a better score to a function with a specific number of arguments
95007   ** than to function that accepts any number of arguments. */
95008   if( p->nArg==nArg ){
95009     match = 4;
95010   }else{
95011     match = 1;
95012   }
95013
95014   /* Bonus points if the text encoding matches */
95015   if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
95016     match += 2;  /* Exact encoding match */
95017   }else if( (enc & p->funcFlags & 2)!=0 ){
95018     match += 1;  /* Both are UTF16, but with different byte orders */
95019   }
95020
95021   return match;
95022 }
95023
95024 /*
95025 ** Search a FuncDefHash for a function with the given name.  Return
95026 ** a pointer to the matching FuncDef if found, or 0 if there is no match.
95027 */
95028 static FuncDef *functionSearch(
95029   FuncDefHash *pHash,  /* Hash table to search */
95030   int h,               /* Hash of the name */
95031   const char *zFunc,   /* Name of function */
95032   int nFunc            /* Number of bytes in zFunc */
95033 ){
95034   FuncDef *p;
95035   for(p=pHash->a[h]; p; p=p->pHash){
95036     if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
95037       return p;
95038     }
95039   }
95040   return 0;
95041 }
95042
95043 /*
95044 ** Insert a new FuncDef into a FuncDefHash hash table.
95045 */
95046 SQLITE_PRIVATE void sqlite3FuncDefInsert(
95047   FuncDefHash *pHash,  /* The hash table into which to insert */
95048   FuncDef *pDef        /* The function definition to insert */
95049 ){
95050   FuncDef *pOther;
95051   int nName = sqlite3Strlen30(pDef->zName);
95052   u8 c1 = (u8)pDef->zName[0];
95053   int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
95054   pOther = functionSearch(pHash, h, pDef->zName, nName);
95055   if( pOther ){
95056     assert( pOther!=pDef && pOther->pNext!=pDef );
95057     pDef->pNext = pOther->pNext;
95058     pOther->pNext = pDef;
95059   }else{
95060     pDef->pNext = 0;
95061     pDef->pHash = pHash->a[h];
95062     pHash->a[h] = pDef;
95063   }
95064 }
95065   
95066   
95067
95068 /*
95069 ** Locate a user function given a name, a number of arguments and a flag
95070 ** indicating whether the function prefers UTF-16 over UTF-8.  Return a
95071 ** pointer to the FuncDef structure that defines that function, or return
95072 ** NULL if the function does not exist.
95073 **
95074 ** If the createFlag argument is true, then a new (blank) FuncDef
95075 ** structure is created and liked into the "db" structure if a
95076 ** no matching function previously existed.
95077 **
95078 ** If nArg is -2, then the first valid function found is returned.  A
95079 ** function is valid if either xFunc or xStep is non-zero.  The nArg==(-2)
95080 ** case is used to see if zName is a valid function name for some number
95081 ** of arguments.  If nArg is -2, then createFlag must be 0.
95082 **
95083 ** If createFlag is false, then a function with the required name and
95084 ** number of arguments may be returned even if the eTextRep flag does not
95085 ** match that requested.
95086 */
95087 SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
95088   sqlite3 *db,       /* An open database */
95089   const char *zName, /* Name of the function.  Not null-terminated */
95090   int nName,         /* Number of characters in the name */
95091   int nArg,          /* Number of arguments.  -1 means any number */
95092   u8 enc,            /* Preferred text encoding */
95093   u8 createFlag      /* Create new entry if true and does not otherwise exist */
95094 ){
95095   FuncDef *p;         /* Iterator variable */
95096   FuncDef *pBest = 0; /* Best match found so far */
95097   int bestScore = 0;  /* Score of best match */
95098   int h;              /* Hash value */
95099
95100   assert( nArg>=(-2) );
95101   assert( nArg>=(-1) || createFlag==0 );
95102   h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
95103
95104   /* First search for a match amongst the application-defined functions.
95105   */
95106   p = functionSearch(&db->aFunc, h, zName, nName);
95107   while( p ){
95108     int score = matchQuality(p, nArg, enc);
95109     if( score>bestScore ){
95110       pBest = p;
95111       bestScore = score;
95112     }
95113     p = p->pNext;
95114   }
95115
95116   /* If no match is found, search the built-in functions.
95117   **
95118   ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
95119   ** functions even if a prior app-defined function was found.  And give
95120   ** priority to built-in functions.
95121   **
95122   ** Except, if createFlag is true, that means that we are trying to
95123   ** install a new function.  Whatever FuncDef structure is returned it will
95124   ** have fields overwritten with new information appropriate for the
95125   ** new function.  But the FuncDefs for built-in functions are read-only.
95126   ** So we must not search for built-ins when creating a new function.
95127   */ 
95128   if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
95129     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
95130     bestScore = 0;
95131     p = functionSearch(pHash, h, zName, nName);
95132     while( p ){
95133       int score = matchQuality(p, nArg, enc);
95134       if( score>bestScore ){
95135         pBest = p;
95136         bestScore = score;
95137       }
95138       p = p->pNext;
95139     }
95140   }
95141
95142   /* If the createFlag parameter is true and the search did not reveal an
95143   ** exact match for the name, number of arguments and encoding, then add a
95144   ** new entry to the hash table and return it.
95145   */
95146   if( createFlag && bestScore<FUNC_PERFECT_MATCH && 
95147       (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
95148     pBest->zName = (char *)&pBest[1];
95149     pBest->nArg = (u16)nArg;
95150     pBest->funcFlags = enc;
95151     memcpy(pBest->zName, zName, nName);
95152     pBest->zName[nName] = 0;
95153     sqlite3FuncDefInsert(&db->aFunc, pBest);
95154   }
95155
95156   if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
95157     return pBest;
95158   }
95159   return 0;
95160 }
95161
95162 /*
95163 ** Free all resources held by the schema structure. The void* argument points
95164 ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the 
95165 ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
95166 ** of the schema hash tables).
95167 **
95168 ** The Schema.cache_size variable is not cleared.
95169 */
95170 SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
95171   Hash temp1;
95172   Hash temp2;
95173   HashElem *pElem;
95174   Schema *pSchema = (Schema *)p;
95175
95176   temp1 = pSchema->tblHash;
95177   temp2 = pSchema->trigHash;
95178   sqlite3HashInit(&pSchema->trigHash);
95179   sqlite3HashClear(&pSchema->idxHash);
95180   for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
95181     sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
95182   }
95183   sqlite3HashClear(&temp2);
95184   sqlite3HashInit(&pSchema->tblHash);
95185   for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
95186     Table *pTab = sqliteHashData(pElem);
95187     sqlite3DeleteTable(0, pTab);
95188   }
95189   sqlite3HashClear(&temp1);
95190   sqlite3HashClear(&pSchema->fkeyHash);
95191   pSchema->pSeqTab = 0;
95192   if( pSchema->schemaFlags & DB_SchemaLoaded ){
95193     pSchema->iGeneration++;
95194     pSchema->schemaFlags &= ~DB_SchemaLoaded;
95195   }
95196 }
95197
95198 /*
95199 ** Find and return the schema associated with a BTree.  Create
95200 ** a new one if necessary.
95201 */
95202 SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
95203   Schema * p;
95204   if( pBt ){
95205     p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
95206   }else{
95207     p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
95208   }
95209   if( !p ){
95210     db->mallocFailed = 1;
95211   }else if ( 0==p->file_format ){
95212     sqlite3HashInit(&p->tblHash);
95213     sqlite3HashInit(&p->idxHash);
95214     sqlite3HashInit(&p->trigHash);
95215     sqlite3HashInit(&p->fkeyHash);
95216     p->enc = SQLITE_UTF8;
95217   }
95218   return p;
95219 }
95220
95221 /************** End of callback.c ********************************************/
95222 /************** Begin file delete.c ******************************************/
95223 /*
95224 ** 2001 September 15
95225 **
95226 ** The author disclaims copyright to this source code.  In place of
95227 ** a legal notice, here is a blessing:
95228 **
95229 **    May you do good and not evil.
95230 **    May you find forgiveness for yourself and forgive others.
95231 **    May you share freely, never taking more than you give.
95232 **
95233 *************************************************************************
95234 ** This file contains C code routines that are called by the parser
95235 ** in order to generate code for DELETE FROM statements.
95236 */
95237
95238 /*
95239 ** While a SrcList can in general represent multiple tables and subqueries
95240 ** (as in the FROM clause of a SELECT statement) in this case it contains
95241 ** the name of a single table, as one might find in an INSERT, DELETE,
95242 ** or UPDATE statement.  Look up that table in the symbol table and
95243 ** return a pointer.  Set an error message and return NULL if the table 
95244 ** name is not found or if any other error occurs.
95245 **
95246 ** The following fields are initialized appropriate in pSrc:
95247 **
95248 **    pSrc->a[0].pTab       Pointer to the Table object
95249 **    pSrc->a[0].pIndex     Pointer to the INDEXED BY index, if there is one
95250 **
95251 */
95252 SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
95253   struct SrcList_item *pItem = pSrc->a;
95254   Table *pTab;
95255   assert( pItem && pSrc->nSrc==1 );
95256   pTab = sqlite3LocateTableItem(pParse, 0, pItem);
95257   sqlite3DeleteTable(pParse->db, pItem->pTab);
95258   pItem->pTab = pTab;
95259   if( pTab ){
95260     pTab->nRef++;
95261   }
95262   if( sqlite3IndexedByLookup(pParse, pItem) ){
95263     pTab = 0;
95264   }
95265   return pTab;
95266 }
95267
95268 /*
95269 ** Check to make sure the given table is writable.  If it is not
95270 ** writable, generate an error message and return 1.  If it is
95271 ** writable return 0;
95272 */
95273 SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
95274   /* A table is not writable under the following circumstances:
95275   **
95276   **   1) It is a virtual table and no implementation of the xUpdate method
95277   **      has been provided, or
95278   **   2) It is a system table (i.e. sqlite_master), this call is not
95279   **      part of a nested parse and writable_schema pragma has not 
95280   **      been specified.
95281   **
95282   ** In either case leave an error message in pParse and return non-zero.
95283   */
95284   if( ( IsVirtual(pTab) 
95285      && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
95286    || ( (pTab->tabFlags & TF_Readonly)!=0
95287      && (pParse->db->flags & SQLITE_WriteSchema)==0
95288      && pParse->nested==0 )
95289   ){
95290     sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
95291     return 1;
95292   }
95293
95294 #ifndef SQLITE_OMIT_VIEW
95295   if( !viewOk && pTab->pSelect ){
95296     sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
95297     return 1;
95298   }
95299 #endif
95300   return 0;
95301 }
95302
95303
95304 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
95305 /*
95306 ** Evaluate a view and store its result in an ephemeral table.  The
95307 ** pWhere argument is an optional WHERE clause that restricts the
95308 ** set of rows in the view that are to be added to the ephemeral table.
95309 */
95310 SQLITE_PRIVATE void sqlite3MaterializeView(
95311   Parse *pParse,       /* Parsing context */
95312   Table *pView,        /* View definition */
95313   Expr *pWhere,        /* Optional WHERE clause to be added */
95314   int iCur             /* Cursor number for ephemeral table */
95315 ){
95316   SelectDest dest;
95317   Select *pSel;
95318   SrcList *pFrom;
95319   sqlite3 *db = pParse->db;
95320   int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
95321   pWhere = sqlite3ExprDup(db, pWhere, 0);
95322   pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
95323   if( pFrom ){
95324     assert( pFrom->nSrc==1 );
95325     pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
95326     pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
95327     assert( pFrom->a[0].pOn==0 );
95328     assert( pFrom->a[0].pUsing==0 );
95329   }
95330   pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
95331   sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
95332   sqlite3Select(pParse, pSel, &dest);
95333   sqlite3SelectDelete(db, pSel);
95334 }
95335 #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
95336
95337 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
95338 /*
95339 ** Generate an expression tree to implement the WHERE, ORDER BY,
95340 ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
95341 **
95342 **     DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
95343 **                            \__________________________/
95344 **                               pLimitWhere (pInClause)
95345 */
95346 SQLITE_PRIVATE Expr *sqlite3LimitWhere(
95347   Parse *pParse,               /* The parser context */
95348   SrcList *pSrc,               /* the FROM clause -- which tables to scan */
95349   Expr *pWhere,                /* The WHERE clause.  May be null */
95350   ExprList *pOrderBy,          /* The ORDER BY clause.  May be null */
95351   Expr *pLimit,                /* The LIMIT clause.  May be null */
95352   Expr *pOffset,               /* The OFFSET clause.  May be null */
95353   char *zStmtType              /* Either DELETE or UPDATE.  For err msgs. */
95354 ){
95355   Expr *pWhereRowid = NULL;    /* WHERE rowid .. */
95356   Expr *pInClause = NULL;      /* WHERE rowid IN ( select ) */
95357   Expr *pSelectRowid = NULL;   /* SELECT rowid ... */
95358   ExprList *pEList = NULL;     /* Expression list contaning only pSelectRowid */
95359   SrcList *pSelectSrc = NULL;  /* SELECT rowid FROM x ... (dup of pSrc) */
95360   Select *pSelect = NULL;      /* Complete SELECT tree */
95361
95362   /* Check that there isn't an ORDER BY without a LIMIT clause.
95363   */
95364   if( pOrderBy && (pLimit == 0) ) {
95365     sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
95366     goto limit_where_cleanup_2;
95367   }
95368
95369   /* We only need to generate a select expression if there
95370   ** is a limit/offset term to enforce.
95371   */
95372   if( pLimit == 0 ) {
95373     /* if pLimit is null, pOffset will always be null as well. */
95374     assert( pOffset == 0 );
95375     return pWhere;
95376   }
95377
95378   /* Generate a select expression tree to enforce the limit/offset 
95379   ** term for the DELETE or UPDATE statement.  For example:
95380   **   DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
95381   ** becomes:
95382   **   DELETE FROM table_a WHERE rowid IN ( 
95383   **     SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
95384   **   );
95385   */
95386
95387   pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
95388   if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
95389   pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
95390   if( pEList == 0 ) goto limit_where_cleanup_2;
95391
95392   /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
95393   ** and the SELECT subtree. */
95394   pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
95395   if( pSelectSrc == 0 ) {
95396     sqlite3ExprListDelete(pParse->db, pEList);
95397     goto limit_where_cleanup_2;
95398   }
95399
95400   /* generate the SELECT expression tree. */
95401   pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
95402                              pOrderBy,0,pLimit,pOffset);
95403   if( pSelect == 0 ) return 0;
95404
95405   /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
95406   pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
95407   if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
95408   pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
95409   if( pInClause == 0 ) goto limit_where_cleanup_1;
95410
95411   pInClause->x.pSelect = pSelect;
95412   pInClause->flags |= EP_xIsSelect;
95413   sqlite3ExprSetHeightAndFlags(pParse, pInClause);
95414   return pInClause;
95415
95416   /* something went wrong. clean up anything allocated. */
95417 limit_where_cleanup_1:
95418   sqlite3SelectDelete(pParse->db, pSelect);
95419   return 0;
95420
95421 limit_where_cleanup_2:
95422   sqlite3ExprDelete(pParse->db, pWhere);
95423   sqlite3ExprListDelete(pParse->db, pOrderBy);
95424   sqlite3ExprDelete(pParse->db, pLimit);
95425   sqlite3ExprDelete(pParse->db, pOffset);
95426   return 0;
95427 }
95428 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
95429        /*      && !defined(SQLITE_OMIT_SUBQUERY) */
95430
95431 /*
95432 ** Generate code for a DELETE FROM statement.
95433 **
95434 **     DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
95435 **                 \________/       \________________/
95436 **                  pTabList              pWhere
95437 */
95438 SQLITE_PRIVATE void sqlite3DeleteFrom(
95439   Parse *pParse,         /* The parser context */
95440   SrcList *pTabList,     /* The table from which we should delete things */
95441   Expr *pWhere           /* The WHERE clause.  May be null */
95442 ){
95443   Vdbe *v;               /* The virtual database engine */
95444   Table *pTab;           /* The table from which records will be deleted */
95445   const char *zDb;       /* Name of database holding pTab */
95446   int i;                 /* Loop counter */
95447   WhereInfo *pWInfo;     /* Information about the WHERE clause */
95448   Index *pIdx;           /* For looping over indices of the table */
95449   int iTabCur;           /* Cursor number for the table */
95450   int iDataCur = 0;      /* VDBE cursor for the canonical data source */
95451   int iIdxCur = 0;       /* Cursor number of the first index */
95452   int nIdx;              /* Number of indices */
95453   sqlite3 *db;           /* Main database structure */
95454   AuthContext sContext;  /* Authorization context */
95455   NameContext sNC;       /* Name context to resolve expressions in */
95456   int iDb;               /* Database number */
95457   int memCnt = -1;       /* Memory cell used for change counting */
95458   int rcauth;            /* Value returned by authorization callback */
95459   int okOnePass;         /* True for one-pass algorithm without the FIFO */
95460   int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
95461   u8 *aToOpen = 0;       /* Open cursor iTabCur+j if aToOpen[j] is true */
95462   Index *pPk;            /* The PRIMARY KEY index on the table */
95463   int iPk = 0;           /* First of nPk registers holding PRIMARY KEY value */
95464   i16 nPk = 1;           /* Number of columns in the PRIMARY KEY */
95465   int iKey;              /* Memory cell holding key of row to be deleted */
95466   i16 nKey;              /* Number of memory cells in the row key */
95467   int iEphCur = 0;       /* Ephemeral table holding all primary key values */
95468   int iRowSet = 0;       /* Register for rowset of rows to delete */
95469   int addrBypass = 0;    /* Address of jump over the delete logic */
95470   int addrLoop = 0;      /* Top of the delete loop */
95471   int addrDelete = 0;    /* Jump directly to the delete logic */
95472   int addrEphOpen = 0;   /* Instruction to open the Ephemeral table */
95473  
95474 #ifndef SQLITE_OMIT_TRIGGER
95475   int isView;                  /* True if attempting to delete from a view */
95476   Trigger *pTrigger;           /* List of table triggers, if required */
95477 #endif
95478
95479   memset(&sContext, 0, sizeof(sContext));
95480   db = pParse->db;
95481   if( pParse->nErr || db->mallocFailed ){
95482     goto delete_from_cleanup;
95483   }
95484   assert( pTabList->nSrc==1 );
95485
95486   /* Locate the table which we want to delete.  This table has to be
95487   ** put in an SrcList structure because some of the subroutines we
95488   ** will be calling are designed to work with multiple tables and expect
95489   ** an SrcList* parameter instead of just a Table* parameter.
95490   */
95491   pTab = sqlite3SrcListLookup(pParse, pTabList);
95492   if( pTab==0 )  goto delete_from_cleanup;
95493
95494   /* Figure out if we have any triggers and if the table being
95495   ** deleted from is a view
95496   */
95497 #ifndef SQLITE_OMIT_TRIGGER
95498   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
95499   isView = pTab->pSelect!=0;
95500 #else
95501 # define pTrigger 0
95502 # define isView 0
95503 #endif
95504 #ifdef SQLITE_OMIT_VIEW
95505 # undef isView
95506 # define isView 0
95507 #endif
95508
95509   /* If pTab is really a view, make sure it has been initialized.
95510   */
95511   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
95512     goto delete_from_cleanup;
95513   }
95514
95515   if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
95516     goto delete_from_cleanup;
95517   }
95518   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
95519   assert( iDb<db->nDb );
95520   zDb = db->aDb[iDb].zName;
95521   rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
95522   assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
95523   if( rcauth==SQLITE_DENY ){
95524     goto delete_from_cleanup;
95525   }
95526   assert(!isView || pTrigger);
95527
95528   /* Assign cursor numbers to the table and all its indices.
95529   */
95530   assert( pTabList->nSrc==1 );
95531   iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
95532   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
95533     pParse->nTab++;
95534   }
95535
95536   /* Start the view context
95537   */
95538   if( isView ){
95539     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
95540   }
95541
95542   /* Begin generating code.
95543   */
95544   v = sqlite3GetVdbe(pParse);
95545   if( v==0 ){
95546     goto delete_from_cleanup;
95547   }
95548   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
95549   sqlite3BeginWriteOperation(pParse, 1, iDb);
95550
95551   /* If we are trying to delete from a view, realize that view into
95552   ** an ephemeral table.
95553   */
95554 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
95555   if( isView ){
95556     sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
95557     iDataCur = iIdxCur = iTabCur;
95558   }
95559 #endif
95560
95561   /* Resolve the column names in the WHERE clause.
95562   */
95563   memset(&sNC, 0, sizeof(sNC));
95564   sNC.pParse = pParse;
95565   sNC.pSrcList = pTabList;
95566   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
95567     goto delete_from_cleanup;
95568   }
95569
95570   /* Initialize the counter of the number of rows deleted, if
95571   ** we are counting rows.
95572   */
95573   if( db->flags & SQLITE_CountRows ){
95574     memCnt = ++pParse->nMem;
95575     sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
95576   }
95577
95578 #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
95579   /* Special case: A DELETE without a WHERE clause deletes everything.
95580   ** It is easier just to erase the whole table. Prior to version 3.6.5,
95581   ** this optimization caused the row change count (the value returned by 
95582   ** API function sqlite3_count_changes) to be set incorrectly.  */
95583   if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab) 
95584    && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
95585   ){
95586     assert( !isView );
95587     sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
95588     if( HasRowid(pTab) ){
95589       sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
95590                         pTab->zName, P4_STATIC);
95591     }
95592     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
95593       assert( pIdx->pSchema==pTab->pSchema );
95594       sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
95595     }
95596   }else
95597 #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
95598   {
95599     if( HasRowid(pTab) ){
95600       /* For a rowid table, initialize the RowSet to an empty set */
95601       pPk = 0;
95602       nPk = 1;
95603       iRowSet = ++pParse->nMem;
95604       sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
95605     }else{
95606       /* For a WITHOUT ROWID table, create an ephemeral table used to
95607       ** hold all primary keys for rows to be deleted. */
95608       pPk = sqlite3PrimaryKeyIndex(pTab);
95609       assert( pPk!=0 );
95610       nPk = pPk->nKeyCol;
95611       iPk = pParse->nMem+1;
95612       pParse->nMem += nPk;
95613       iEphCur = pParse->nTab++;
95614       addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
95615       sqlite3VdbeSetP4KeyInfo(pParse, pPk);
95616     }
95617   
95618     /* Construct a query to find the rowid or primary key for every row
95619     ** to be deleted, based on the WHERE clause.
95620     */
95621     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, 
95622                                WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK,
95623                                iTabCur+1);
95624     if( pWInfo==0 ) goto delete_from_cleanup;
95625     okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
95626   
95627     /* Keep track of the number of rows to be deleted */
95628     if( db->flags & SQLITE_CountRows ){
95629       sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
95630     }
95631   
95632     /* Extract the rowid or primary key for the current row */
95633     if( pPk ){
95634       for(i=0; i<nPk; i++){
95635         sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
95636                                         pPk->aiColumn[i], iPk+i);
95637       }
95638       iKey = iPk;
95639     }else{
95640       iKey = pParse->nMem + 1;
95641       iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
95642       if( iKey>pParse->nMem ) pParse->nMem = iKey;
95643     }
95644   
95645     if( okOnePass ){
95646       /* For ONEPASS, no need to store the rowid/primary-key.  There is only
95647       ** one, so just keep it in its register(s) and fall through to the
95648       ** delete code.
95649       */
95650       nKey = nPk; /* OP_Found will use an unpacked key */
95651       aToOpen = sqlite3DbMallocRaw(db, nIdx+2);
95652       if( aToOpen==0 ){
95653         sqlite3WhereEnd(pWInfo);
95654         goto delete_from_cleanup;
95655       }
95656       memset(aToOpen, 1, nIdx+1);
95657       aToOpen[nIdx+1] = 0;
95658       if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
95659       if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
95660       if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
95661       addrDelete = sqlite3VdbeAddOp0(v, OP_Goto); /* Jump to DELETE logic */
95662     }else if( pPk ){
95663       /* Construct a composite key for the row to be deleted and remember it */
95664       iKey = ++pParse->nMem;
95665       nKey = 0;   /* Zero tells OP_Found to use a composite key */
95666       sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
95667                         sqlite3IndexAffinityStr(v, pPk), nPk);
95668       sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
95669     }else{
95670       /* Get the rowid of the row to be deleted and remember it in the RowSet */
95671       nKey = 1;  /* OP_Seek always uses a single rowid */
95672       sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
95673     }
95674   
95675     /* End of the WHERE loop */
95676     sqlite3WhereEnd(pWInfo);
95677     if( okOnePass ){
95678       /* Bypass the delete logic below if the WHERE loop found zero rows */
95679       addrBypass = sqlite3VdbeMakeLabel(v);
95680       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBypass);
95681       sqlite3VdbeJumpHere(v, addrDelete);
95682     }
95683   
95684     /* Unless this is a view, open cursors for the table we are 
95685     ** deleting from and all its indices. If this is a view, then the
95686     ** only effect this statement has is to fire the INSTEAD OF 
95687     ** triggers.
95688     */
95689     if( !isView ){
95690       testcase( IsVirtual(pTab) );
95691       sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iTabCur, aToOpen,
95692                                  &iDataCur, &iIdxCur);
95693       assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
95694       assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
95695     }
95696   
95697     /* Set up a loop over the rowids/primary-keys that were found in the
95698     ** where-clause loop above.
95699     */
95700     if( okOnePass ){
95701       /* Just one row.  Hence the top-of-loop is a no-op */
95702       assert( nKey==nPk );  /* OP_Found will use an unpacked key */
95703       assert( !IsVirtual(pTab) );
95704       if( aToOpen[iDataCur-iTabCur] ){
95705         assert( pPk!=0 || pTab->pSelect!=0 );
95706         sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
95707         VdbeCoverage(v);
95708       }
95709     }else if( pPk ){
95710       addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
95711       sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
95712       assert( nKey==0 );  /* OP_Found will use a composite key */
95713     }else{
95714       addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
95715       VdbeCoverage(v);
95716       assert( nKey==1 );
95717     }  
95718   
95719     /* Delete the row */
95720 #ifndef SQLITE_OMIT_VIRTUALTABLE
95721     if( IsVirtual(pTab) ){
95722       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
95723       sqlite3VtabMakeWritable(pParse, pTab);
95724       sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
95725       sqlite3VdbeChangeP5(v, OE_Abort);
95726       sqlite3MayAbort(pParse);
95727     }else
95728 #endif
95729     {
95730       int count = (pParse->nested==0);    /* True to count changes */
95731       sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
95732                                iKey, nKey, count, OE_Default, okOnePass);
95733     }
95734   
95735     /* End of the loop over all rowids/primary-keys. */
95736     if( okOnePass ){
95737       sqlite3VdbeResolveLabel(v, addrBypass);
95738     }else if( pPk ){
95739       sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
95740       sqlite3VdbeJumpHere(v, addrLoop);
95741     }else{
95742       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrLoop);
95743       sqlite3VdbeJumpHere(v, addrLoop);
95744     }     
95745   
95746     /* Close the cursors open on the table and its indexes. */
95747     if( !isView && !IsVirtual(pTab) ){
95748       if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
95749       for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
95750         sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
95751       }
95752     }
95753   } /* End non-truncate path */
95754
95755   /* Update the sqlite_sequence table by storing the content of the
95756   ** maximum rowid counter values recorded while inserting into
95757   ** autoincrement tables.
95758   */
95759   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
95760     sqlite3AutoincrementEnd(pParse);
95761   }
95762
95763   /* Return the number of rows that were deleted. If this routine is 
95764   ** generating code because of a call to sqlite3NestedParse(), do not
95765   ** invoke the callback function.
95766   */
95767   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
95768     sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
95769     sqlite3VdbeSetNumCols(v, 1);
95770     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
95771   }
95772
95773 delete_from_cleanup:
95774   sqlite3AuthContextPop(&sContext);
95775   sqlite3SrcListDelete(db, pTabList);
95776   sqlite3ExprDelete(db, pWhere);
95777   sqlite3DbFree(db, aToOpen);
95778   return;
95779 }
95780 /* Make sure "isView" and other macros defined above are undefined. Otherwise
95781 ** they may interfere with compilation of other functions in this file
95782 ** (or in another file, if this file becomes part of the amalgamation).  */
95783 #ifdef isView
95784  #undef isView
95785 #endif
95786 #ifdef pTrigger
95787  #undef pTrigger
95788 #endif
95789
95790 /*
95791 ** This routine generates VDBE code that causes a single row of a
95792 ** single table to be deleted.  Both the original table entry and
95793 ** all indices are removed.
95794 **
95795 ** Preconditions:
95796 **
95797 **   1.  iDataCur is an open cursor on the btree that is the canonical data
95798 **       store for the table.  (This will be either the table itself,
95799 **       in the case of a rowid table, or the PRIMARY KEY index in the case
95800 **       of a WITHOUT ROWID table.)
95801 **
95802 **   2.  Read/write cursors for all indices of pTab must be open as
95803 **       cursor number iIdxCur+i for the i-th index.
95804 **
95805 **   3.  The primary key for the row to be deleted must be stored in a
95806 **       sequence of nPk memory cells starting at iPk.  If nPk==0 that means
95807 **       that a search record formed from OP_MakeRecord is contained in the
95808 **       single memory location iPk.
95809 */
95810 SQLITE_PRIVATE void sqlite3GenerateRowDelete(
95811   Parse *pParse,     /* Parsing context */
95812   Table *pTab,       /* Table containing the row to be deleted */
95813   Trigger *pTrigger, /* List of triggers to (potentially) fire */
95814   int iDataCur,      /* Cursor from which column data is extracted */
95815   int iIdxCur,       /* First index cursor */
95816   int iPk,           /* First memory cell containing the PRIMARY KEY */
95817   i16 nPk,           /* Number of PRIMARY KEY memory cells */
95818   u8 count,          /* If non-zero, increment the row change counter */
95819   u8 onconf,         /* Default ON CONFLICT policy for triggers */
95820   u8 bNoSeek         /* iDataCur is already pointing to the row to delete */
95821 ){
95822   Vdbe *v = pParse->pVdbe;        /* Vdbe */
95823   int iOld = 0;                   /* First register in OLD.* array */
95824   int iLabel;                     /* Label resolved to end of generated code */
95825   u8 opSeek;                      /* Seek opcode */
95826
95827   /* Vdbe is guaranteed to have been allocated by this stage. */
95828   assert( v );
95829   VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
95830                          iDataCur, iIdxCur, iPk, (int)nPk));
95831
95832   /* Seek cursor iCur to the row to delete. If this row no longer exists 
95833   ** (this can happen if a trigger program has already deleted it), do
95834   ** not attempt to delete it or fire any DELETE triggers.  */
95835   iLabel = sqlite3VdbeMakeLabel(v);
95836   opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
95837   if( !bNoSeek ){
95838     sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
95839     VdbeCoverageIf(v, opSeek==OP_NotExists);
95840     VdbeCoverageIf(v, opSeek==OP_NotFound);
95841   }
95842  
95843   /* If there are any triggers to fire, allocate a range of registers to
95844   ** use for the old.* references in the triggers.  */
95845   if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
95846     u32 mask;                     /* Mask of OLD.* columns in use */
95847     int iCol;                     /* Iterator used while populating OLD.* */
95848     int addrStart;                /* Start of BEFORE trigger programs */
95849
95850     /* TODO: Could use temporary registers here. Also could attempt to
95851     ** avoid copying the contents of the rowid register.  */
95852     mask = sqlite3TriggerColmask(
95853         pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
95854     );
95855     mask |= sqlite3FkOldmask(pParse, pTab);
95856     iOld = pParse->nMem+1;
95857     pParse->nMem += (1 + pTab->nCol);
95858
95859     /* Populate the OLD.* pseudo-table register array. These values will be 
95860     ** used by any BEFORE and AFTER triggers that exist.  */
95861     sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
95862     for(iCol=0; iCol<pTab->nCol; iCol++){
95863       testcase( mask!=0xffffffff && iCol==31 );
95864       testcase( mask!=0xffffffff && iCol==32 );
95865       if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
95866         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
95867       }
95868     }
95869
95870     /* Invoke BEFORE DELETE trigger programs. */
95871     addrStart = sqlite3VdbeCurrentAddr(v);
95872     sqlite3CodeRowTrigger(pParse, pTrigger, 
95873         TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
95874     );
95875
95876     /* If any BEFORE triggers were coded, then seek the cursor to the 
95877     ** row to be deleted again. It may be that the BEFORE triggers moved
95878     ** the cursor or of already deleted the row that the cursor was
95879     ** pointing to.
95880     */
95881     if( addrStart<sqlite3VdbeCurrentAddr(v) ){
95882       sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
95883       VdbeCoverageIf(v, opSeek==OP_NotExists);
95884       VdbeCoverageIf(v, opSeek==OP_NotFound);
95885     }
95886
95887     /* Do FK processing. This call checks that any FK constraints that
95888     ** refer to this table (i.e. constraints attached to other tables) 
95889     ** are not violated by deleting this row.  */
95890     sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
95891   }
95892
95893   /* Delete the index and table entries. Skip this step if pTab is really
95894   ** a view (in which case the only effect of the DELETE statement is to
95895   ** fire the INSTEAD OF triggers).  */ 
95896   if( pTab->pSelect==0 ){
95897     sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
95898     sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
95899     if( count ){
95900       sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
95901     }
95902   }
95903
95904   /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
95905   ** handle rows (possibly in other tables) that refer via a foreign key
95906   ** to the row just deleted. */ 
95907   sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
95908
95909   /* Invoke AFTER DELETE trigger programs. */
95910   sqlite3CodeRowTrigger(pParse, pTrigger, 
95911       TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
95912   );
95913
95914   /* Jump here if the row had already been deleted before any BEFORE
95915   ** trigger programs were invoked. Or if a trigger program throws a 
95916   ** RAISE(IGNORE) exception.  */
95917   sqlite3VdbeResolveLabel(v, iLabel);
95918   VdbeModuleComment((v, "END: GenRowDel()"));
95919 }
95920
95921 /*
95922 ** This routine generates VDBE code that causes the deletion of all
95923 ** index entries associated with a single row of a single table, pTab
95924 **
95925 ** Preconditions:
95926 **
95927 **   1.  A read/write cursor "iDataCur" must be open on the canonical storage
95928 **       btree for the table pTab.  (This will be either the table itself
95929 **       for rowid tables or to the primary key index for WITHOUT ROWID
95930 **       tables.)
95931 **
95932 **   2.  Read/write cursors for all indices of pTab must be open as
95933 **       cursor number iIdxCur+i for the i-th index.  (The pTab->pIndex
95934 **       index is the 0-th index.)
95935 **
95936 **   3.  The "iDataCur" cursor must be already be positioned on the row
95937 **       that is to be deleted.
95938 */
95939 SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
95940   Parse *pParse,     /* Parsing and code generating context */
95941   Table *pTab,       /* Table containing the row to be deleted */
95942   int iDataCur,      /* Cursor of table holding data. */
95943   int iIdxCur,       /* First index cursor */
95944   int *aRegIdx       /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
95945 ){
95946   int i;             /* Index loop counter */
95947   int r1 = -1;       /* Register holding an index key */
95948   int iPartIdxLabel; /* Jump destination for skipping partial index entries */
95949   Index *pIdx;       /* Current index */
95950   Index *pPrior = 0; /* Prior index */
95951   Vdbe *v;           /* The prepared statement under construction */
95952   Index *pPk;        /* PRIMARY KEY index, or NULL for rowid tables */
95953
95954   v = pParse->pVdbe;
95955   pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
95956   for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
95957     assert( iIdxCur+i!=iDataCur || pPk==pIdx );
95958     if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
95959     if( pIdx==pPk ) continue;
95960     VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
95961     r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
95962                                  &iPartIdxLabel, pPrior, r1);
95963     sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
95964                       pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
95965     sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
95966     pPrior = pIdx;
95967   }
95968 }
95969
95970 /*
95971 ** Generate code that will assemble an index key and stores it in register
95972 ** regOut.  The key with be for index pIdx which is an index on pTab.
95973 ** iCur is the index of a cursor open on the pTab table and pointing to
95974 ** the entry that needs indexing.  If pTab is a WITHOUT ROWID table, then
95975 ** iCur must be the cursor of the PRIMARY KEY index.
95976 **
95977 ** Return a register number which is the first in a block of
95978 ** registers that holds the elements of the index key.  The
95979 ** block of registers has already been deallocated by the time
95980 ** this routine returns.
95981 **
95982 ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
95983 ** to that label if pIdx is a partial index that should be skipped.
95984 ** The label should be resolved using sqlite3ResolvePartIdxLabel().
95985 ** A partial index should be skipped if its WHERE clause evaluates
95986 ** to false or null.  If pIdx is not a partial index, *piPartIdxLabel
95987 ** will be set to zero which is an empty label that is ignored by
95988 ** sqlite3ResolvePartIdxLabel().
95989 **
95990 ** The pPrior and regPrior parameters are used to implement a cache to
95991 ** avoid unnecessary register loads.  If pPrior is not NULL, then it is
95992 ** a pointer to a different index for which an index key has just been
95993 ** computed into register regPrior.  If the current pIdx index is generating
95994 ** its key into the same sequence of registers and if pPrior and pIdx share
95995 ** a column in common, then the register corresponding to that column already
95996 ** holds the correct value and the loading of that register is skipped.
95997 ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK 
95998 ** on a table with multiple indices, and especially with the ROWID or
95999 ** PRIMARY KEY columns of the index.
96000 */
96001 SQLITE_PRIVATE int sqlite3GenerateIndexKey(
96002   Parse *pParse,       /* Parsing context */
96003   Index *pIdx,         /* The index for which to generate a key */
96004   int iDataCur,        /* Cursor number from which to take column data */
96005   int regOut,          /* Put the new key into this register if not 0 */
96006   int prefixOnly,      /* Compute only a unique prefix of the key */
96007   int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
96008   Index *pPrior,       /* Previously generated index key */
96009   int regPrior         /* Register holding previous generated key */
96010 ){
96011   Vdbe *v = pParse->pVdbe;
96012   int j;
96013   Table *pTab = pIdx->pTable;
96014   int regBase;
96015   int nCol;
96016
96017   if( piPartIdxLabel ){
96018     if( pIdx->pPartIdxWhere ){
96019       *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
96020       pParse->iPartIdxTab = iDataCur;
96021       sqlite3ExprCachePush(pParse);
96022       sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel, 
96023                          SQLITE_JUMPIFNULL);
96024     }else{
96025       *piPartIdxLabel = 0;
96026     }
96027   }
96028   nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
96029   regBase = sqlite3GetTempRange(pParse, nCol);
96030   if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
96031   for(j=0; j<nCol; j++){
96032     if( pPrior && pPrior->aiColumn[j]==pIdx->aiColumn[j] ) continue;
96033     sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pIdx->aiColumn[j],
96034                                     regBase+j);
96035     /* If the column affinity is REAL but the number is an integer, then it
96036     ** might be stored in the table as an integer (using a compact
96037     ** representation) then converted to REAL by an OP_RealAffinity opcode.
96038     ** But we are getting ready to store this value back into an index, where
96039     ** it should be converted by to INTEGER again.  So omit the OP_RealAffinity
96040     ** opcode if it is present */
96041     sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
96042   }
96043   if( regOut ){
96044     sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
96045   }
96046   sqlite3ReleaseTempRange(pParse, regBase, nCol);
96047   return regBase;
96048 }
96049
96050 /*
96051 ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
96052 ** because it was a partial index, then this routine should be called to
96053 ** resolve that label.
96054 */
96055 SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
96056   if( iLabel ){
96057     sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
96058     sqlite3ExprCachePop(pParse);
96059   }
96060 }
96061
96062 /************** End of delete.c **********************************************/
96063 /************** Begin file func.c ********************************************/
96064 /*
96065 ** 2002 February 23
96066 **
96067 ** The author disclaims copyright to this source code.  In place of
96068 ** a legal notice, here is a blessing:
96069 **
96070 **    May you do good and not evil.
96071 **    May you find forgiveness for yourself and forgive others.
96072 **    May you share freely, never taking more than you give.
96073 **
96074 *************************************************************************
96075 ** This file contains the C-language implementations for many of the SQL
96076 ** functions of SQLite.  (Some function, and in particular the date and
96077 ** time functions, are implemented separately.)
96078 */
96079 /* #include <stdlib.h> */
96080 /* #include <assert.h> */
96081
96082 /*
96083 ** Return the collating function associated with a function.
96084 */
96085 static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
96086   VdbeOp *pOp;
96087   assert( context->pVdbe!=0 );
96088   pOp = &context->pVdbe->aOp[context->iOp-1];
96089   assert( pOp->opcode==OP_CollSeq );
96090   assert( pOp->p4type==P4_COLLSEQ );
96091   return pOp->p4.pColl;
96092 }
96093
96094 /*
96095 ** Indicate that the accumulator load should be skipped on this
96096 ** iteration of the aggregate loop.
96097 */
96098 static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
96099   context->skipFlag = 1;
96100 }
96101
96102 /*
96103 ** Implementation of the non-aggregate min() and max() functions
96104 */
96105 static void minmaxFunc(
96106   sqlite3_context *context,
96107   int argc,
96108   sqlite3_value **argv
96109 ){
96110   int i;
96111   int mask;    /* 0 for min() or 0xffffffff for max() */
96112   int iBest;
96113   CollSeq *pColl;
96114
96115   assert( argc>1 );
96116   mask = sqlite3_user_data(context)==0 ? 0 : -1;
96117   pColl = sqlite3GetFuncCollSeq(context);
96118   assert( pColl );
96119   assert( mask==-1 || mask==0 );
96120   iBest = 0;
96121   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
96122   for(i=1; i<argc; i++){
96123     if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
96124     if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
96125       testcase( mask==0 );
96126       iBest = i;
96127     }
96128   }
96129   sqlite3_result_value(context, argv[iBest]);
96130 }
96131
96132 /*
96133 ** Return the type of the argument.
96134 */
96135 static void typeofFunc(
96136   sqlite3_context *context,
96137   int NotUsed,
96138   sqlite3_value **argv
96139 ){
96140   const char *z = 0;
96141   UNUSED_PARAMETER(NotUsed);
96142   switch( sqlite3_value_type(argv[0]) ){
96143     case SQLITE_INTEGER: z = "integer"; break;
96144     case SQLITE_TEXT:    z = "text";    break;
96145     case SQLITE_FLOAT:   z = "real";    break;
96146     case SQLITE_BLOB:    z = "blob";    break;
96147     default:             z = "null";    break;
96148   }
96149   sqlite3_result_text(context, z, -1, SQLITE_STATIC);
96150 }
96151
96152
96153 /*
96154 ** Implementation of the length() function
96155 */
96156 static void lengthFunc(
96157   sqlite3_context *context,
96158   int argc,
96159   sqlite3_value **argv
96160 ){
96161   int len;
96162
96163   assert( argc==1 );
96164   UNUSED_PARAMETER(argc);
96165   switch( sqlite3_value_type(argv[0]) ){
96166     case SQLITE_BLOB:
96167     case SQLITE_INTEGER:
96168     case SQLITE_FLOAT: {
96169       sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
96170       break;
96171     }
96172     case SQLITE_TEXT: {
96173       const unsigned char *z = sqlite3_value_text(argv[0]);
96174       if( z==0 ) return;
96175       len = 0;
96176       while( *z ){
96177         len++;
96178         SQLITE_SKIP_UTF8(z);
96179       }
96180       sqlite3_result_int(context, len);
96181       break;
96182     }
96183     default: {
96184       sqlite3_result_null(context);
96185       break;
96186     }
96187   }
96188 }
96189
96190 /*
96191 ** Implementation of the abs() function.
96192 **
96193 ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
96194 ** the numeric argument X. 
96195 */
96196 static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
96197   assert( argc==1 );
96198   UNUSED_PARAMETER(argc);
96199   switch( sqlite3_value_type(argv[0]) ){
96200     case SQLITE_INTEGER: {
96201       i64 iVal = sqlite3_value_int64(argv[0]);
96202       if( iVal<0 ){
96203         if( iVal==SMALLEST_INT64 ){
96204           /* IMP: R-31676-45509 If X is the integer -9223372036854775808
96205           ** then abs(X) throws an integer overflow error since there is no
96206           ** equivalent positive 64-bit two complement value. */
96207           sqlite3_result_error(context, "integer overflow", -1);
96208           return;
96209         }
96210         iVal = -iVal;
96211       } 
96212       sqlite3_result_int64(context, iVal);
96213       break;
96214     }
96215     case SQLITE_NULL: {
96216       /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
96217       sqlite3_result_null(context);
96218       break;
96219     }
96220     default: {
96221       /* Because sqlite3_value_double() returns 0.0 if the argument is not
96222       ** something that can be converted into a number, we have:
96223       ** IMP: R-01992-00519 Abs(X) returns 0.0 if X is a string or blob
96224       ** that cannot be converted to a numeric value.
96225       */
96226       double rVal = sqlite3_value_double(argv[0]);
96227       if( rVal<0 ) rVal = -rVal;
96228       sqlite3_result_double(context, rVal);
96229       break;
96230     }
96231   }
96232 }
96233
96234 /*
96235 ** Implementation of the instr() function.
96236 **
96237 ** instr(haystack,needle) finds the first occurrence of needle
96238 ** in haystack and returns the number of previous characters plus 1,
96239 ** or 0 if needle does not occur within haystack.
96240 **
96241 ** If both haystack and needle are BLOBs, then the result is one more than
96242 ** the number of bytes in haystack prior to the first occurrence of needle,
96243 ** or 0 if needle never occurs in haystack.
96244 */
96245 static void instrFunc(
96246   sqlite3_context *context,
96247   int argc,
96248   sqlite3_value **argv
96249 ){
96250   const unsigned char *zHaystack;
96251   const unsigned char *zNeedle;
96252   int nHaystack;
96253   int nNeedle;
96254   int typeHaystack, typeNeedle;
96255   int N = 1;
96256   int isText;
96257
96258   UNUSED_PARAMETER(argc);
96259   typeHaystack = sqlite3_value_type(argv[0]);
96260   typeNeedle = sqlite3_value_type(argv[1]);
96261   if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
96262   nHaystack = sqlite3_value_bytes(argv[0]);
96263   nNeedle = sqlite3_value_bytes(argv[1]);
96264   if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
96265     zHaystack = sqlite3_value_blob(argv[0]);
96266     zNeedle = sqlite3_value_blob(argv[1]);
96267     isText = 0;
96268   }else{
96269     zHaystack = sqlite3_value_text(argv[0]);
96270     zNeedle = sqlite3_value_text(argv[1]);
96271     isText = 1;
96272   }
96273   while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
96274     N++;
96275     do{
96276       nHaystack--;
96277       zHaystack++;
96278     }while( isText && (zHaystack[0]&0xc0)==0x80 );
96279   }
96280   if( nNeedle>nHaystack ) N = 0;
96281   sqlite3_result_int(context, N);
96282 }
96283
96284 /*
96285 ** Implementation of the printf() function.
96286 */
96287 static void printfFunc(
96288   sqlite3_context *context,
96289   int argc,
96290   sqlite3_value **argv
96291 ){
96292   PrintfArguments x;
96293   StrAccum str;
96294   const char *zFormat;
96295   int n;
96296
96297   if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
96298     x.nArg = argc-1;
96299     x.nUsed = 0;
96300     x.apArg = argv+1;
96301     sqlite3StrAccumInit(&str, 0, 0, SQLITE_MAX_LENGTH);
96302     str.db = sqlite3_context_db_handle(context);
96303     sqlite3XPrintf(&str, SQLITE_PRINTF_SQLFUNC, zFormat, &x);
96304     n = str.nChar;
96305     sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
96306                         SQLITE_DYNAMIC);
96307   }
96308 }
96309
96310 /*
96311 ** Implementation of the substr() function.
96312 **
96313 ** substr(x,p1,p2)  returns p2 characters of x[] beginning with p1.
96314 ** p1 is 1-indexed.  So substr(x,1,1) returns the first character
96315 ** of x.  If x is text, then we actually count UTF-8 characters.
96316 ** If x is a blob, then we count bytes.
96317 **
96318 ** If p1 is negative, then we begin abs(p1) from the end of x[].
96319 **
96320 ** If p2 is negative, return the p2 characters preceding p1.
96321 */
96322 static void substrFunc(
96323   sqlite3_context *context,
96324   int argc,
96325   sqlite3_value **argv
96326 ){
96327   const unsigned char *z;
96328   const unsigned char *z2;
96329   int len;
96330   int p0type;
96331   i64 p1, p2;
96332   int negP2 = 0;
96333
96334   assert( argc==3 || argc==2 );
96335   if( sqlite3_value_type(argv[1])==SQLITE_NULL
96336    || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
96337   ){
96338     return;
96339   }
96340   p0type = sqlite3_value_type(argv[0]);
96341   p1 = sqlite3_value_int(argv[1]);
96342   if( p0type==SQLITE_BLOB ){
96343     len = sqlite3_value_bytes(argv[0]);
96344     z = sqlite3_value_blob(argv[0]);
96345     if( z==0 ) return;
96346     assert( len==sqlite3_value_bytes(argv[0]) );
96347   }else{
96348     z = sqlite3_value_text(argv[0]);
96349     if( z==0 ) return;
96350     len = 0;
96351     if( p1<0 ){
96352       for(z2=z; *z2; len++){
96353         SQLITE_SKIP_UTF8(z2);
96354       }
96355     }
96356   }
96357 #ifdef SQLITE_SUBSTR_COMPATIBILITY
96358   /* If SUBSTR_COMPATIBILITY is defined then substr(X,0,N) work the same as
96359   ** as substr(X,1,N) - it returns the first N characters of X.  This
96360   ** is essentially a back-out of the bug-fix in check-in [5fc125d362df4b8]
96361   ** from 2009-02-02 for compatibility of applications that exploited the
96362   ** old buggy behavior. */
96363   if( p1==0 ) p1 = 1; /* <rdar://problem/6778339> */
96364 #endif
96365   if( argc==3 ){
96366     p2 = sqlite3_value_int(argv[2]);
96367     if( p2<0 ){
96368       p2 = -p2;
96369       negP2 = 1;
96370     }
96371   }else{
96372     p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
96373   }
96374   if( p1<0 ){
96375     p1 += len;
96376     if( p1<0 ){
96377       p2 += p1;
96378       if( p2<0 ) p2 = 0;
96379       p1 = 0;
96380     }
96381   }else if( p1>0 ){
96382     p1--;
96383   }else if( p2>0 ){
96384     p2--;
96385   }
96386   if( negP2 ){
96387     p1 -= p2;
96388     if( p1<0 ){
96389       p2 += p1;
96390       p1 = 0;
96391     }
96392   }
96393   assert( p1>=0 && p2>=0 );
96394   if( p0type!=SQLITE_BLOB ){
96395     while( *z && p1 ){
96396       SQLITE_SKIP_UTF8(z);
96397       p1--;
96398     }
96399     for(z2=z; *z2 && p2; p2--){
96400       SQLITE_SKIP_UTF8(z2);
96401     }
96402     sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
96403                           SQLITE_UTF8);
96404   }else{
96405     if( p1+p2>len ){
96406       p2 = len-p1;
96407       if( p2<0 ) p2 = 0;
96408     }
96409     sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
96410   }
96411 }
96412
96413 /*
96414 ** Implementation of the round() function
96415 */
96416 #ifndef SQLITE_OMIT_FLOATING_POINT
96417 static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
96418   int n = 0;
96419   double r;
96420   char *zBuf;
96421   assert( argc==1 || argc==2 );
96422   if( argc==2 ){
96423     if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
96424     n = sqlite3_value_int(argv[1]);
96425     if( n>30 ) n = 30;
96426     if( n<0 ) n = 0;
96427   }
96428   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
96429   r = sqlite3_value_double(argv[0]);
96430   /* If Y==0 and X will fit in a 64-bit int,
96431   ** handle the rounding directly,
96432   ** otherwise use printf.
96433   */
96434   if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
96435     r = (double)((sqlite_int64)(r+0.5));
96436   }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
96437     r = -(double)((sqlite_int64)((-r)+0.5));
96438   }else{
96439     zBuf = sqlite3_mprintf("%.*f",n,r);
96440     if( zBuf==0 ){
96441       sqlite3_result_error_nomem(context);
96442       return;
96443     }
96444     sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
96445     sqlite3_free(zBuf);
96446   }
96447   sqlite3_result_double(context, r);
96448 }
96449 #endif
96450
96451 /*
96452 ** Allocate nByte bytes of space using sqlite3_malloc(). If the
96453 ** allocation fails, call sqlite3_result_error_nomem() to notify
96454 ** the database handle that malloc() has failed and return NULL.
96455 ** If nByte is larger than the maximum string or blob length, then
96456 ** raise an SQLITE_TOOBIG exception and return NULL.
96457 */
96458 static void *contextMalloc(sqlite3_context *context, i64 nByte){
96459   char *z;
96460   sqlite3 *db = sqlite3_context_db_handle(context);
96461   assert( nByte>0 );
96462   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
96463   testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
96464   if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
96465     sqlite3_result_error_toobig(context);
96466     z = 0;
96467   }else{
96468     z = sqlite3Malloc(nByte);
96469     if( !z ){
96470       sqlite3_result_error_nomem(context);
96471     }
96472   }
96473   return z;
96474 }
96475
96476 /*
96477 ** Implementation of the upper() and lower() SQL functions.
96478 */
96479 static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
96480   char *z1;
96481   const char *z2;
96482   int i, n;
96483   UNUSED_PARAMETER(argc);
96484   z2 = (char*)sqlite3_value_text(argv[0]);
96485   n = sqlite3_value_bytes(argv[0]);
96486   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
96487   assert( z2==(char*)sqlite3_value_text(argv[0]) );
96488   if( z2 ){
96489     z1 = contextMalloc(context, ((i64)n)+1);
96490     if( z1 ){
96491       for(i=0; i<n; i++){
96492         z1[i] = (char)sqlite3Toupper(z2[i]);
96493       }
96494       sqlite3_result_text(context, z1, n, sqlite3_free);
96495     }
96496   }
96497 }
96498 static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
96499   char *z1;
96500   const char *z2;
96501   int i, n;
96502   UNUSED_PARAMETER(argc);
96503   z2 = (char*)sqlite3_value_text(argv[0]);
96504   n = sqlite3_value_bytes(argv[0]);
96505   /* Verify that the call to _bytes() does not invalidate the _text() pointer */
96506   assert( z2==(char*)sqlite3_value_text(argv[0]) );
96507   if( z2 ){
96508     z1 = contextMalloc(context, ((i64)n)+1);
96509     if( z1 ){
96510       for(i=0; i<n; i++){
96511         z1[i] = sqlite3Tolower(z2[i]);
96512       }
96513       sqlite3_result_text(context, z1, n, sqlite3_free);
96514     }
96515   }
96516 }
96517
96518 /*
96519 ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
96520 ** as VDBE code so that unused argument values do not have to be computed.
96521 ** However, we still need some kind of function implementation for this
96522 ** routines in the function table.  The noopFunc macro provides this.
96523 ** noopFunc will never be called so it doesn't matter what the implementation
96524 ** is.  We might as well use the "version()" function as a substitute.
96525 */
96526 #define noopFunc versionFunc   /* Substitute function - never called */
96527
96528 /*
96529 ** Implementation of random().  Return a random integer.  
96530 */
96531 static void randomFunc(
96532   sqlite3_context *context,
96533   int NotUsed,
96534   sqlite3_value **NotUsed2
96535 ){
96536   sqlite_int64 r;
96537   UNUSED_PARAMETER2(NotUsed, NotUsed2);
96538   sqlite3_randomness(sizeof(r), &r);
96539   if( r<0 ){
96540     /* We need to prevent a random number of 0x8000000000000000 
96541     ** (or -9223372036854775808) since when you do abs() of that
96542     ** number of you get the same value back again.  To do this
96543     ** in a way that is testable, mask the sign bit off of negative
96544     ** values, resulting in a positive value.  Then take the 
96545     ** 2s complement of that positive value.  The end result can
96546     ** therefore be no less than -9223372036854775807.
96547     */
96548     r = -(r & LARGEST_INT64);
96549   }
96550   sqlite3_result_int64(context, r);
96551 }
96552
96553 /*
96554 ** Implementation of randomblob(N).  Return a random blob
96555 ** that is N bytes long.
96556 */
96557 static void randomBlob(
96558   sqlite3_context *context,
96559   int argc,
96560   sqlite3_value **argv
96561 ){
96562   int n;
96563   unsigned char *p;
96564   assert( argc==1 );
96565   UNUSED_PARAMETER(argc);
96566   n = sqlite3_value_int(argv[0]);
96567   if( n<1 ){
96568     n = 1;
96569   }
96570   p = contextMalloc(context, n);
96571   if( p ){
96572     sqlite3_randomness(n, p);
96573     sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
96574   }
96575 }
96576
96577 /*
96578 ** Implementation of the last_insert_rowid() SQL function.  The return
96579 ** value is the same as the sqlite3_last_insert_rowid() API function.
96580 */
96581 static void last_insert_rowid(
96582   sqlite3_context *context, 
96583   int NotUsed, 
96584   sqlite3_value **NotUsed2
96585 ){
96586   sqlite3 *db = sqlite3_context_db_handle(context);
96587   UNUSED_PARAMETER2(NotUsed, NotUsed2);
96588   /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
96589   ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
96590   ** function. */
96591   sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
96592 }
96593
96594 /*
96595 ** Implementation of the changes() SQL function.
96596 **
96597 ** IMP: R-62073-11209 The changes() SQL function is a wrapper
96598 ** around the sqlite3_changes() C/C++ function and hence follows the same
96599 ** rules for counting changes.
96600 */
96601 static void changes(
96602   sqlite3_context *context,
96603   int NotUsed,
96604   sqlite3_value **NotUsed2
96605 ){
96606   sqlite3 *db = sqlite3_context_db_handle(context);
96607   UNUSED_PARAMETER2(NotUsed, NotUsed2);
96608   sqlite3_result_int(context, sqlite3_changes(db));
96609 }
96610
96611 /*
96612 ** Implementation of the total_changes() SQL function.  The return value is
96613 ** the same as the sqlite3_total_changes() API function.
96614 */
96615 static void total_changes(
96616   sqlite3_context *context,
96617   int NotUsed,
96618   sqlite3_value **NotUsed2
96619 ){
96620   sqlite3 *db = sqlite3_context_db_handle(context);
96621   UNUSED_PARAMETER2(NotUsed, NotUsed2);
96622   /* IMP: R-52756-41993 This function is a wrapper around the
96623   ** sqlite3_total_changes() C/C++ interface. */
96624   sqlite3_result_int(context, sqlite3_total_changes(db));
96625 }
96626
96627 /*
96628 ** A structure defining how to do GLOB-style comparisons.
96629 */
96630 struct compareInfo {
96631   u8 matchAll;
96632   u8 matchOne;
96633   u8 matchSet;
96634   u8 noCase;
96635 };
96636
96637 /*
96638 ** For LIKE and GLOB matching on EBCDIC machines, assume that every
96639 ** character is exactly one byte in size.  Also, all characters are
96640 ** able to participate in upper-case-to-lower-case mappings in EBCDIC
96641 ** whereas only characters less than 0x80 do in ASCII.
96642 */
96643 #if defined(SQLITE_EBCDIC)
96644 # define sqlite3Utf8Read(A)        (*((*A)++))
96645 # define GlobUpperToLower(A)       A = sqlite3UpperToLower[A]
96646 # define GlobUpperToLowerAscii(A)  A = sqlite3UpperToLower[A]
96647 #else
96648 # define GlobUpperToLower(A)       if( A<=0x7f ){ A = sqlite3UpperToLower[A]; }
96649 # define GlobUpperToLowerAscii(A)  A = sqlite3UpperToLower[A]
96650 #endif
96651
96652 static const struct compareInfo globInfo = { '*', '?', '[', 0 };
96653 /* The correct SQL-92 behavior is for the LIKE operator to ignore
96654 ** case.  Thus  'a' LIKE 'A' would be true. */
96655 static const struct compareInfo likeInfoNorm = { '%', '_',   0, 1 };
96656 /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
96657 ** is case sensitive causing 'a' LIKE 'A' to be false */
96658 static const struct compareInfo likeInfoAlt = { '%', '_',   0, 0 };
96659
96660 /*
96661 ** Compare two UTF-8 strings for equality where the first string can
96662 ** potentially be a "glob" or "like" expression.  Return true (1) if they
96663 ** are the same and false (0) if they are different.
96664 **
96665 ** Globbing rules:
96666 **
96667 **      '*'       Matches any sequence of zero or more characters.
96668 **
96669 **      '?'       Matches exactly one character.
96670 **
96671 **     [...]      Matches one character from the enclosed list of
96672 **                characters.
96673 **
96674 **     [^...]     Matches one character not in the enclosed list.
96675 **
96676 ** With the [...] and [^...] matching, a ']' character can be included
96677 ** in the list by making it the first character after '[' or '^'.  A
96678 ** range of characters can be specified using '-'.  Example:
96679 ** "[a-z]" matches any single lower-case letter.  To match a '-', make
96680 ** it the last character in the list.
96681 **
96682 ** Like matching rules:
96683 ** 
96684 **      '%'       Matches any sequence of zero or more characters
96685 **
96686 ***     '_'       Matches any one character
96687 **
96688 **      Ec        Where E is the "esc" character and c is any other
96689 **                character, including '%', '_', and esc, match exactly c.
96690 **
96691 ** The comments through this routine usually assume glob matching.
96692 **
96693 ** This routine is usually quick, but can be N**2 in the worst case.
96694 */
96695 static int patternCompare(
96696   const u8 *zPattern,              /* The glob pattern */
96697   const u8 *zString,               /* The string to compare against the glob */
96698   const struct compareInfo *pInfo, /* Information about how to do the compare */
96699   u32 esc                          /* The escape character */
96700 ){
96701   u32 c, c2;                       /* Next pattern and input string chars */
96702   u32 matchOne = pInfo->matchOne;  /* "?" or "_" */
96703   u32 matchAll = pInfo->matchAll;  /* "*" or "%" */
96704   u32 matchOther;                  /* "[" or the escape character */
96705   u8 noCase = pInfo->noCase;       /* True if uppercase==lowercase */
96706   const u8 *zEscaped = 0;          /* One past the last escaped input char */
96707   
96708   /* The GLOB operator does not have an ESCAPE clause.  And LIKE does not
96709   ** have the matchSet operator.  So we either have to look for one or
96710   ** the other, never both.  Hence the single variable matchOther is used
96711   ** to store the one we have to look for.
96712   */
96713   matchOther = esc ? esc : pInfo->matchSet;
96714
96715   while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
96716     if( c==matchAll ){  /* Match "*" */
96717       /* Skip over multiple "*" characters in the pattern.  If there
96718       ** are also "?" characters, skip those as well, but consume a
96719       ** single character of the input string for each "?" skipped */
96720       while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
96721                || c == matchOne ){
96722         if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
96723           return 0;
96724         }
96725       }
96726       if( c==0 ){
96727         return 1;   /* "*" at the end of the pattern matches */
96728       }else if( c==matchOther ){
96729         if( esc ){
96730           c = sqlite3Utf8Read(&zPattern);
96731           if( c==0 ) return 0;
96732         }else{
96733           /* "[...]" immediately follows the "*".  We have to do a slow
96734           ** recursive search in this case, but it is an unusual case. */
96735           assert( matchOther<0x80 );  /* '[' is a single-byte character */
96736           while( *zString
96737                  && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
96738             SQLITE_SKIP_UTF8(zString);
96739           }
96740           return *zString!=0;
96741         }
96742       }
96743
96744       /* At this point variable c contains the first character of the
96745       ** pattern string past the "*".  Search in the input string for the
96746       ** first matching character and recursively contine the match from
96747       ** that point.
96748       **
96749       ** For a case-insensitive search, set variable cx to be the same as
96750       ** c but in the other case and search the input string for either
96751       ** c or cx.
96752       */
96753       if( c<=0x80 ){
96754         u32 cx;
96755         if( noCase ){
96756           cx = sqlite3Toupper(c);
96757           c = sqlite3Tolower(c);
96758         }else{
96759           cx = c;
96760         }
96761         while( (c2 = *(zString++))!=0 ){
96762           if( c2!=c && c2!=cx ) continue;
96763           if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
96764         }
96765       }else{
96766         while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
96767           if( c2!=c ) continue;
96768           if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
96769         }
96770       }
96771       return 0;
96772     }
96773     if( c==matchOther ){
96774       if( esc ){
96775         c = sqlite3Utf8Read(&zPattern);
96776         if( c==0 ) return 0;
96777         zEscaped = zPattern;
96778       }else{
96779         u32 prior_c = 0;
96780         int seen = 0;
96781         int invert = 0;
96782         c = sqlite3Utf8Read(&zString);
96783         if( c==0 ) return 0;
96784         c2 = sqlite3Utf8Read(&zPattern);
96785         if( c2=='^' ){
96786           invert = 1;
96787           c2 = sqlite3Utf8Read(&zPattern);
96788         }
96789         if( c2==']' ){
96790           if( c==']' ) seen = 1;
96791           c2 = sqlite3Utf8Read(&zPattern);
96792         }
96793         while( c2 && c2!=']' ){
96794           if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
96795             c2 = sqlite3Utf8Read(&zPattern);
96796             if( c>=prior_c && c<=c2 ) seen = 1;
96797             prior_c = 0;
96798           }else{
96799             if( c==c2 ){
96800               seen = 1;
96801             }
96802             prior_c = c2;
96803           }
96804           c2 = sqlite3Utf8Read(&zPattern);
96805         }
96806         if( c2==0 || (seen ^ invert)==0 ){
96807           return 0;
96808         }
96809         continue;
96810       }
96811     }
96812     c2 = sqlite3Utf8Read(&zString);
96813     if( c==c2 ) continue;
96814     if( noCase && c<0x80 && c2<0x80 && sqlite3Tolower(c)==sqlite3Tolower(c2) ){
96815       continue;
96816     }
96817     if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
96818     return 0;
96819   }
96820   return *zString==0;
96821 }
96822
96823 /*
96824 ** The sqlite3_strglob() interface.
96825 */
96826 SQLITE_API int SQLITE_STDCALL sqlite3_strglob(const char *zGlobPattern, const char *zString){
96827   return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
96828 }
96829
96830 /*
96831 ** Count the number of times that the LIKE operator (or GLOB which is
96832 ** just a variation of LIKE) gets called.  This is used for testing
96833 ** only.
96834 */
96835 #ifdef SQLITE_TEST
96836 SQLITE_API int sqlite3_like_count = 0;
96837 #endif
96838
96839
96840 /*
96841 ** Implementation of the like() SQL function.  This function implements
96842 ** the build-in LIKE operator.  The first argument to the function is the
96843 ** pattern and the second argument is the string.  So, the SQL statements:
96844 **
96845 **       A LIKE B
96846 **
96847 ** is implemented as like(B,A).
96848 **
96849 ** This same function (with a different compareInfo structure) computes
96850 ** the GLOB operator.
96851 */
96852 static void likeFunc(
96853   sqlite3_context *context, 
96854   int argc, 
96855   sqlite3_value **argv
96856 ){
96857   const unsigned char *zA, *zB;
96858   u32 escape = 0;
96859   int nPat;
96860   sqlite3 *db = sqlite3_context_db_handle(context);
96861
96862   zB = sqlite3_value_text(argv[0]);
96863   zA = sqlite3_value_text(argv[1]);
96864
96865   /* Limit the length of the LIKE or GLOB pattern to avoid problems
96866   ** of deep recursion and N*N behavior in patternCompare().
96867   */
96868   nPat = sqlite3_value_bytes(argv[0]);
96869   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
96870   testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
96871   if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
96872     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
96873     return;
96874   }
96875   assert( zB==sqlite3_value_text(argv[0]) );  /* Encoding did not change */
96876
96877   if( argc==3 ){
96878     /* The escape character string must consist of a single UTF-8 character.
96879     ** Otherwise, return an error.
96880     */
96881     const unsigned char *zEsc = sqlite3_value_text(argv[2]);
96882     if( zEsc==0 ) return;
96883     if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
96884       sqlite3_result_error(context, 
96885           "ESCAPE expression must be a single character", -1);
96886       return;
96887     }
96888     escape = sqlite3Utf8Read(&zEsc);
96889   }
96890   if( zA && zB ){
96891     struct compareInfo *pInfo = sqlite3_user_data(context);
96892 #ifdef SQLITE_TEST
96893     sqlite3_like_count++;
96894 #endif
96895     
96896     sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
96897   }
96898 }
96899
96900 /*
96901 ** Implementation of the NULLIF(x,y) function.  The result is the first
96902 ** argument if the arguments are different.  The result is NULL if the
96903 ** arguments are equal to each other.
96904 */
96905 static void nullifFunc(
96906   sqlite3_context *context,
96907   int NotUsed,
96908   sqlite3_value **argv
96909 ){
96910   CollSeq *pColl = sqlite3GetFuncCollSeq(context);
96911   UNUSED_PARAMETER(NotUsed);
96912   if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
96913     sqlite3_result_value(context, argv[0]);
96914   }
96915 }
96916
96917 /*
96918 ** Implementation of the sqlite_version() function.  The result is the version
96919 ** of the SQLite library that is running.
96920 */
96921 static void versionFunc(
96922   sqlite3_context *context,
96923   int NotUsed,
96924   sqlite3_value **NotUsed2
96925 ){
96926   UNUSED_PARAMETER2(NotUsed, NotUsed2);
96927   /* IMP: R-48699-48617 This function is an SQL wrapper around the
96928   ** sqlite3_libversion() C-interface. */
96929   sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
96930 }
96931
96932 /*
96933 ** Implementation of the sqlite_source_id() function. The result is a string
96934 ** that identifies the particular version of the source code used to build
96935 ** SQLite.
96936 */
96937 static void sourceidFunc(
96938   sqlite3_context *context,
96939   int NotUsed,
96940   sqlite3_value **NotUsed2
96941 ){
96942   UNUSED_PARAMETER2(NotUsed, NotUsed2);
96943   /* IMP: R-24470-31136 This function is an SQL wrapper around the
96944   ** sqlite3_sourceid() C interface. */
96945   sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
96946 }
96947
96948 /*
96949 ** Implementation of the sqlite_log() function.  This is a wrapper around
96950 ** sqlite3_log().  The return value is NULL.  The function exists purely for
96951 ** its side-effects.
96952 */
96953 static void errlogFunc(
96954   sqlite3_context *context,
96955   int argc,
96956   sqlite3_value **argv
96957 ){
96958   UNUSED_PARAMETER(argc);
96959   UNUSED_PARAMETER(context);
96960   sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
96961 }
96962
96963 /*
96964 ** Implementation of the sqlite_compileoption_used() function.
96965 ** The result is an integer that identifies if the compiler option
96966 ** was used to build SQLite.
96967 */
96968 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
96969 static void compileoptionusedFunc(
96970   sqlite3_context *context,
96971   int argc,
96972   sqlite3_value **argv
96973 ){
96974   const char *zOptName;
96975   assert( argc==1 );
96976   UNUSED_PARAMETER(argc);
96977   /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
96978   ** function is a wrapper around the sqlite3_compileoption_used() C/C++
96979   ** function.
96980   */
96981   if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
96982     sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
96983   }
96984 }
96985 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
96986
96987 /*
96988 ** Implementation of the sqlite_compileoption_get() function. 
96989 ** The result is a string that identifies the compiler options 
96990 ** used to build SQLite.
96991 */
96992 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
96993 static void compileoptiongetFunc(
96994   sqlite3_context *context,
96995   int argc,
96996   sqlite3_value **argv
96997 ){
96998   int n;
96999   assert( argc==1 );
97000   UNUSED_PARAMETER(argc);
97001   /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
97002   ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
97003   */
97004   n = sqlite3_value_int(argv[0]);
97005   sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
97006 }
97007 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
97008
97009 /* Array for converting from half-bytes (nybbles) into ASCII hex
97010 ** digits. */
97011 static const char hexdigits[] = {
97012   '0', '1', '2', '3', '4', '5', '6', '7',
97013   '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' 
97014 };
97015
97016 /*
97017 ** Implementation of the QUOTE() function.  This function takes a single
97018 ** argument.  If the argument is numeric, the return value is the same as
97019 ** the argument.  If the argument is NULL, the return value is the string
97020 ** "NULL".  Otherwise, the argument is enclosed in single quotes with
97021 ** single-quote escapes.
97022 */
97023 static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
97024   assert( argc==1 );
97025   UNUSED_PARAMETER(argc);
97026   switch( sqlite3_value_type(argv[0]) ){
97027     case SQLITE_FLOAT: {
97028       double r1, r2;
97029       char zBuf[50];
97030       r1 = sqlite3_value_double(argv[0]);
97031       sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
97032       sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
97033       if( r1!=r2 ){
97034         sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
97035       }
97036       sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
97037       break;
97038     }
97039     case SQLITE_INTEGER: {
97040       sqlite3_result_value(context, argv[0]);
97041       break;
97042     }
97043     case SQLITE_BLOB: {
97044       char *zText = 0;
97045       char const *zBlob = sqlite3_value_blob(argv[0]);
97046       int nBlob = sqlite3_value_bytes(argv[0]);
97047       assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
97048       zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4); 
97049       if( zText ){
97050         int i;
97051         for(i=0; i<nBlob; i++){
97052           zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
97053           zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
97054         }
97055         zText[(nBlob*2)+2] = '\'';
97056         zText[(nBlob*2)+3] = '\0';
97057         zText[0] = 'X';
97058         zText[1] = '\'';
97059         sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
97060         sqlite3_free(zText);
97061       }
97062       break;
97063     }
97064     case SQLITE_TEXT: {
97065       int i,j;
97066       u64 n;
97067       const unsigned char *zArg = sqlite3_value_text(argv[0]);
97068       char *z;
97069
97070       if( zArg==0 ) return;
97071       for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
97072       z = contextMalloc(context, ((i64)i)+((i64)n)+3);
97073       if( z ){
97074         z[0] = '\'';
97075         for(i=0, j=1; zArg[i]; i++){
97076           z[j++] = zArg[i];
97077           if( zArg[i]=='\'' ){
97078             z[j++] = '\'';
97079           }
97080         }
97081         z[j++] = '\'';
97082         z[j] = 0;
97083         sqlite3_result_text(context, z, j, sqlite3_free);
97084       }
97085       break;
97086     }
97087     default: {
97088       assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
97089       sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
97090       break;
97091     }
97092   }
97093 }
97094
97095 /*
97096 ** The unicode() function.  Return the integer unicode code-point value
97097 ** for the first character of the input string. 
97098 */
97099 static void unicodeFunc(
97100   sqlite3_context *context,
97101   int argc,
97102   sqlite3_value **argv
97103 ){
97104   const unsigned char *z = sqlite3_value_text(argv[0]);
97105   (void)argc;
97106   if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
97107 }
97108
97109 /*
97110 ** The char() function takes zero or more arguments, each of which is
97111 ** an integer.  It constructs a string where each character of the string
97112 ** is the unicode character for the corresponding integer argument.
97113 */
97114 static void charFunc(
97115   sqlite3_context *context,
97116   int argc,
97117   sqlite3_value **argv
97118 ){
97119   unsigned char *z, *zOut;
97120   int i;
97121   zOut = z = sqlite3_malloc( argc*4+1 );
97122   if( z==0 ){
97123     sqlite3_result_error_nomem(context);
97124     return;
97125   }
97126   for(i=0; i<argc; i++){
97127     sqlite3_int64 x;
97128     unsigned c;
97129     x = sqlite3_value_int64(argv[i]);
97130     if( x<0 || x>0x10ffff ) x = 0xfffd;
97131     c = (unsigned)(x & 0x1fffff);
97132     if( c<0x00080 ){
97133       *zOut++ = (u8)(c&0xFF);
97134     }else if( c<0x00800 ){
97135       *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
97136       *zOut++ = 0x80 + (u8)(c & 0x3F);
97137     }else if( c<0x10000 ){
97138       *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
97139       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
97140       *zOut++ = 0x80 + (u8)(c & 0x3F);
97141     }else{
97142       *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
97143       *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
97144       *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
97145       *zOut++ = 0x80 + (u8)(c & 0x3F);
97146     }                                                    \
97147   }
97148   sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
97149 }
97150
97151 /*
97152 ** The hex() function.  Interpret the argument as a blob.  Return
97153 ** a hexadecimal rendering as text.
97154 */
97155 static void hexFunc(
97156   sqlite3_context *context,
97157   int argc,
97158   sqlite3_value **argv
97159 ){
97160   int i, n;
97161   const unsigned char *pBlob;
97162   char *zHex, *z;
97163   assert( argc==1 );
97164   UNUSED_PARAMETER(argc);
97165   pBlob = sqlite3_value_blob(argv[0]);
97166   n = sqlite3_value_bytes(argv[0]);
97167   assert( pBlob==sqlite3_value_blob(argv[0]) );  /* No encoding change */
97168   z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
97169   if( zHex ){
97170     for(i=0; i<n; i++, pBlob++){
97171       unsigned char c = *pBlob;
97172       *(z++) = hexdigits[(c>>4)&0xf];
97173       *(z++) = hexdigits[c&0xf];
97174     }
97175     *z = 0;
97176     sqlite3_result_text(context, zHex, n*2, sqlite3_free);
97177   }
97178 }
97179
97180 /*
97181 ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
97182 */
97183 static void zeroblobFunc(
97184   sqlite3_context *context,
97185   int argc,
97186   sqlite3_value **argv
97187 ){
97188   i64 n;
97189   sqlite3 *db = sqlite3_context_db_handle(context);
97190   assert( argc==1 );
97191   UNUSED_PARAMETER(argc);
97192   n = sqlite3_value_int64(argv[0]);
97193   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
97194   testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
97195   if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
97196     sqlite3_result_error_toobig(context);
97197   }else{
97198     sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
97199   }
97200 }
97201
97202 /*
97203 ** The replace() function.  Three arguments are all strings: call
97204 ** them A, B, and C. The result is also a string which is derived
97205 ** from A by replacing every occurrence of B with C.  The match
97206 ** must be exact.  Collating sequences are not used.
97207 */
97208 static void replaceFunc(
97209   sqlite3_context *context,
97210   int argc,
97211   sqlite3_value **argv
97212 ){
97213   const unsigned char *zStr;        /* The input string A */
97214   const unsigned char *zPattern;    /* The pattern string B */
97215   const unsigned char *zRep;        /* The replacement string C */
97216   unsigned char *zOut;              /* The output */
97217   int nStr;                /* Size of zStr */
97218   int nPattern;            /* Size of zPattern */
97219   int nRep;                /* Size of zRep */
97220   i64 nOut;                /* Maximum size of zOut */
97221   int loopLimit;           /* Last zStr[] that might match zPattern[] */
97222   int i, j;                /* Loop counters */
97223
97224   assert( argc==3 );
97225   UNUSED_PARAMETER(argc);
97226   zStr = sqlite3_value_text(argv[0]);
97227   if( zStr==0 ) return;
97228   nStr = sqlite3_value_bytes(argv[0]);
97229   assert( zStr==sqlite3_value_text(argv[0]) );  /* No encoding change */
97230   zPattern = sqlite3_value_text(argv[1]);
97231   if( zPattern==0 ){
97232     assert( sqlite3_value_type(argv[1])==SQLITE_NULL
97233             || sqlite3_context_db_handle(context)->mallocFailed );
97234     return;
97235   }
97236   if( zPattern[0]==0 ){
97237     assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
97238     sqlite3_result_value(context, argv[0]);
97239     return;
97240   }
97241   nPattern = sqlite3_value_bytes(argv[1]);
97242   assert( zPattern==sqlite3_value_text(argv[1]) );  /* No encoding change */
97243   zRep = sqlite3_value_text(argv[2]);
97244   if( zRep==0 ) return;
97245   nRep = sqlite3_value_bytes(argv[2]);
97246   assert( zRep==sqlite3_value_text(argv[2]) );
97247   nOut = nStr + 1;
97248   assert( nOut<SQLITE_MAX_LENGTH );
97249   zOut = contextMalloc(context, (i64)nOut);
97250   if( zOut==0 ){
97251     return;
97252   }
97253   loopLimit = nStr - nPattern;  
97254   for(i=j=0; i<=loopLimit; i++){
97255     if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
97256       zOut[j++] = zStr[i];
97257     }else{
97258       u8 *zOld;
97259       sqlite3 *db = sqlite3_context_db_handle(context);
97260       nOut += nRep - nPattern;
97261       testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
97262       testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
97263       if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
97264         sqlite3_result_error_toobig(context);
97265         sqlite3_free(zOut);
97266         return;
97267       }
97268       zOld = zOut;
97269       zOut = sqlite3_realloc(zOut, (int)nOut);
97270       if( zOut==0 ){
97271         sqlite3_result_error_nomem(context);
97272         sqlite3_free(zOld);
97273         return;
97274       }
97275       memcpy(&zOut[j], zRep, nRep);
97276       j += nRep;
97277       i += nPattern-1;
97278     }
97279   }
97280   assert( j+nStr-i+1==nOut );
97281   memcpy(&zOut[j], &zStr[i], nStr-i);
97282   j += nStr - i;
97283   assert( j<=nOut );
97284   zOut[j] = 0;
97285   sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
97286 }
97287
97288 /*
97289 ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
97290 ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
97291 */
97292 static void trimFunc(
97293   sqlite3_context *context,
97294   int argc,
97295   sqlite3_value **argv
97296 ){
97297   const unsigned char *zIn;         /* Input string */
97298   const unsigned char *zCharSet;    /* Set of characters to trim */
97299   int nIn;                          /* Number of bytes in input */
97300   int flags;                        /* 1: trimleft  2: trimright  3: trim */
97301   int i;                            /* Loop counter */
97302   unsigned char *aLen = 0;          /* Length of each character in zCharSet */
97303   unsigned char **azChar = 0;       /* Individual characters in zCharSet */
97304   int nChar;                        /* Number of characters in zCharSet */
97305
97306   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
97307     return;
97308   }
97309   zIn = sqlite3_value_text(argv[0]);
97310   if( zIn==0 ) return;
97311   nIn = sqlite3_value_bytes(argv[0]);
97312   assert( zIn==sqlite3_value_text(argv[0]) );
97313   if( argc==1 ){
97314     static const unsigned char lenOne[] = { 1 };
97315     static unsigned char * const azOne[] = { (u8*)" " };
97316     nChar = 1;
97317     aLen = (u8*)lenOne;
97318     azChar = (unsigned char **)azOne;
97319     zCharSet = 0;
97320   }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
97321     return;
97322   }else{
97323     const unsigned char *z;
97324     for(z=zCharSet, nChar=0; *z; nChar++){
97325       SQLITE_SKIP_UTF8(z);
97326     }
97327     if( nChar>0 ){
97328       azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
97329       if( azChar==0 ){
97330         return;
97331       }
97332       aLen = (unsigned char*)&azChar[nChar];
97333       for(z=zCharSet, nChar=0; *z; nChar++){
97334         azChar[nChar] = (unsigned char *)z;
97335         SQLITE_SKIP_UTF8(z);
97336         aLen[nChar] = (u8)(z - azChar[nChar]);
97337       }
97338     }
97339   }
97340   if( nChar>0 ){
97341     flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
97342     if( flags & 1 ){
97343       while( nIn>0 ){
97344         int len = 0;
97345         for(i=0; i<nChar; i++){
97346           len = aLen[i];
97347           if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
97348         }
97349         if( i>=nChar ) break;
97350         zIn += len;
97351         nIn -= len;
97352       }
97353     }
97354     if( flags & 2 ){
97355       while( nIn>0 ){
97356         int len = 0;
97357         for(i=0; i<nChar; i++){
97358           len = aLen[i];
97359           if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
97360         }
97361         if( i>=nChar ) break;
97362         nIn -= len;
97363       }
97364     }
97365     if( zCharSet ){
97366       sqlite3_free(azChar);
97367     }
97368   }
97369   sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
97370 }
97371
97372
97373 /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
97374 ** is only available if the SQLITE_SOUNDEX compile-time option is used
97375 ** when SQLite is built.
97376 */
97377 #ifdef SQLITE_SOUNDEX
97378 /*
97379 ** Compute the soundex encoding of a word.
97380 **
97381 ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
97382 ** soundex encoding of the string X. 
97383 */
97384 static void soundexFunc(
97385   sqlite3_context *context,
97386   int argc,
97387   sqlite3_value **argv
97388 ){
97389   char zResult[8];
97390   const u8 *zIn;
97391   int i, j;
97392   static const unsigned char iCode[] = {
97393     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
97394     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
97395     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
97396     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
97397     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
97398     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
97399     0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
97400     1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
97401   };
97402   assert( argc==1 );
97403   zIn = (u8*)sqlite3_value_text(argv[0]);
97404   if( zIn==0 ) zIn = (u8*)"";
97405   for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
97406   if( zIn[i] ){
97407     u8 prevcode = iCode[zIn[i]&0x7f];
97408     zResult[0] = sqlite3Toupper(zIn[i]);
97409     for(j=1; j<4 && zIn[i]; i++){
97410       int code = iCode[zIn[i]&0x7f];
97411       if( code>0 ){
97412         if( code!=prevcode ){
97413           prevcode = code;
97414           zResult[j++] = code + '0';
97415         }
97416       }else{
97417         prevcode = 0;
97418       }
97419     }
97420     while( j<4 ){
97421       zResult[j++] = '0';
97422     }
97423     zResult[j] = 0;
97424     sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
97425   }else{
97426     /* IMP: R-64894-50321 The string "?000" is returned if the argument
97427     ** is NULL or contains no ASCII alphabetic characters. */
97428     sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
97429   }
97430 }
97431 #endif /* SQLITE_SOUNDEX */
97432
97433 #ifndef SQLITE_OMIT_LOAD_EXTENSION
97434 /*
97435 ** A function that loads a shared-library extension then returns NULL.
97436 */
97437 static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
97438   const char *zFile = (const char *)sqlite3_value_text(argv[0]);
97439   const char *zProc;
97440   sqlite3 *db = sqlite3_context_db_handle(context);
97441   char *zErrMsg = 0;
97442
97443   if( argc==2 ){
97444     zProc = (const char *)sqlite3_value_text(argv[1]);
97445   }else{
97446     zProc = 0;
97447   }
97448   if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
97449     sqlite3_result_error(context, zErrMsg, -1);
97450     sqlite3_free(zErrMsg);
97451   }
97452 }
97453 #endif
97454
97455
97456 /*
97457 ** An instance of the following structure holds the context of a
97458 ** sum() or avg() aggregate computation.
97459 */
97460 typedef struct SumCtx SumCtx;
97461 struct SumCtx {
97462   double rSum;      /* Floating point sum */
97463   i64 iSum;         /* Integer sum */   
97464   i64 cnt;          /* Number of elements summed */
97465   u8 overflow;      /* True if integer overflow seen */
97466   u8 approx;        /* True if non-integer value was input to the sum */
97467 };
97468
97469 /*
97470 ** Routines used to compute the sum, average, and total.
97471 **
97472 ** The SUM() function follows the (broken) SQL standard which means
97473 ** that it returns NULL if it sums over no inputs.  TOTAL returns
97474 ** 0.0 in that case.  In addition, TOTAL always returns a float where
97475 ** SUM might return an integer if it never encounters a floating point
97476 ** value.  TOTAL never fails, but SUM might through an exception if
97477 ** it overflows an integer.
97478 */
97479 static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
97480   SumCtx *p;
97481   int type;
97482   assert( argc==1 );
97483   UNUSED_PARAMETER(argc);
97484   p = sqlite3_aggregate_context(context, sizeof(*p));
97485   type = sqlite3_value_numeric_type(argv[0]);
97486   if( p && type!=SQLITE_NULL ){
97487     p->cnt++;
97488     if( type==SQLITE_INTEGER ){
97489       i64 v = sqlite3_value_int64(argv[0]);
97490       p->rSum += v;
97491       if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
97492         p->overflow = 1;
97493       }
97494     }else{
97495       p->rSum += sqlite3_value_double(argv[0]);
97496       p->approx = 1;
97497     }
97498   }
97499 }
97500 static void sumFinalize(sqlite3_context *context){
97501   SumCtx *p;
97502   p = sqlite3_aggregate_context(context, 0);
97503   if( p && p->cnt>0 ){
97504     if( p->overflow ){
97505       sqlite3_result_error(context,"integer overflow",-1);
97506     }else if( p->approx ){
97507       sqlite3_result_double(context, p->rSum);
97508     }else{
97509       sqlite3_result_int64(context, p->iSum);
97510     }
97511   }
97512 }
97513 static void avgFinalize(sqlite3_context *context){
97514   SumCtx *p;
97515   p = sqlite3_aggregate_context(context, 0);
97516   if( p && p->cnt>0 ){
97517     sqlite3_result_double(context, p->rSum/(double)p->cnt);
97518   }
97519 }
97520 static void totalFinalize(sqlite3_context *context){
97521   SumCtx *p;
97522   p = sqlite3_aggregate_context(context, 0);
97523   /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
97524   sqlite3_result_double(context, p ? p->rSum : (double)0);
97525 }
97526
97527 /*
97528 ** The following structure keeps track of state information for the
97529 ** count() aggregate function.
97530 */
97531 typedef struct CountCtx CountCtx;
97532 struct CountCtx {
97533   i64 n;
97534 };
97535
97536 /*
97537 ** Routines to implement the count() aggregate function.
97538 */
97539 static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
97540   CountCtx *p;
97541   p = sqlite3_aggregate_context(context, sizeof(*p));
97542   if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
97543     p->n++;
97544   }
97545
97546 #ifndef SQLITE_OMIT_DEPRECATED
97547   /* The sqlite3_aggregate_count() function is deprecated.  But just to make
97548   ** sure it still operates correctly, verify that its count agrees with our 
97549   ** internal count when using count(*) and when the total count can be
97550   ** expressed as a 32-bit integer. */
97551   assert( argc==1 || p==0 || p->n>0x7fffffff
97552           || p->n==sqlite3_aggregate_count(context) );
97553 #endif
97554 }   
97555 static void countFinalize(sqlite3_context *context){
97556   CountCtx *p;
97557   p = sqlite3_aggregate_context(context, 0);
97558   sqlite3_result_int64(context, p ? p->n : 0);
97559 }
97560
97561 /*
97562 ** Routines to implement min() and max() aggregate functions.
97563 */
97564 static void minmaxStep(
97565   sqlite3_context *context, 
97566   int NotUsed, 
97567   sqlite3_value **argv
97568 ){
97569   Mem *pArg  = (Mem *)argv[0];
97570   Mem *pBest;
97571   UNUSED_PARAMETER(NotUsed);
97572
97573   pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
97574   if( !pBest ) return;
97575
97576   if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
97577     if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
97578   }else if( pBest->flags ){
97579     int max;
97580     int cmp;
97581     CollSeq *pColl = sqlite3GetFuncCollSeq(context);
97582     /* This step function is used for both the min() and max() aggregates,
97583     ** the only difference between the two being that the sense of the
97584     ** comparison is inverted. For the max() aggregate, the
97585     ** sqlite3_user_data() function returns (void *)-1. For min() it
97586     ** returns (void *)db, where db is the sqlite3* database pointer.
97587     ** Therefore the next statement sets variable 'max' to 1 for the max()
97588     ** aggregate, or 0 for min().
97589     */
97590     max = sqlite3_user_data(context)!=0;
97591     cmp = sqlite3MemCompare(pBest, pArg, pColl);
97592     if( (max && cmp<0) || (!max && cmp>0) ){
97593       sqlite3VdbeMemCopy(pBest, pArg);
97594     }else{
97595       sqlite3SkipAccumulatorLoad(context);
97596     }
97597   }else{
97598     pBest->db = sqlite3_context_db_handle(context);
97599     sqlite3VdbeMemCopy(pBest, pArg);
97600   }
97601 }
97602 static void minMaxFinalize(sqlite3_context *context){
97603   sqlite3_value *pRes;
97604   pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
97605   if( pRes ){
97606     if( pRes->flags ){
97607       sqlite3_result_value(context, pRes);
97608     }
97609     sqlite3VdbeMemRelease(pRes);
97610   }
97611 }
97612
97613 /*
97614 ** group_concat(EXPR, ?SEPARATOR?)
97615 */
97616 static void groupConcatStep(
97617   sqlite3_context *context,
97618   int argc,
97619   sqlite3_value **argv
97620 ){
97621   const char *zVal;
97622   StrAccum *pAccum;
97623   const char *zSep;
97624   int nVal, nSep;
97625   assert( argc==1 || argc==2 );
97626   if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
97627   pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
97628
97629   if( pAccum ){
97630     sqlite3 *db = sqlite3_context_db_handle(context);
97631     int firstTerm = pAccum->useMalloc==0;
97632     pAccum->useMalloc = 2;
97633     pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
97634     if( !firstTerm ){
97635       if( argc==2 ){
97636         zSep = (char*)sqlite3_value_text(argv[1]);
97637         nSep = sqlite3_value_bytes(argv[1]);
97638       }else{
97639         zSep = ",";
97640         nSep = 1;
97641       }
97642       if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
97643     }
97644     zVal = (char*)sqlite3_value_text(argv[0]);
97645     nVal = sqlite3_value_bytes(argv[0]);
97646     if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
97647   }
97648 }
97649 static void groupConcatFinalize(sqlite3_context *context){
97650   StrAccum *pAccum;
97651   pAccum = sqlite3_aggregate_context(context, 0);
97652   if( pAccum ){
97653     if( pAccum->accError==STRACCUM_TOOBIG ){
97654       sqlite3_result_error_toobig(context);
97655     }else if( pAccum->accError==STRACCUM_NOMEM ){
97656       sqlite3_result_error_nomem(context);
97657     }else{    
97658       sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1, 
97659                           sqlite3_free);
97660     }
97661   }
97662 }
97663
97664 /*
97665 ** This routine does per-connection function registration.  Most
97666 ** of the built-in functions above are part of the global function set.
97667 ** This routine only deals with those that are not global.
97668 */
97669 SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
97670   int rc = sqlite3_overload_function(db, "MATCH", 2);
97671   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
97672   if( rc==SQLITE_NOMEM ){
97673     db->mallocFailed = 1;
97674   }
97675 }
97676
97677 /*
97678 ** Set the LIKEOPT flag on the 2-argument function with the given name.
97679 */
97680 static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
97681   FuncDef *pDef;
97682   pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
97683                              2, SQLITE_UTF8, 0);
97684   if( ALWAYS(pDef) ){
97685     pDef->funcFlags |= flagVal;
97686   }
97687 }
97688
97689 /*
97690 ** Register the built-in LIKE and GLOB functions.  The caseSensitive
97691 ** parameter determines whether or not the LIKE operator is case
97692 ** sensitive.  GLOB is always case sensitive.
97693 */
97694 SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
97695   struct compareInfo *pInfo;
97696   if( caseSensitive ){
97697     pInfo = (struct compareInfo*)&likeInfoAlt;
97698   }else{
97699     pInfo = (struct compareInfo*)&likeInfoNorm;
97700   }
97701   sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
97702   sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
97703   sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8, 
97704       (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
97705   setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
97706   setLikeOptFlag(db, "like", 
97707       caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
97708 }
97709
97710 /*
97711 ** pExpr points to an expression which implements a function.  If
97712 ** it is appropriate to apply the LIKE optimization to that function
97713 ** then set aWc[0] through aWc[2] to the wildcard characters and
97714 ** return TRUE.  If the function is not a LIKE-style function then
97715 ** return FALSE.
97716 **
97717 ** *pIsNocase is set to true if uppercase and lowercase are equivalent for
97718 ** the function (default for LIKE).  If the function makes the distinction
97719 ** between uppercase and lowercase (as does GLOB) then *pIsNocase is set to
97720 ** false.
97721 */
97722 SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
97723   FuncDef *pDef;
97724   if( pExpr->op!=TK_FUNCTION 
97725    || !pExpr->x.pList 
97726    || pExpr->x.pList->nExpr!=2
97727   ){
97728     return 0;
97729   }
97730   assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
97731   pDef = sqlite3FindFunction(db, pExpr->u.zToken, 
97732                              sqlite3Strlen30(pExpr->u.zToken),
97733                              2, SQLITE_UTF8, 0);
97734   if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
97735     return 0;
97736   }
97737
97738   /* The memcpy() statement assumes that the wildcard characters are
97739   ** the first three statements in the compareInfo structure.  The
97740   ** asserts() that follow verify that assumption
97741   */
97742   memcpy(aWc, pDef->pUserData, 3);
97743   assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
97744   assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
97745   assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
97746   *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
97747   return 1;
97748 }
97749
97750 /*
97751 ** All of the FuncDef structures in the aBuiltinFunc[] array above
97752 ** to the global function hash table.  This occurs at start-time (as
97753 ** a consequence of calling sqlite3_initialize()).
97754 **
97755 ** After this routine runs
97756 */
97757 SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
97758   /*
97759   ** The following array holds FuncDef structures for all of the functions
97760   ** defined in this file.
97761   **
97762   ** The array cannot be constant since changes are made to the
97763   ** FuncDef.pHash elements at start-time.  The elements of this array
97764   ** are read-only after initialization is complete.
97765   */
97766   static SQLITE_WSD FuncDef aBuiltinFunc[] = {
97767     FUNCTION(ltrim,              1, 1, 0, trimFunc         ),
97768     FUNCTION(ltrim,              2, 1, 0, trimFunc         ),
97769     FUNCTION(rtrim,              1, 2, 0, trimFunc         ),
97770     FUNCTION(rtrim,              2, 2, 0, trimFunc         ),
97771     FUNCTION(trim,               1, 3, 0, trimFunc         ),
97772     FUNCTION(trim,               2, 3, 0, trimFunc         ),
97773     FUNCTION(min,               -1, 0, 1, minmaxFunc       ),
97774     FUNCTION(min,                0, 0, 1, 0                ),
97775     AGGREGATE2(min,              1, 0, 1, minmaxStep,      minMaxFinalize,
97776                                           SQLITE_FUNC_MINMAX ),
97777     FUNCTION(max,               -1, 1, 1, minmaxFunc       ),
97778     FUNCTION(max,                0, 1, 1, 0                ),
97779     AGGREGATE2(max,              1, 1, 1, minmaxStep,      minMaxFinalize,
97780                                           SQLITE_FUNC_MINMAX ),
97781     FUNCTION2(typeof,            1, 0, 0, typeofFunc,  SQLITE_FUNC_TYPEOF),
97782     FUNCTION2(length,            1, 0, 0, lengthFunc,  SQLITE_FUNC_LENGTH),
97783     FUNCTION(instr,              2, 0, 0, instrFunc        ),
97784     FUNCTION(substr,             2, 0, 0, substrFunc       ),
97785     FUNCTION(substr,             3, 0, 0, substrFunc       ),
97786     FUNCTION(printf,            -1, 0, 0, printfFunc       ),
97787     FUNCTION(unicode,            1, 0, 0, unicodeFunc      ),
97788     FUNCTION(char,              -1, 0, 0, charFunc         ),
97789     FUNCTION(abs,                1, 0, 0, absFunc          ),
97790 #ifndef SQLITE_OMIT_FLOATING_POINT
97791     FUNCTION(round,              1, 0, 0, roundFunc        ),
97792     FUNCTION(round,              2, 0, 0, roundFunc        ),
97793 #endif
97794     FUNCTION(upper,              1, 0, 0, upperFunc        ),
97795     FUNCTION(lower,              1, 0, 0, lowerFunc        ),
97796     FUNCTION(coalesce,           1, 0, 0, 0                ),
97797     FUNCTION(coalesce,           0, 0, 0, 0                ),
97798     FUNCTION2(coalesce,         -1, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
97799     FUNCTION(hex,                1, 0, 0, hexFunc          ),
97800     FUNCTION2(ifnull,            2, 0, 0, noopFunc,  SQLITE_FUNC_COALESCE),
97801     FUNCTION2(unlikely,          1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
97802     FUNCTION2(likelihood,        2, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
97803     FUNCTION2(likely,            1, 0, 0, noopFunc,  SQLITE_FUNC_UNLIKELY),
97804     VFUNCTION(random,            0, 0, 0, randomFunc       ),
97805     VFUNCTION(randomblob,        1, 0, 0, randomBlob       ),
97806     FUNCTION(nullif,             2, 0, 1, nullifFunc       ),
97807     FUNCTION(sqlite_version,     0, 0, 0, versionFunc      ),
97808     FUNCTION(sqlite_source_id,   0, 0, 0, sourceidFunc     ),
97809     FUNCTION(sqlite_log,         2, 0, 0, errlogFunc       ),
97810 #if SQLITE_USER_AUTHENTICATION
97811     FUNCTION(sqlite_crypt,       2, 0, 0, sqlite3CryptFunc ),
97812 #endif
97813 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
97814     FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc  ),
97815     FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc  ),
97816 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
97817     FUNCTION(quote,              1, 0, 0, quoteFunc        ),
97818     VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
97819     VFUNCTION(changes,           0, 0, 0, changes          ),
97820     VFUNCTION(total_changes,     0, 0, 0, total_changes    ),
97821     FUNCTION(replace,            3, 0, 0, replaceFunc      ),
97822     FUNCTION(zeroblob,           1, 0, 0, zeroblobFunc     ),
97823   #ifdef SQLITE_SOUNDEX
97824     FUNCTION(soundex,            1, 0, 0, soundexFunc      ),
97825   #endif
97826   #ifndef SQLITE_OMIT_LOAD_EXTENSION
97827     FUNCTION(load_extension,     1, 0, 0, loadExt          ),
97828     FUNCTION(load_extension,     2, 0, 0, loadExt          ),
97829   #endif
97830     AGGREGATE(sum,               1, 0, 0, sumStep,         sumFinalize    ),
97831     AGGREGATE(total,             1, 0, 0, sumStep,         totalFinalize    ),
97832     AGGREGATE(avg,               1, 0, 0, sumStep,         avgFinalize    ),
97833     AGGREGATE2(count,            0, 0, 0, countStep,       countFinalize,
97834                SQLITE_FUNC_COUNT  ),
97835     AGGREGATE(count,             1, 0, 0, countStep,       countFinalize  ),
97836     AGGREGATE(group_concat,      1, 0, 0, groupConcatStep, groupConcatFinalize),
97837     AGGREGATE(group_concat,      2, 0, 0, groupConcatStep, groupConcatFinalize),
97838   
97839     LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
97840   #ifdef SQLITE_CASE_SENSITIVE_LIKE
97841     LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
97842     LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
97843   #else
97844     LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
97845     LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
97846   #endif
97847   };
97848
97849   int i;
97850   FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
97851   FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
97852
97853   for(i=0; i<ArraySize(aBuiltinFunc); i++){
97854     sqlite3FuncDefInsert(pHash, &aFunc[i]);
97855   }
97856   sqlite3RegisterDateTimeFunctions();
97857 #ifndef SQLITE_OMIT_ALTERTABLE
97858   sqlite3AlterFunctions();
97859 #endif
97860 #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
97861   sqlite3AnalyzeFunctions();
97862 #endif
97863 }
97864
97865 /************** End of func.c ************************************************/
97866 /************** Begin file fkey.c ********************************************/
97867 /*
97868 **
97869 ** The author disclaims copyright to this source code.  In place of
97870 ** a legal notice, here is a blessing:
97871 **
97872 **    May you do good and not evil.
97873 **    May you find forgiveness for yourself and forgive others.
97874 **    May you share freely, never taking more than you give.
97875 **
97876 *************************************************************************
97877 ** This file contains code used by the compiler to add foreign key
97878 ** support to compiled SQL statements.
97879 */
97880
97881 #ifndef SQLITE_OMIT_FOREIGN_KEY
97882 #ifndef SQLITE_OMIT_TRIGGER
97883
97884 /*
97885 ** Deferred and Immediate FKs
97886 ** --------------------------
97887 **
97888 ** Foreign keys in SQLite come in two flavours: deferred and immediate.
97889 ** If an immediate foreign key constraint is violated,
97890 ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
97891 ** statement transaction rolled back. If a 
97892 ** deferred foreign key constraint is violated, no action is taken 
97893 ** immediately. However if the application attempts to commit the 
97894 ** transaction before fixing the constraint violation, the attempt fails.
97895 **
97896 ** Deferred constraints are implemented using a simple counter associated
97897 ** with the database handle. The counter is set to zero each time a 
97898 ** database transaction is opened. Each time a statement is executed 
97899 ** that causes a foreign key violation, the counter is incremented. Each
97900 ** time a statement is executed that removes an existing violation from
97901 ** the database, the counter is decremented. When the transaction is
97902 ** committed, the commit fails if the current value of the counter is
97903 ** greater than zero. This scheme has two big drawbacks:
97904 **
97905 **   * When a commit fails due to a deferred foreign key constraint, 
97906 **     there is no way to tell which foreign constraint is not satisfied,
97907 **     or which row it is not satisfied for.
97908 **
97909 **   * If the database contains foreign key violations when the 
97910 **     transaction is opened, this may cause the mechanism to malfunction.
97911 **
97912 ** Despite these problems, this approach is adopted as it seems simpler
97913 ** than the alternatives.
97914 **
97915 ** INSERT operations:
97916 **
97917 **   I.1) For each FK for which the table is the child table, search
97918 **        the parent table for a match. If none is found increment the
97919 **        constraint counter.
97920 **
97921 **   I.2) For each FK for which the table is the parent table, 
97922 **        search the child table for rows that correspond to the new
97923 **        row in the parent table. Decrement the counter for each row
97924 **        found (as the constraint is now satisfied).
97925 **
97926 ** DELETE operations:
97927 **
97928 **   D.1) For each FK for which the table is the child table, 
97929 **        search the parent table for a row that corresponds to the 
97930 **        deleted row in the child table. If such a row is not found, 
97931 **        decrement the counter.
97932 **
97933 **   D.2) For each FK for which the table is the parent table, search 
97934 **        the child table for rows that correspond to the deleted row 
97935 **        in the parent table. For each found increment the counter.
97936 **
97937 ** UPDATE operations:
97938 **
97939 **   An UPDATE command requires that all 4 steps above are taken, but only
97940 **   for FK constraints for which the affected columns are actually 
97941 **   modified (values must be compared at runtime).
97942 **
97943 ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
97944 ** This simplifies the implementation a bit.
97945 **
97946 ** For the purposes of immediate FK constraints, the OR REPLACE conflict
97947 ** resolution is considered to delete rows before the new row is inserted.
97948 ** If a delete caused by OR REPLACE violates an FK constraint, an exception
97949 ** is thrown, even if the FK constraint would be satisfied after the new 
97950 ** row is inserted.
97951 **
97952 ** Immediate constraints are usually handled similarly. The only difference 
97953 ** is that the counter used is stored as part of each individual statement
97954 ** object (struct Vdbe). If, after the statement has run, its immediate
97955 ** constraint counter is greater than zero,
97956 ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
97957 ** and the statement transaction is rolled back. An exception is an INSERT
97958 ** statement that inserts a single row only (no triggers). In this case,
97959 ** instead of using a counter, an exception is thrown immediately if the
97960 ** INSERT violates a foreign key constraint. This is necessary as such
97961 ** an INSERT does not open a statement transaction.
97962 **
97963 ** TODO: How should dropping a table be handled? How should renaming a 
97964 ** table be handled?
97965 **
97966 **
97967 ** Query API Notes
97968 ** ---------------
97969 **
97970 ** Before coding an UPDATE or DELETE row operation, the code-generator
97971 ** for those two operations needs to know whether or not the operation
97972 ** requires any FK processing and, if so, which columns of the original
97973 ** row are required by the FK processing VDBE code (i.e. if FKs were
97974 ** implemented using triggers, which of the old.* columns would be 
97975 ** accessed). No information is required by the code-generator before
97976 ** coding an INSERT operation. The functions used by the UPDATE/DELETE
97977 ** generation code to query for this information are:
97978 **
97979 **   sqlite3FkRequired() - Test to see if FK processing is required.
97980 **   sqlite3FkOldmask()  - Query for the set of required old.* columns.
97981 **
97982 **
97983 ** Externally accessible module functions
97984 ** --------------------------------------
97985 **
97986 **   sqlite3FkCheck()    - Check for foreign key violations.
97987 **   sqlite3FkActions()  - Code triggers for ON UPDATE/ON DELETE actions.
97988 **   sqlite3FkDelete()   - Delete an FKey structure.
97989 */
97990
97991 /*
97992 ** VDBE Calling Convention
97993 ** -----------------------
97994 **
97995 ** Example:
97996 **
97997 **   For the following INSERT statement:
97998 **
97999 **     CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
98000 **     INSERT INTO t1 VALUES(1, 2, 3.1);
98001 **
98002 **   Register (x):        2    (type integer)
98003 **   Register (x+1):      1    (type integer)
98004 **   Register (x+2):      NULL (type NULL)
98005 **   Register (x+3):      3.1  (type real)
98006 */
98007
98008 /*
98009 ** A foreign key constraint requires that the key columns in the parent
98010 ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
98011 ** Given that pParent is the parent table for foreign key constraint pFKey, 
98012 ** search the schema for a unique index on the parent key columns. 
98013 **
98014 ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY 
98015 ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx 
98016 ** is set to point to the unique index. 
98017 ** 
98018 ** If the parent key consists of a single column (the foreign key constraint
98019 ** is not a composite foreign key), output variable *paiCol is set to NULL.
98020 ** Otherwise, it is set to point to an allocated array of size N, where
98021 ** N is the number of columns in the parent key. The first element of the
98022 ** array is the index of the child table column that is mapped by the FK
98023 ** constraint to the parent table column stored in the left-most column
98024 ** of index *ppIdx. The second element of the array is the index of the
98025 ** child table column that corresponds to the second left-most column of
98026 ** *ppIdx, and so on.
98027 **
98028 ** If the required index cannot be found, either because:
98029 **
98030 **   1) The named parent key columns do not exist, or
98031 **
98032 **   2) The named parent key columns do exist, but are not subject to a
98033 **      UNIQUE or PRIMARY KEY constraint, or
98034 **
98035 **   3) No parent key columns were provided explicitly as part of the
98036 **      foreign key definition, and the parent table does not have a
98037 **      PRIMARY KEY, or
98038 **
98039 **   4) No parent key columns were provided explicitly as part of the
98040 **      foreign key definition, and the PRIMARY KEY of the parent table 
98041 **      consists of a different number of columns to the child key in 
98042 **      the child table.
98043 **
98044 ** then non-zero is returned, and a "foreign key mismatch" error loaded
98045 ** into pParse. If an OOM error occurs, non-zero is returned and the
98046 ** pParse->db->mallocFailed flag is set.
98047 */
98048 SQLITE_PRIVATE int sqlite3FkLocateIndex(
98049   Parse *pParse,                  /* Parse context to store any error in */
98050   Table *pParent,                 /* Parent table of FK constraint pFKey */
98051   FKey *pFKey,                    /* Foreign key to find index for */
98052   Index **ppIdx,                  /* OUT: Unique index on parent table */
98053   int **paiCol                    /* OUT: Map of index columns in pFKey */
98054 ){
98055   Index *pIdx = 0;                    /* Value to return via *ppIdx */
98056   int *aiCol = 0;                     /* Value to return via *paiCol */
98057   int nCol = pFKey->nCol;             /* Number of columns in parent key */
98058   char *zKey = pFKey->aCol[0].zCol;   /* Name of left-most parent key column */
98059
98060   /* The caller is responsible for zeroing output parameters. */
98061   assert( ppIdx && *ppIdx==0 );
98062   assert( !paiCol || *paiCol==0 );
98063   assert( pParse );
98064
98065   /* If this is a non-composite (single column) foreign key, check if it 
98066   ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx 
98067   ** and *paiCol set to zero and return early. 
98068   **
98069   ** Otherwise, for a composite foreign key (more than one column), allocate
98070   ** space for the aiCol array (returned via output parameter *paiCol).
98071   ** Non-composite foreign keys do not require the aiCol array.
98072   */
98073   if( nCol==1 ){
98074     /* The FK maps to the IPK if any of the following are true:
98075     **
98076     **   1) There is an INTEGER PRIMARY KEY column and the FK is implicitly 
98077     **      mapped to the primary key of table pParent, or
98078     **   2) The FK is explicitly mapped to a column declared as INTEGER
98079     **      PRIMARY KEY.
98080     */
98081     if( pParent->iPKey>=0 ){
98082       if( !zKey ) return 0;
98083       if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
98084     }
98085   }else if( paiCol ){
98086     assert( nCol>1 );
98087     aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
98088     if( !aiCol ) return 1;
98089     *paiCol = aiCol;
98090   }
98091
98092   for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
98093     if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){ 
98094       /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
98095       ** of columns. If each indexed column corresponds to a foreign key
98096       ** column of pFKey, then this index is a winner.  */
98097
98098       if( zKey==0 ){
98099         /* If zKey is NULL, then this foreign key is implicitly mapped to 
98100         ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be 
98101         ** identified by the test.  */
98102         if( IsPrimaryKeyIndex(pIdx) ){
98103           if( aiCol ){
98104             int i;
98105             for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
98106           }
98107           break;
98108         }
98109       }else{
98110         /* If zKey is non-NULL, then this foreign key was declared to
98111         ** map to an explicit list of columns in table pParent. Check if this
98112         ** index matches those columns. Also, check that the index uses
98113         ** the default collation sequences for each column. */
98114         int i, j;
98115         for(i=0; i<nCol; i++){
98116           i16 iCol = pIdx->aiColumn[i];     /* Index of column in parent tbl */
98117           char *zDfltColl;                  /* Def. collation for column */
98118           char *zIdxCol;                    /* Name of indexed column */
98119
98120           /* If the index uses a collation sequence that is different from
98121           ** the default collation sequence for the column, this index is
98122           ** unusable. Bail out early in this case.  */
98123           zDfltColl = pParent->aCol[iCol].zColl;
98124           if( !zDfltColl ){
98125             zDfltColl = "BINARY";
98126           }
98127           if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
98128
98129           zIdxCol = pParent->aCol[iCol].zName;
98130           for(j=0; j<nCol; j++){
98131             if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
98132               if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
98133               break;
98134             }
98135           }
98136           if( j==nCol ) break;
98137         }
98138         if( i==nCol ) break;      /* pIdx is usable */
98139       }
98140     }
98141   }
98142
98143   if( !pIdx ){
98144     if( !pParse->disableTriggers ){
98145       sqlite3ErrorMsg(pParse,
98146            "foreign key mismatch - \"%w\" referencing \"%w\"",
98147            pFKey->pFrom->zName, pFKey->zTo);
98148     }
98149     sqlite3DbFree(pParse->db, aiCol);
98150     return 1;
98151   }
98152
98153   *ppIdx = pIdx;
98154   return 0;
98155 }
98156
98157 /*
98158 ** This function is called when a row is inserted into or deleted from the 
98159 ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed 
98160 ** on the child table of pFKey, this function is invoked twice for each row
98161 ** affected - once to "delete" the old row, and then again to "insert" the
98162 ** new row.
98163 **
98164 ** Each time it is called, this function generates VDBE code to locate the
98165 ** row in the parent table that corresponds to the row being inserted into 
98166 ** or deleted from the child table. If the parent row can be found, no 
98167 ** special action is taken. Otherwise, if the parent row can *not* be
98168 ** found in the parent table:
98169 **
98170 **   Operation | FK type   | Action taken
98171 **   --------------------------------------------------------------------------
98172 **   INSERT      immediate   Increment the "immediate constraint counter".
98173 **
98174 **   DELETE      immediate   Decrement the "immediate constraint counter".
98175 **
98176 **   INSERT      deferred    Increment the "deferred constraint counter".
98177 **
98178 **   DELETE      deferred    Decrement the "deferred constraint counter".
98179 **
98180 ** These operations are identified in the comment at the top of this file 
98181 ** (fkey.c) as "I.1" and "D.1".
98182 */
98183 static void fkLookupParent(
98184   Parse *pParse,        /* Parse context */
98185   int iDb,              /* Index of database housing pTab */
98186   Table *pTab,          /* Parent table of FK pFKey */
98187   Index *pIdx,          /* Unique index on parent key columns in pTab */
98188   FKey *pFKey,          /* Foreign key constraint */
98189   int *aiCol,           /* Map from parent key columns to child table columns */
98190   int regData,          /* Address of array containing child table row */
98191   int nIncr,            /* Increment constraint counter by this */
98192   int isIgnore          /* If true, pretend pTab contains all NULL values */
98193 ){
98194   int i;                                    /* Iterator variable */
98195   Vdbe *v = sqlite3GetVdbe(pParse);         /* Vdbe to add code to */
98196   int iCur = pParse->nTab - 1;              /* Cursor number to use */
98197   int iOk = sqlite3VdbeMakeLabel(v);        /* jump here if parent key found */
98198
98199   /* If nIncr is less than zero, then check at runtime if there are any
98200   ** outstanding constraints to resolve. If there are not, there is no need
98201   ** to check if deleting this row resolves any outstanding violations.
98202   **
98203   ** Check if any of the key columns in the child table row are NULL. If 
98204   ** any are, then the constraint is considered satisfied. No need to 
98205   ** search for a matching row in the parent table.  */
98206   if( nIncr<0 ){
98207     sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
98208     VdbeCoverage(v);
98209   }
98210   for(i=0; i<pFKey->nCol; i++){
98211     int iReg = aiCol[i] + regData + 1;
98212     sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
98213   }
98214
98215   if( isIgnore==0 ){
98216     if( pIdx==0 ){
98217       /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
98218       ** column of the parent table (table pTab).  */
98219       int iMustBeInt;               /* Address of MustBeInt instruction */
98220       int regTemp = sqlite3GetTempReg(pParse);
98221   
98222       /* Invoke MustBeInt to coerce the child key value to an integer (i.e. 
98223       ** apply the affinity of the parent key). If this fails, then there
98224       ** is no matching parent key. Before using MustBeInt, make a copy of
98225       ** the value. Otherwise, the value inserted into the child key column
98226       ** will have INTEGER affinity applied to it, which may not be correct.  */
98227       sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
98228       iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
98229       VdbeCoverage(v);
98230   
98231       /* If the parent table is the same as the child table, and we are about
98232       ** to increment the constraint-counter (i.e. this is an INSERT operation),
98233       ** then check if the row being inserted matches itself. If so, do not
98234       ** increment the constraint-counter.  */
98235       if( pTab==pFKey->pFrom && nIncr==1 ){
98236         sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
98237         sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
98238       }
98239   
98240       sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
98241       sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
98242       sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
98243       sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
98244       sqlite3VdbeJumpHere(v, iMustBeInt);
98245       sqlite3ReleaseTempReg(pParse, regTemp);
98246     }else{
98247       int nCol = pFKey->nCol;
98248       int regTemp = sqlite3GetTempRange(pParse, nCol);
98249       int regRec = sqlite3GetTempReg(pParse);
98250   
98251       sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
98252       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
98253       for(i=0; i<nCol; i++){
98254         sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
98255       }
98256   
98257       /* If the parent table is the same as the child table, and we are about
98258       ** to increment the constraint-counter (i.e. this is an INSERT operation),
98259       ** then check if the row being inserted matches itself. If so, do not
98260       ** increment the constraint-counter. 
98261       **
98262       ** If any of the parent-key values are NULL, then the row cannot match 
98263       ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
98264       ** of the parent-key values are NULL (at this point it is known that
98265       ** none of the child key values are).
98266       */
98267       if( pTab==pFKey->pFrom && nIncr==1 ){
98268         int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
98269         for(i=0; i<nCol; i++){
98270           int iChild = aiCol[i]+1+regData;
98271           int iParent = pIdx->aiColumn[i]+1+regData;
98272           assert( aiCol[i]!=pTab->iPKey );
98273           if( pIdx->aiColumn[i]==pTab->iPKey ){
98274             /* The parent key is a composite key that includes the IPK column */
98275             iParent = regData;
98276           }
98277           sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
98278           sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
98279         }
98280         sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
98281       }
98282   
98283       sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
98284                         sqlite3IndexAffinityStr(v,pIdx), nCol);
98285       sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
98286   
98287       sqlite3ReleaseTempReg(pParse, regRec);
98288       sqlite3ReleaseTempRange(pParse, regTemp, nCol);
98289     }
98290   }
98291
98292   if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
98293    && !pParse->pToplevel 
98294    && !pParse->isMultiWrite 
98295   ){
98296     /* Special case: If this is an INSERT statement that will insert exactly
98297     ** one row into the table, raise a constraint immediately instead of
98298     ** incrementing a counter. This is necessary as the VM code is being
98299     ** generated for will not open a statement transaction.  */
98300     assert( nIncr==1 );
98301     sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
98302         OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
98303   }else{
98304     if( nIncr>0 && pFKey->isDeferred==0 ){
98305       sqlite3MayAbort(pParse);
98306     }
98307     sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
98308   }
98309
98310   sqlite3VdbeResolveLabel(v, iOk);
98311   sqlite3VdbeAddOp1(v, OP_Close, iCur);
98312 }
98313
98314
98315 /*
98316 ** Return an Expr object that refers to a memory register corresponding
98317 ** to column iCol of table pTab.
98318 **
98319 ** regBase is the first of an array of register that contains the data
98320 ** for pTab.  regBase itself holds the rowid.  regBase+1 holds the first
98321 ** column.  regBase+2 holds the second column, and so forth.
98322 */
98323 static Expr *exprTableRegister(
98324   Parse *pParse,     /* Parsing and code generating context */
98325   Table *pTab,       /* The table whose content is at r[regBase]... */
98326   int regBase,       /* Contents of table pTab */
98327   i16 iCol           /* Which column of pTab is desired */
98328 ){
98329   Expr *pExpr;
98330   Column *pCol;
98331   const char *zColl;
98332   sqlite3 *db = pParse->db;
98333
98334   pExpr = sqlite3Expr(db, TK_REGISTER, 0);
98335   if( pExpr ){
98336     if( iCol>=0 && iCol!=pTab->iPKey ){
98337       pCol = &pTab->aCol[iCol];
98338       pExpr->iTable = regBase + iCol + 1;
98339       pExpr->affinity = pCol->affinity;
98340       zColl = pCol->zColl;
98341       if( zColl==0 ) zColl = db->pDfltColl->zName;
98342       pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
98343     }else{
98344       pExpr->iTable = regBase;
98345       pExpr->affinity = SQLITE_AFF_INTEGER;
98346     }
98347   }
98348   return pExpr;
98349 }
98350
98351 /*
98352 ** Return an Expr object that refers to column iCol of table pTab which
98353 ** has cursor iCur.
98354 */
98355 static Expr *exprTableColumn(
98356   sqlite3 *db,      /* The database connection */
98357   Table *pTab,      /* The table whose column is desired */
98358   int iCursor,      /* The open cursor on the table */
98359   i16 iCol          /* The column that is wanted */
98360 ){
98361   Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
98362   if( pExpr ){
98363     pExpr->pTab = pTab;
98364     pExpr->iTable = iCursor;
98365     pExpr->iColumn = iCol;
98366   }
98367   return pExpr;
98368 }
98369
98370 /*
98371 ** This function is called to generate code executed when a row is deleted
98372 ** from the parent table of foreign key constraint pFKey and, if pFKey is 
98373 ** deferred, when a row is inserted into the same table. When generating
98374 ** code for an SQL UPDATE operation, this function may be called twice -
98375 ** once to "delete" the old row and once to "insert" the new row.
98376 **
98377 ** Parameter nIncr is passed -1 when inserting a row (as this may decrease
98378 ** the number of FK violations in the db) or +1 when deleting one (as this
98379 ** may increase the number of FK constraint problems).
98380 **
98381 ** The code generated by this function scans through the rows in the child
98382 ** table that correspond to the parent table row being deleted or inserted.
98383 ** For each child row found, one of the following actions is taken:
98384 **
98385 **   Operation | FK type   | Action taken
98386 **   --------------------------------------------------------------------------
98387 **   DELETE      immediate   Increment the "immediate constraint counter".
98388 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
98389 **                           throw a "FOREIGN KEY constraint failed" exception.
98390 **
98391 **   INSERT      immediate   Decrement the "immediate constraint counter".
98392 **
98393 **   DELETE      deferred    Increment the "deferred constraint counter".
98394 **                           Or, if the ON (UPDATE|DELETE) action is RESTRICT,
98395 **                           throw a "FOREIGN KEY constraint failed" exception.
98396 **
98397 **   INSERT      deferred    Decrement the "deferred constraint counter".
98398 **
98399 ** These operations are identified in the comment at the top of this file 
98400 ** (fkey.c) as "I.2" and "D.2".
98401 */
98402 static void fkScanChildren(
98403   Parse *pParse,                  /* Parse context */
98404   SrcList *pSrc,                  /* The child table to be scanned */
98405   Table *pTab,                    /* The parent table */
98406   Index *pIdx,                    /* Index on parent covering the foreign key */
98407   FKey *pFKey,                    /* The foreign key linking pSrc to pTab */
98408   int *aiCol,                     /* Map from pIdx cols to child table cols */
98409   int regData,                    /* Parent row data starts here */
98410   int nIncr                       /* Amount to increment deferred counter by */
98411 ){
98412   sqlite3 *db = pParse->db;       /* Database handle */
98413   int i;                          /* Iterator variable */
98414   Expr *pWhere = 0;               /* WHERE clause to scan with */
98415   NameContext sNameContext;       /* Context used to resolve WHERE clause */
98416   WhereInfo *pWInfo;              /* Context used by sqlite3WhereXXX() */
98417   int iFkIfZero = 0;              /* Address of OP_FkIfZero */
98418   Vdbe *v = sqlite3GetVdbe(pParse);
98419
98420   assert( pIdx==0 || pIdx->pTable==pTab );
98421   assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
98422   assert( pIdx!=0 || pFKey->nCol==1 );
98423   assert( pIdx!=0 || HasRowid(pTab) );
98424
98425   if( nIncr<0 ){
98426     iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
98427     VdbeCoverage(v);
98428   }
98429
98430   /* Create an Expr object representing an SQL expression like:
98431   **
98432   **   <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
98433   **
98434   ** The collation sequence used for the comparison should be that of
98435   ** the parent key columns. The affinity of the parent key column should
98436   ** be applied to each child key value before the comparison takes place.
98437   */
98438   for(i=0; i<pFKey->nCol; i++){
98439     Expr *pLeft;                  /* Value from parent table row */
98440     Expr *pRight;                 /* Column ref to child table */
98441     Expr *pEq;                    /* Expression (pLeft = pRight) */
98442     i16 iCol;                     /* Index of column in child table */ 
98443     const char *zCol;             /* Name of column in child table */
98444
98445     iCol = pIdx ? pIdx->aiColumn[i] : -1;
98446     pLeft = exprTableRegister(pParse, pTab, regData, iCol);
98447     iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
98448     assert( iCol>=0 );
98449     zCol = pFKey->pFrom->aCol[iCol].zName;
98450     pRight = sqlite3Expr(db, TK_ID, zCol);
98451     pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
98452     pWhere = sqlite3ExprAnd(db, pWhere, pEq);
98453   }
98454
98455   /* If the child table is the same as the parent table, then add terms
98456   ** to the WHERE clause that prevent this entry from being scanned.
98457   ** The added WHERE clause terms are like this:
98458   **
98459   **     $current_rowid!=rowid
98460   **     NOT( $current_a==a AND $current_b==b AND ... )
98461   **
98462   ** The first form is used for rowid tables.  The second form is used
98463   ** for WITHOUT ROWID tables.  In the second form, the primary key is
98464   ** (a,b,...)
98465   */
98466   if( pTab==pFKey->pFrom && nIncr>0 ){
98467     Expr *pNe;                    /* Expression (pLeft != pRight) */
98468     Expr *pLeft;                  /* Value from parent table row */
98469     Expr *pRight;                 /* Column ref to child table */
98470     if( HasRowid(pTab) ){
98471       pLeft = exprTableRegister(pParse, pTab, regData, -1);
98472       pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
98473       pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
98474     }else{
98475       Expr *pEq, *pAll = 0;
98476       Index *pPk = sqlite3PrimaryKeyIndex(pTab);
98477       assert( pIdx!=0 );
98478       for(i=0; i<pPk->nKeyCol; i++){
98479         i16 iCol = pIdx->aiColumn[i];
98480         pLeft = exprTableRegister(pParse, pTab, regData, iCol);
98481         pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
98482         pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
98483         pAll = sqlite3ExprAnd(db, pAll, pEq);
98484       }
98485       pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
98486     }
98487     pWhere = sqlite3ExprAnd(db, pWhere, pNe);
98488   }
98489
98490   /* Resolve the references in the WHERE clause. */
98491   memset(&sNameContext, 0, sizeof(NameContext));
98492   sNameContext.pSrcList = pSrc;
98493   sNameContext.pParse = pParse;
98494   sqlite3ResolveExprNames(&sNameContext, pWhere);
98495
98496   /* Create VDBE to loop through the entries in pSrc that match the WHERE
98497   ** clause. For each row found, increment either the deferred or immediate
98498   ** foreign key constraint counter. */
98499   pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
98500   sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
98501   if( pWInfo ){
98502     sqlite3WhereEnd(pWInfo);
98503   }
98504
98505   /* Clean up the WHERE clause constructed above. */
98506   sqlite3ExprDelete(db, pWhere);
98507   if( iFkIfZero ){
98508     sqlite3VdbeJumpHere(v, iFkIfZero);
98509   }
98510 }
98511
98512 /*
98513 ** This function returns a linked list of FKey objects (connected by
98514 ** FKey.pNextTo) holding all children of table pTab.  For example,
98515 ** given the following schema:
98516 **
98517 **   CREATE TABLE t1(a PRIMARY KEY);
98518 **   CREATE TABLE t2(b REFERENCES t1(a);
98519 **
98520 ** Calling this function with table "t1" as an argument returns a pointer
98521 ** to the FKey structure representing the foreign key constraint on table
98522 ** "t2". Calling this function with "t2" as the argument would return a
98523 ** NULL pointer (as there are no FK constraints for which t2 is the parent
98524 ** table).
98525 */
98526 SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
98527   return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
98528 }
98529
98530 /*
98531 ** The second argument is a Trigger structure allocated by the 
98532 ** fkActionTrigger() routine. This function deletes the Trigger structure
98533 ** and all of its sub-components.
98534 **
98535 ** The Trigger structure or any of its sub-components may be allocated from
98536 ** the lookaside buffer belonging to database handle dbMem.
98537 */
98538 static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
98539   if( p ){
98540     TriggerStep *pStep = p->step_list;
98541     sqlite3ExprDelete(dbMem, pStep->pWhere);
98542     sqlite3ExprListDelete(dbMem, pStep->pExprList);
98543     sqlite3SelectDelete(dbMem, pStep->pSelect);
98544     sqlite3ExprDelete(dbMem, p->pWhen);
98545     sqlite3DbFree(dbMem, p);
98546   }
98547 }
98548
98549 /*
98550 ** This function is called to generate code that runs when table pTab is
98551 ** being dropped from the database. The SrcList passed as the second argument
98552 ** to this function contains a single entry guaranteed to resolve to
98553 ** table pTab.
98554 **
98555 ** Normally, no code is required. However, if either
98556 **
98557 **   (a) The table is the parent table of a FK constraint, or
98558 **   (b) The table is the child table of a deferred FK constraint and it is
98559 **       determined at runtime that there are outstanding deferred FK 
98560 **       constraint violations in the database,
98561 **
98562 ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
98563 ** the table from the database. Triggers are disabled while running this
98564 ** DELETE, but foreign key actions are not.
98565 */
98566 SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
98567   sqlite3 *db = pParse->db;
98568   if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
98569     int iSkip = 0;
98570     Vdbe *v = sqlite3GetVdbe(pParse);
98571
98572     assert( v );                  /* VDBE has already been allocated */
98573     if( sqlite3FkReferences(pTab)==0 ){
98574       /* Search for a deferred foreign key constraint for which this table
98575       ** is the child table. If one cannot be found, return without 
98576       ** generating any VDBE code. If one can be found, then jump over
98577       ** the entire DELETE if there are no outstanding deferred constraints
98578       ** when this statement is run.  */
98579       FKey *p;
98580       for(p=pTab->pFKey; p; p=p->pNextFrom){
98581         if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
98582       }
98583       if( !p ) return;
98584       iSkip = sqlite3VdbeMakeLabel(v);
98585       sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
98586     }
98587
98588     pParse->disableTriggers = 1;
98589     sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
98590     pParse->disableTriggers = 0;
98591
98592     /* If the DELETE has generated immediate foreign key constraint 
98593     ** violations, halt the VDBE and return an error at this point, before
98594     ** any modifications to the schema are made. This is because statement
98595     ** transactions are not able to rollback schema changes.  
98596     **
98597     ** If the SQLITE_DeferFKs flag is set, then this is not required, as
98598     ** the statement transaction will not be rolled back even if FK
98599     ** constraints are violated.
98600     */
98601     if( (db->flags & SQLITE_DeferFKs)==0 ){
98602       sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
98603       VdbeCoverage(v);
98604       sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
98605           OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
98606     }
98607
98608     if( iSkip ){
98609       sqlite3VdbeResolveLabel(v, iSkip);
98610     }
98611   }
98612 }
98613
98614
98615 /*
98616 ** The second argument points to an FKey object representing a foreign key
98617 ** for which pTab is the child table. An UPDATE statement against pTab
98618 ** is currently being processed. For each column of the table that is 
98619 ** actually updated, the corresponding element in the aChange[] array
98620 ** is zero or greater (if a column is unmodified the corresponding element
98621 ** is set to -1). If the rowid column is modified by the UPDATE statement
98622 ** the bChngRowid argument is non-zero.
98623 **
98624 ** This function returns true if any of the columns that are part of the
98625 ** child key for FK constraint *p are modified.
98626 */
98627 static int fkChildIsModified(
98628   Table *pTab,                    /* Table being updated */
98629   FKey *p,                        /* Foreign key for which pTab is the child */
98630   int *aChange,                   /* Array indicating modified columns */
98631   int bChngRowid                  /* True if rowid is modified by this update */
98632 ){
98633   int i;
98634   for(i=0; i<p->nCol; i++){
98635     int iChildKey = p->aCol[i].iFrom;
98636     if( aChange[iChildKey]>=0 ) return 1;
98637     if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
98638   }
98639   return 0;
98640 }
98641
98642 /*
98643 ** The second argument points to an FKey object representing a foreign key
98644 ** for which pTab is the parent table. An UPDATE statement against pTab
98645 ** is currently being processed. For each column of the table that is 
98646 ** actually updated, the corresponding element in the aChange[] array
98647 ** is zero or greater (if a column is unmodified the corresponding element
98648 ** is set to -1). If the rowid column is modified by the UPDATE statement
98649 ** the bChngRowid argument is non-zero.
98650 **
98651 ** This function returns true if any of the columns that are part of the
98652 ** parent key for FK constraint *p are modified.
98653 */
98654 static int fkParentIsModified(
98655   Table *pTab, 
98656   FKey *p, 
98657   int *aChange, 
98658   int bChngRowid
98659 ){
98660   int i;
98661   for(i=0; i<p->nCol; i++){
98662     char *zKey = p->aCol[i].zCol;
98663     int iKey;
98664     for(iKey=0; iKey<pTab->nCol; iKey++){
98665       if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
98666         Column *pCol = &pTab->aCol[iKey];
98667         if( zKey ){
98668           if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
98669         }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
98670           return 1;
98671         }
98672       }
98673     }
98674   }
98675   return 0;
98676 }
98677
98678 /*
98679 ** Return true if the parser passed as the first argument is being
98680 ** used to code a trigger that is really a "SET NULL" action belonging
98681 ** to trigger pFKey.
98682 */
98683 static int isSetNullAction(Parse *pParse, FKey *pFKey){
98684   Parse *pTop = sqlite3ParseToplevel(pParse);
98685   if( pTop->pTriggerPrg ){
98686     Trigger *p = pTop->pTriggerPrg->pTrigger;
98687     if( (p==pFKey->apTrigger[0] && pFKey->aAction[0]==OE_SetNull)
98688      || (p==pFKey->apTrigger[1] && pFKey->aAction[1]==OE_SetNull)
98689     ){
98690       return 1;
98691     }
98692   }
98693   return 0;
98694 }
98695
98696 /*
98697 ** This function is called when inserting, deleting or updating a row of
98698 ** table pTab to generate VDBE code to perform foreign key constraint 
98699 ** processing for the operation.
98700 **
98701 ** For a DELETE operation, parameter regOld is passed the index of the
98702 ** first register in an array of (pTab->nCol+1) registers containing the
98703 ** rowid of the row being deleted, followed by each of the column values
98704 ** of the row being deleted, from left to right. Parameter regNew is passed
98705 ** zero in this case.
98706 **
98707 ** For an INSERT operation, regOld is passed zero and regNew is passed the
98708 ** first register of an array of (pTab->nCol+1) registers containing the new
98709 ** row data.
98710 **
98711 ** For an UPDATE operation, this function is called twice. Once before
98712 ** the original record is deleted from the table using the calling convention
98713 ** described for DELETE. Then again after the original record is deleted
98714 ** but before the new record is inserted using the INSERT convention. 
98715 */
98716 SQLITE_PRIVATE void sqlite3FkCheck(
98717   Parse *pParse,                  /* Parse context */
98718   Table *pTab,                    /* Row is being deleted from this table */ 
98719   int regOld,                     /* Previous row data is stored here */
98720   int regNew,                     /* New row data is stored here */
98721   int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
98722   int bChngRowid                  /* True if rowid is UPDATEd */
98723 ){
98724   sqlite3 *db = pParse->db;       /* Database handle */
98725   FKey *pFKey;                    /* Used to iterate through FKs */
98726   int iDb;                        /* Index of database containing pTab */
98727   const char *zDb;                /* Name of database containing pTab */
98728   int isIgnoreErrors = pParse->disableTriggers;
98729
98730   /* Exactly one of regOld and regNew should be non-zero. */
98731   assert( (regOld==0)!=(regNew==0) );
98732
98733   /* If foreign-keys are disabled, this function is a no-op. */
98734   if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
98735
98736   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
98737   zDb = db->aDb[iDb].zName;
98738
98739   /* Loop through all the foreign key constraints for which pTab is the
98740   ** child table (the table that the foreign key definition is part of).  */
98741   for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
98742     Table *pTo;                   /* Parent table of foreign key pFKey */
98743     Index *pIdx = 0;              /* Index on key columns in pTo */
98744     int *aiFree = 0;
98745     int *aiCol;
98746     int iCol;
98747     int i;
98748     int bIgnore = 0;
98749
98750     if( aChange 
98751      && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
98752      && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0 
98753     ){
98754       continue;
98755     }
98756
98757     /* Find the parent table of this foreign key. Also find a unique index 
98758     ** on the parent key columns in the parent table. If either of these 
98759     ** schema items cannot be located, set an error in pParse and return 
98760     ** early.  */
98761     if( pParse->disableTriggers ){
98762       pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
98763     }else{
98764       pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
98765     }
98766     if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
98767       assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
98768       if( !isIgnoreErrors || db->mallocFailed ) return;
98769       if( pTo==0 ){
98770         /* If isIgnoreErrors is true, then a table is being dropped. In this
98771         ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
98772         ** before actually dropping it in order to check FK constraints.
98773         ** If the parent table of an FK constraint on the current table is
98774         ** missing, behave as if it is empty. i.e. decrement the relevant
98775         ** FK counter for each row of the current table with non-NULL keys.
98776         */
98777         Vdbe *v = sqlite3GetVdbe(pParse);
98778         int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
98779         for(i=0; i<pFKey->nCol; i++){
98780           int iReg = pFKey->aCol[i].iFrom + regOld + 1;
98781           sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
98782         }
98783         sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
98784       }
98785       continue;
98786     }
98787     assert( pFKey->nCol==1 || (aiFree && pIdx) );
98788
98789     if( aiFree ){
98790       aiCol = aiFree;
98791     }else{
98792       iCol = pFKey->aCol[0].iFrom;
98793       aiCol = &iCol;
98794     }
98795     for(i=0; i<pFKey->nCol; i++){
98796       if( aiCol[i]==pTab->iPKey ){
98797         aiCol[i] = -1;
98798       }
98799 #ifndef SQLITE_OMIT_AUTHORIZATION
98800       /* Request permission to read the parent key columns. If the 
98801       ** authorization callback returns SQLITE_IGNORE, behave as if any
98802       ** values read from the parent table are NULL. */
98803       if( db->xAuth ){
98804         int rcauth;
98805         char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
98806         rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
98807         bIgnore = (rcauth==SQLITE_IGNORE);
98808       }
98809 #endif
98810     }
98811
98812     /* Take a shared-cache advisory read-lock on the parent table. Allocate 
98813     ** a cursor to use to search the unique index on the parent key columns 
98814     ** in the parent table.  */
98815     sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
98816     pParse->nTab++;
98817
98818     if( regOld!=0 ){
98819       /* A row is being removed from the child table. Search for the parent.
98820       ** If the parent does not exist, removing the child row resolves an 
98821       ** outstanding foreign key constraint violation. */
98822       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1, bIgnore);
98823     }
98824     if( regNew!=0 && !isSetNullAction(pParse, pFKey) ){
98825       /* A row is being added to the child table. If a parent row cannot
98826       ** be found, adding the child row has violated the FK constraint. 
98827       **
98828       ** If this operation is being performed as part of a trigger program
98829       ** that is actually a "SET NULL" action belonging to this very 
98830       ** foreign key, then omit this scan altogether. As all child key
98831       ** values are guaranteed to be NULL, it is not possible for adding
98832       ** this row to cause an FK violation.  */
98833       fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1, bIgnore);
98834     }
98835
98836     sqlite3DbFree(db, aiFree);
98837   }
98838
98839   /* Loop through all the foreign key constraints that refer to this table.
98840   ** (the "child" constraints) */
98841   for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
98842     Index *pIdx = 0;              /* Foreign key index for pFKey */
98843     SrcList *pSrc;
98844     int *aiCol = 0;
98845
98846     if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
98847       continue;
98848     }
98849
98850     if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs) 
98851      && !pParse->pToplevel && !pParse->isMultiWrite 
98852     ){
98853       assert( regOld==0 && regNew!=0 );
98854       /* Inserting a single row into a parent table cannot cause (or fix)
98855       ** an immediate foreign key violation. So do nothing in this case.  */
98856       continue;
98857     }
98858
98859     if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
98860       if( !isIgnoreErrors || db->mallocFailed ) return;
98861       continue;
98862     }
98863     assert( aiCol || pFKey->nCol==1 );
98864
98865     /* Create a SrcList structure containing the child table.  We need the
98866     ** child table as a SrcList for sqlite3WhereBegin() */
98867     pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
98868     if( pSrc ){
98869       struct SrcList_item *pItem = pSrc->a;
98870       pItem->pTab = pFKey->pFrom;
98871       pItem->zName = pFKey->pFrom->zName;
98872       pItem->pTab->nRef++;
98873       pItem->iCursor = pParse->nTab++;
98874   
98875       if( regNew!=0 ){
98876         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
98877       }
98878       if( regOld!=0 ){
98879         int eAction = pFKey->aAction[aChange!=0];
98880         fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
98881         /* If this is a deferred FK constraint, or a CASCADE or SET NULL
98882         ** action applies, then any foreign key violations caused by
98883         ** removing the parent key will be rectified by the action trigger.
98884         ** So do not set the "may-abort" flag in this case.
98885         **
98886         ** Note 1: If the FK is declared "ON UPDATE CASCADE", then the
98887         ** may-abort flag will eventually be set on this statement anyway
98888         ** (when this function is called as part of processing the UPDATE
98889         ** within the action trigger).
98890         **
98891         ** Note 2: At first glance it may seem like SQLite could simply omit
98892         ** all OP_FkCounter related scans when either CASCADE or SET NULL
98893         ** applies. The trouble starts if the CASCADE or SET NULL action 
98894         ** trigger causes other triggers or action rules attached to the 
98895         ** child table to fire. In these cases the fk constraint counters
98896         ** might be set incorrectly if any OP_FkCounter related scans are 
98897         ** omitted.  */
98898         if( !pFKey->isDeferred && eAction!=OE_Cascade && eAction!=OE_SetNull ){
98899           sqlite3MayAbort(pParse);
98900         }
98901       }
98902       pItem->zName = 0;
98903       sqlite3SrcListDelete(db, pSrc);
98904     }
98905     sqlite3DbFree(db, aiCol);
98906   }
98907 }
98908
98909 #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
98910
98911 /*
98912 ** This function is called before generating code to update or delete a 
98913 ** row contained in table pTab.
98914 */
98915 SQLITE_PRIVATE u32 sqlite3FkOldmask(
98916   Parse *pParse,                  /* Parse context */
98917   Table *pTab                     /* Table being modified */
98918 ){
98919   u32 mask = 0;
98920   if( pParse->db->flags&SQLITE_ForeignKeys ){
98921     FKey *p;
98922     int i;
98923     for(p=pTab->pFKey; p; p=p->pNextFrom){
98924       for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
98925     }
98926     for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
98927       Index *pIdx = 0;
98928       sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
98929       if( pIdx ){
98930         for(i=0; i<pIdx->nKeyCol; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
98931       }
98932     }
98933   }
98934   return mask;
98935 }
98936
98937
98938 /*
98939 ** This function is called before generating code to update or delete a 
98940 ** row contained in table pTab. If the operation is a DELETE, then
98941 ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
98942 ** to an array of size N, where N is the number of columns in table pTab.
98943 ** If the i'th column is not modified by the UPDATE, then the corresponding 
98944 ** entry in the aChange[] array is set to -1. If the column is modified,
98945 ** the value is 0 or greater. Parameter chngRowid is set to true if the
98946 ** UPDATE statement modifies the rowid fields of the table.
98947 **
98948 ** If any foreign key processing will be required, this function returns
98949 ** true. If there is no foreign key related processing, this function 
98950 ** returns false.
98951 */
98952 SQLITE_PRIVATE int sqlite3FkRequired(
98953   Parse *pParse,                  /* Parse context */
98954   Table *pTab,                    /* Table being modified */
98955   int *aChange,                   /* Non-NULL for UPDATE operations */
98956   int chngRowid                   /* True for UPDATE that affects rowid */
98957 ){
98958   if( pParse->db->flags&SQLITE_ForeignKeys ){
98959     if( !aChange ){
98960       /* A DELETE operation. Foreign key processing is required if the 
98961       ** table in question is either the child or parent table for any 
98962       ** foreign key constraint.  */
98963       return (sqlite3FkReferences(pTab) || pTab->pFKey);
98964     }else{
98965       /* This is an UPDATE. Foreign key processing is only required if the
98966       ** operation modifies one or more child or parent key columns. */
98967       FKey *p;
98968
98969       /* Check if any child key columns are being modified. */
98970       for(p=pTab->pFKey; p; p=p->pNextFrom){
98971         if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
98972       }
98973
98974       /* Check if any parent key columns are being modified. */
98975       for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
98976         if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
98977       }
98978     }
98979   }
98980   return 0;
98981 }
98982
98983 /*
98984 ** This function is called when an UPDATE or DELETE operation is being 
98985 ** compiled on table pTab, which is the parent table of foreign-key pFKey.
98986 ** If the current operation is an UPDATE, then the pChanges parameter is
98987 ** passed a pointer to the list of columns being modified. If it is a
98988 ** DELETE, pChanges is passed a NULL pointer.
98989 **
98990 ** It returns a pointer to a Trigger structure containing a trigger
98991 ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
98992 ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
98993 ** returned (these actions require no special handling by the triggers
98994 ** sub-system, code for them is created by fkScanChildren()).
98995 **
98996 ** For example, if pFKey is the foreign key and pTab is table "p" in 
98997 ** the following schema:
98998 **
98999 **   CREATE TABLE p(pk PRIMARY KEY);
99000 **   CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
99001 **
99002 ** then the returned trigger structure is equivalent to:
99003 **
99004 **   CREATE TRIGGER ... DELETE ON p BEGIN
99005 **     DELETE FROM c WHERE ck = old.pk;
99006 **   END;
99007 **
99008 ** The returned pointer is cached as part of the foreign key object. It
99009 ** is eventually freed along with the rest of the foreign key object by 
99010 ** sqlite3FkDelete().
99011 */
99012 static Trigger *fkActionTrigger(
99013   Parse *pParse,                  /* Parse context */
99014   Table *pTab,                    /* Table being updated or deleted from */
99015   FKey *pFKey,                    /* Foreign key to get action for */
99016   ExprList *pChanges              /* Change-list for UPDATE, NULL for DELETE */
99017 ){
99018   sqlite3 *db = pParse->db;       /* Database handle */
99019   int action;                     /* One of OE_None, OE_Cascade etc. */
99020   Trigger *pTrigger;              /* Trigger definition to return */
99021   int iAction = (pChanges!=0);    /* 1 for UPDATE, 0 for DELETE */
99022
99023   action = pFKey->aAction[iAction];
99024   pTrigger = pFKey->apTrigger[iAction];
99025
99026   if( action!=OE_None && !pTrigger ){
99027     u8 enableLookaside;           /* Copy of db->lookaside.bEnabled */
99028     char const *zFrom;            /* Name of child table */
99029     int nFrom;                    /* Length in bytes of zFrom */
99030     Index *pIdx = 0;              /* Parent key index for this FK */
99031     int *aiCol = 0;               /* child table cols -> parent key cols */
99032     TriggerStep *pStep = 0;        /* First (only) step of trigger program */
99033     Expr *pWhere = 0;             /* WHERE clause of trigger step */
99034     ExprList *pList = 0;          /* Changes list if ON UPDATE CASCADE */
99035     Select *pSelect = 0;          /* If RESTRICT, "SELECT RAISE(...)" */
99036     int i;                        /* Iterator variable */
99037     Expr *pWhen = 0;              /* WHEN clause for the trigger */
99038
99039     if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
99040     assert( aiCol || pFKey->nCol==1 );
99041
99042     for(i=0; i<pFKey->nCol; i++){
99043       Token tOld = { "old", 3 };  /* Literal "old" token */
99044       Token tNew = { "new", 3 };  /* Literal "new" token */
99045       Token tFromCol;             /* Name of column in child table */
99046       Token tToCol;               /* Name of column in parent table */
99047       int iFromCol;               /* Idx of column in child table */
99048       Expr *pEq;                  /* tFromCol = OLD.tToCol */
99049
99050       iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
99051       assert( iFromCol>=0 );
99052       tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
99053       tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
99054
99055       tToCol.n = sqlite3Strlen30(tToCol.z);
99056       tFromCol.n = sqlite3Strlen30(tFromCol.z);
99057
99058       /* Create the expression "OLD.zToCol = zFromCol". It is important
99059       ** that the "OLD.zToCol" term is on the LHS of the = operator, so
99060       ** that the affinity and collation sequence associated with the
99061       ** parent table are used for the comparison. */
99062       pEq = sqlite3PExpr(pParse, TK_EQ,
99063           sqlite3PExpr(pParse, TK_DOT, 
99064             sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
99065             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
99066           , 0),
99067           sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
99068       , 0);
99069       pWhere = sqlite3ExprAnd(db, pWhere, pEq);
99070
99071       /* For ON UPDATE, construct the next term of the WHEN clause.
99072       ** The final WHEN clause will be like this:
99073       **
99074       **    WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
99075       */
99076       if( pChanges ){
99077         pEq = sqlite3PExpr(pParse, TK_IS,
99078             sqlite3PExpr(pParse, TK_DOT, 
99079               sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
99080               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
99081               0),
99082             sqlite3PExpr(pParse, TK_DOT, 
99083               sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
99084               sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
99085               0),
99086             0);
99087         pWhen = sqlite3ExprAnd(db, pWhen, pEq);
99088       }
99089   
99090       if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
99091         Expr *pNew;
99092         if( action==OE_Cascade ){
99093           pNew = sqlite3PExpr(pParse, TK_DOT, 
99094             sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
99095             sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
99096           , 0);
99097         }else if( action==OE_SetDflt ){
99098           Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
99099           if( pDflt ){
99100             pNew = sqlite3ExprDup(db, pDflt, 0);
99101           }else{
99102             pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
99103           }
99104         }else{
99105           pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
99106         }
99107         pList = sqlite3ExprListAppend(pParse, pList, pNew);
99108         sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
99109       }
99110     }
99111     sqlite3DbFree(db, aiCol);
99112
99113     zFrom = pFKey->pFrom->zName;
99114     nFrom = sqlite3Strlen30(zFrom);
99115
99116     if( action==OE_Restrict ){
99117       Token tFrom;
99118       Expr *pRaise; 
99119
99120       tFrom.z = zFrom;
99121       tFrom.n = nFrom;
99122       pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
99123       if( pRaise ){
99124         pRaise->affinity = OE_Abort;
99125       }
99126       pSelect = sqlite3SelectNew(pParse, 
99127           sqlite3ExprListAppend(pParse, 0, pRaise),
99128           sqlite3SrcListAppend(db, 0, &tFrom, 0),
99129           pWhere,
99130           0, 0, 0, 0, 0, 0
99131       );
99132       pWhere = 0;
99133     }
99134
99135     /* Disable lookaside memory allocation */
99136     enableLookaside = db->lookaside.bEnabled;
99137     db->lookaside.bEnabled = 0;
99138
99139     pTrigger = (Trigger *)sqlite3DbMallocZero(db, 
99140         sizeof(Trigger) +         /* struct Trigger */
99141         sizeof(TriggerStep) +     /* Single step in trigger program */
99142         nFrom + 1                 /* Space for pStep->target.z */
99143     );
99144     if( pTrigger ){
99145       pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
99146       pStep->target.z = (char *)&pStep[1];
99147       pStep->target.n = nFrom;
99148       memcpy((char *)pStep->target.z, zFrom, nFrom);
99149   
99150       pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
99151       pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
99152       pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
99153       if( pWhen ){
99154         pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
99155         pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
99156       }
99157     }
99158
99159     /* Re-enable the lookaside buffer, if it was disabled earlier. */
99160     db->lookaside.bEnabled = enableLookaside;
99161
99162     sqlite3ExprDelete(db, pWhere);
99163     sqlite3ExprDelete(db, pWhen);
99164     sqlite3ExprListDelete(db, pList);
99165     sqlite3SelectDelete(db, pSelect);
99166     if( db->mallocFailed==1 ){
99167       fkTriggerDelete(db, pTrigger);
99168       return 0;
99169     }
99170     assert( pStep!=0 );
99171
99172     switch( action ){
99173       case OE_Restrict:
99174         pStep->op = TK_SELECT; 
99175         break;
99176       case OE_Cascade: 
99177         if( !pChanges ){ 
99178           pStep->op = TK_DELETE; 
99179           break; 
99180         }
99181       default:
99182         pStep->op = TK_UPDATE;
99183     }
99184     pStep->pTrig = pTrigger;
99185     pTrigger->pSchema = pTab->pSchema;
99186     pTrigger->pTabSchema = pTab->pSchema;
99187     pFKey->apTrigger[iAction] = pTrigger;
99188     pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
99189   }
99190
99191   return pTrigger;
99192 }
99193
99194 /*
99195 ** This function is called when deleting or updating a row to implement
99196 ** any required CASCADE, SET NULL or SET DEFAULT actions.
99197 */
99198 SQLITE_PRIVATE void sqlite3FkActions(
99199   Parse *pParse,                  /* Parse context */
99200   Table *pTab,                    /* Table being updated or deleted from */
99201   ExprList *pChanges,             /* Change-list for UPDATE, NULL for DELETE */
99202   int regOld,                     /* Address of array containing old row */
99203   int *aChange,                   /* Array indicating UPDATEd columns (or 0) */
99204   int bChngRowid                  /* True if rowid is UPDATEd */
99205 ){
99206   /* If foreign-key support is enabled, iterate through all FKs that 
99207   ** refer to table pTab. If there is an action associated with the FK 
99208   ** for this operation (either update or delete), invoke the associated 
99209   ** trigger sub-program.  */
99210   if( pParse->db->flags&SQLITE_ForeignKeys ){
99211     FKey *pFKey;                  /* Iterator variable */
99212     for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
99213       if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
99214         Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
99215         if( pAct ){
99216           sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
99217         }
99218       }
99219     }
99220   }
99221 }
99222
99223 #endif /* ifndef SQLITE_OMIT_TRIGGER */
99224
99225 /*
99226 ** Free all memory associated with foreign key definitions attached to
99227 ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
99228 ** hash table.
99229 */
99230 SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
99231   FKey *pFKey;                    /* Iterator variable */
99232   FKey *pNext;                    /* Copy of pFKey->pNextFrom */
99233
99234   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
99235   for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
99236
99237     /* Remove the FK from the fkeyHash hash table. */
99238     if( !db || db->pnBytesFreed==0 ){
99239       if( pFKey->pPrevTo ){
99240         pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
99241       }else{
99242         void *p = (void *)pFKey->pNextTo;
99243         const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
99244         sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
99245       }
99246       if( pFKey->pNextTo ){
99247         pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
99248       }
99249     }
99250
99251     /* EV: R-30323-21917 Each foreign key constraint in SQLite is
99252     ** classified as either immediate or deferred.
99253     */
99254     assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
99255
99256     /* Delete any triggers created to implement actions for this FK. */
99257 #ifndef SQLITE_OMIT_TRIGGER
99258     fkTriggerDelete(db, pFKey->apTrigger[0]);
99259     fkTriggerDelete(db, pFKey->apTrigger[1]);
99260 #endif
99261
99262     pNext = pFKey->pNextFrom;
99263     sqlite3DbFree(db, pFKey);
99264   }
99265 }
99266 #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
99267
99268 /************** End of fkey.c ************************************************/
99269 /************** Begin file insert.c ******************************************/
99270 /*
99271 ** 2001 September 15
99272 **
99273 ** The author disclaims copyright to this source code.  In place of
99274 ** a legal notice, here is a blessing:
99275 **
99276 **    May you do good and not evil.
99277 **    May you find forgiveness for yourself and forgive others.
99278 **    May you share freely, never taking more than you give.
99279 **
99280 *************************************************************************
99281 ** This file contains C code routines that are called by the parser
99282 ** to handle INSERT statements in SQLite.
99283 */
99284
99285 /*
99286 ** Generate code that will 
99287 **
99288 **   (1) acquire a lock for table pTab then
99289 **   (2) open pTab as cursor iCur.
99290 **
99291 ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
99292 ** for that table that is actually opened.
99293 */
99294 SQLITE_PRIVATE void sqlite3OpenTable(
99295   Parse *pParse,  /* Generate code into this VDBE */
99296   int iCur,       /* The cursor number of the table */
99297   int iDb,        /* The database index in sqlite3.aDb[] */
99298   Table *pTab,    /* The table to be opened */
99299   int opcode      /* OP_OpenRead or OP_OpenWrite */
99300 ){
99301   Vdbe *v;
99302   assert( !IsVirtual(pTab) );
99303   v = sqlite3GetVdbe(pParse);
99304   assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
99305   sqlite3TableLock(pParse, iDb, pTab->tnum, 
99306                    (opcode==OP_OpenWrite)?1:0, pTab->zName);
99307   if( HasRowid(pTab) ){
99308     sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
99309     VdbeComment((v, "%s", pTab->zName));
99310   }else{
99311     Index *pPk = sqlite3PrimaryKeyIndex(pTab);
99312     assert( pPk!=0 );
99313     assert( pPk->tnum=pTab->tnum );
99314     sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
99315     sqlite3VdbeSetP4KeyInfo(pParse, pPk);
99316     VdbeComment((v, "%s", pTab->zName));
99317   }
99318 }
99319
99320 /*
99321 ** Return a pointer to the column affinity string associated with index
99322 ** pIdx. A column affinity string has one character for each column in 
99323 ** the table, according to the affinity of the column:
99324 **
99325 **  Character      Column affinity
99326 **  ------------------------------
99327 **  'A'            NONE
99328 **  'B'            TEXT
99329 **  'C'            NUMERIC
99330 **  'D'            INTEGER
99331 **  'F'            REAL
99332 **
99333 ** An extra 'D' is appended to the end of the string to cover the
99334 ** rowid that appears as the last column in every index.
99335 **
99336 ** Memory for the buffer containing the column index affinity string
99337 ** is managed along with the rest of the Index structure. It will be
99338 ** released when sqlite3DeleteIndex() is called.
99339 */
99340 SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
99341   if( !pIdx->zColAff ){
99342     /* The first time a column affinity string for a particular index is
99343     ** required, it is allocated and populated here. It is then stored as
99344     ** a member of the Index structure for subsequent use.
99345     **
99346     ** The column affinity string will eventually be deleted by
99347     ** sqliteDeleteIndex() when the Index structure itself is cleaned
99348     ** up.
99349     */
99350     int n;
99351     Table *pTab = pIdx->pTable;
99352     sqlite3 *db = sqlite3VdbeDb(v);
99353     pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
99354     if( !pIdx->zColAff ){
99355       db->mallocFailed = 1;
99356       return 0;
99357     }
99358     for(n=0; n<pIdx->nColumn; n++){
99359       i16 x = pIdx->aiColumn[n];
99360       pIdx->zColAff[n] = x<0 ? SQLITE_AFF_INTEGER : pTab->aCol[x].affinity;
99361     }
99362     pIdx->zColAff[n] = 0;
99363   }
99364  
99365   return pIdx->zColAff;
99366 }
99367
99368 /*
99369 ** Compute the affinity string for table pTab, if it has not already been
99370 ** computed.  As an optimization, omit trailing SQLITE_AFF_NONE affinities.
99371 **
99372 ** If the affinity exists (if it is no entirely SQLITE_AFF_NONE values) and
99373 ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
99374 ** for register iReg and following.  Or if affinities exists and iReg==0,
99375 ** then just set the P4 operand of the previous opcode (which should  be
99376 ** an OP_MakeRecord) to the affinity string.
99377 **
99378 ** A column affinity string has one character per column:
99379 **
99380 **  Character      Column affinity
99381 **  ------------------------------
99382 **  'A'            NONE
99383 **  'B'            TEXT
99384 **  'C'            NUMERIC
99385 **  'D'            INTEGER
99386 **  'E'            REAL
99387 */
99388 SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
99389   int i;
99390   char *zColAff = pTab->zColAff;
99391   if( zColAff==0 ){
99392     sqlite3 *db = sqlite3VdbeDb(v);
99393     zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
99394     if( !zColAff ){
99395       db->mallocFailed = 1;
99396       return;
99397     }
99398
99399     for(i=0; i<pTab->nCol; i++){
99400       zColAff[i] = pTab->aCol[i].affinity;
99401     }
99402     do{
99403       zColAff[i--] = 0;
99404     }while( i>=0 && zColAff[i]==SQLITE_AFF_NONE );
99405     pTab->zColAff = zColAff;
99406   }
99407   i = sqlite3Strlen30(zColAff);
99408   if( i ){
99409     if( iReg ){
99410       sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
99411     }else{
99412       sqlite3VdbeChangeP4(v, -1, zColAff, i);
99413     }
99414   }
99415 }
99416
99417 /*
99418 ** Return non-zero if the table pTab in database iDb or any of its indices
99419 ** have been opened at any point in the VDBE program. This is used to see if 
99420 ** a statement of the form  "INSERT INTO <iDb, pTab> SELECT ..." can 
99421 ** run without using a temporary table for the results of the SELECT. 
99422 */
99423 static int readsTable(Parse *p, int iDb, Table *pTab){
99424   Vdbe *v = sqlite3GetVdbe(p);
99425   int i;
99426   int iEnd = sqlite3VdbeCurrentAddr(v);
99427 #ifndef SQLITE_OMIT_VIRTUALTABLE
99428   VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
99429 #endif
99430
99431   for(i=1; i<iEnd; i++){
99432     VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
99433     assert( pOp!=0 );
99434     if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
99435       Index *pIndex;
99436       int tnum = pOp->p2;
99437       if( tnum==pTab->tnum ){
99438         return 1;
99439       }
99440       for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
99441         if( tnum==pIndex->tnum ){
99442           return 1;
99443         }
99444       }
99445     }
99446 #ifndef SQLITE_OMIT_VIRTUALTABLE
99447     if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
99448       assert( pOp->p4.pVtab!=0 );
99449       assert( pOp->p4type==P4_VTAB );
99450       return 1;
99451     }
99452 #endif
99453   }
99454   return 0;
99455 }
99456
99457 #ifndef SQLITE_OMIT_AUTOINCREMENT
99458 /*
99459 ** Locate or create an AutoincInfo structure associated with table pTab
99460 ** which is in database iDb.  Return the register number for the register
99461 ** that holds the maximum rowid.
99462 **
99463 ** There is at most one AutoincInfo structure per table even if the
99464 ** same table is autoincremented multiple times due to inserts within
99465 ** triggers.  A new AutoincInfo structure is created if this is the
99466 ** first use of table pTab.  On 2nd and subsequent uses, the original
99467 ** AutoincInfo structure is used.
99468 **
99469 ** Three memory locations are allocated:
99470 **
99471 **   (1)  Register to hold the name of the pTab table.
99472 **   (2)  Register to hold the maximum ROWID of pTab.
99473 **   (3)  Register to hold the rowid in sqlite_sequence of pTab
99474 **
99475 ** The 2nd register is the one that is returned.  That is all the
99476 ** insert routine needs to know about.
99477 */
99478 static int autoIncBegin(
99479   Parse *pParse,      /* Parsing context */
99480   int iDb,            /* Index of the database holding pTab */
99481   Table *pTab         /* The table we are writing to */
99482 ){
99483   int memId = 0;      /* Register holding maximum rowid */
99484   if( pTab->tabFlags & TF_Autoincrement ){
99485     Parse *pToplevel = sqlite3ParseToplevel(pParse);
99486     AutoincInfo *pInfo;
99487
99488     pInfo = pToplevel->pAinc;
99489     while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
99490     if( pInfo==0 ){
99491       pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
99492       if( pInfo==0 ) return 0;
99493       pInfo->pNext = pToplevel->pAinc;
99494       pToplevel->pAinc = pInfo;
99495       pInfo->pTab = pTab;
99496       pInfo->iDb = iDb;
99497       pToplevel->nMem++;                  /* Register to hold name of table */
99498       pInfo->regCtr = ++pToplevel->nMem;  /* Max rowid register */
99499       pToplevel->nMem++;                  /* Rowid in sqlite_sequence */
99500     }
99501     memId = pInfo->regCtr;
99502   }
99503   return memId;
99504 }
99505
99506 /*
99507 ** This routine generates code that will initialize all of the
99508 ** register used by the autoincrement tracker.  
99509 */
99510 SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
99511   AutoincInfo *p;            /* Information about an AUTOINCREMENT */
99512   sqlite3 *db = pParse->db;  /* The database connection */
99513   Db *pDb;                   /* Database only autoinc table */
99514   int memId;                 /* Register holding max rowid */
99515   int addr;                  /* A VDBE address */
99516   Vdbe *v = pParse->pVdbe;   /* VDBE under construction */
99517
99518   /* This routine is never called during trigger-generation.  It is
99519   ** only called from the top-level */
99520   assert( pParse->pTriggerTab==0 );
99521   assert( pParse==sqlite3ParseToplevel(pParse) );
99522
99523   assert( v );   /* We failed long ago if this is not so */
99524   for(p = pParse->pAinc; p; p = p->pNext){
99525     pDb = &db->aDb[p->iDb];
99526     memId = p->regCtr;
99527     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
99528     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
99529     sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
99530     addr = sqlite3VdbeCurrentAddr(v);
99531     sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
99532     sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); VdbeCoverage(v);
99533     sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
99534     sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); VdbeCoverage(v);
99535     sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
99536     sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
99537     sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
99538     sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
99539     sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); VdbeCoverage(v);
99540     sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
99541     sqlite3VdbeAddOp0(v, OP_Close);
99542   }
99543 }
99544
99545 /*
99546 ** Update the maximum rowid for an autoincrement calculation.
99547 **
99548 ** This routine should be called when the top of the stack holds a
99549 ** new rowid that is about to be inserted.  If that new rowid is
99550 ** larger than the maximum rowid in the memId memory cell, then the
99551 ** memory cell is updated.  The stack is unchanged.
99552 */
99553 static void autoIncStep(Parse *pParse, int memId, int regRowid){
99554   if( memId>0 ){
99555     sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
99556   }
99557 }
99558
99559 /*
99560 ** This routine generates the code needed to write autoincrement
99561 ** maximum rowid values back into the sqlite_sequence register.
99562 ** Every statement that might do an INSERT into an autoincrement
99563 ** table (either directly or through triggers) needs to call this
99564 ** routine just before the "exit" code.
99565 */
99566 SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
99567   AutoincInfo *p;
99568   Vdbe *v = pParse->pVdbe;
99569   sqlite3 *db = pParse->db;
99570
99571   assert( v );
99572   for(p = pParse->pAinc; p; p = p->pNext){
99573     Db *pDb = &db->aDb[p->iDb];
99574     int j1;
99575     int iRec;
99576     int memId = p->regCtr;
99577
99578     iRec = sqlite3GetTempReg(pParse);
99579     assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
99580     sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
99581     j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); VdbeCoverage(v);
99582     sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
99583     sqlite3VdbeJumpHere(v, j1);
99584     sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
99585     sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
99586     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
99587     sqlite3VdbeAddOp0(v, OP_Close);
99588     sqlite3ReleaseTempReg(pParse, iRec);
99589   }
99590 }
99591 #else
99592 /*
99593 ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
99594 ** above are all no-ops
99595 */
99596 # define autoIncBegin(A,B,C) (0)
99597 # define autoIncStep(A,B,C)
99598 #endif /* SQLITE_OMIT_AUTOINCREMENT */
99599
99600
99601 /* Forward declaration */
99602 static int xferOptimization(
99603   Parse *pParse,        /* Parser context */
99604   Table *pDest,         /* The table we are inserting into */
99605   Select *pSelect,      /* A SELECT statement to use as the data source */
99606   int onError,          /* How to handle constraint errors */
99607   int iDbDest           /* The database of pDest */
99608 );
99609
99610 /*
99611 ** This routine is called to handle SQL of the following forms:
99612 **
99613 **    insert into TABLE (IDLIST) values(EXPRLIST)
99614 **    insert into TABLE (IDLIST) select
99615 **
99616 ** The IDLIST following the table name is always optional.  If omitted,
99617 ** then a list of all columns for the table is substituted.  The IDLIST
99618 ** appears in the pColumn parameter.  pColumn is NULL if IDLIST is omitted.
99619 **
99620 ** The pList parameter holds EXPRLIST in the first form of the INSERT
99621 ** statement above, and pSelect is NULL.  For the second form, pList is
99622 ** NULL and pSelect is a pointer to the select statement used to generate
99623 ** data for the insert.
99624 **
99625 ** The code generated follows one of four templates.  For a simple
99626 ** insert with data coming from a VALUES clause, the code executes
99627 ** once straight down through.  Pseudo-code follows (we call this
99628 ** the "1st template"):
99629 **
99630 **         open write cursor to <table> and its indices
99631 **         put VALUES clause expressions into registers
99632 **         write the resulting record into <table>
99633 **         cleanup
99634 **
99635 ** The three remaining templates assume the statement is of the form
99636 **
99637 **   INSERT INTO <table> SELECT ...
99638 **
99639 ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
99640 ** in other words if the SELECT pulls all columns from a single table
99641 ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
99642 ** if <table2> and <table1> are distinct tables but have identical
99643 ** schemas, including all the same indices, then a special optimization
99644 ** is invoked that copies raw records from <table2> over to <table1>.
99645 ** See the xferOptimization() function for the implementation of this
99646 ** template.  This is the 2nd template.
99647 **
99648 **         open a write cursor to <table>
99649 **         open read cursor on <table2>
99650 **         transfer all records in <table2> over to <table>
99651 **         close cursors
99652 **         foreach index on <table>
99653 **           open a write cursor on the <table> index
99654 **           open a read cursor on the corresponding <table2> index
99655 **           transfer all records from the read to the write cursors
99656 **           close cursors
99657 **         end foreach
99658 **
99659 ** The 3rd template is for when the second template does not apply
99660 ** and the SELECT clause does not read from <table> at any time.
99661 ** The generated code follows this template:
99662 **
99663 **         X <- A
99664 **         goto B
99665 **      A: setup for the SELECT
99666 **         loop over the rows in the SELECT
99667 **           load values into registers R..R+n
99668 **           yield X
99669 **         end loop
99670 **         cleanup after the SELECT
99671 **         end-coroutine X
99672 **      B: open write cursor to <table> and its indices
99673 **      C: yield X, at EOF goto D
99674 **         insert the select result into <table> from R..R+n
99675 **         goto C
99676 **      D: cleanup
99677 **
99678 ** The 4th template is used if the insert statement takes its
99679 ** values from a SELECT but the data is being inserted into a table
99680 ** that is also read as part of the SELECT.  In the third form,
99681 ** we have to use an intermediate table to store the results of
99682 ** the select.  The template is like this:
99683 **
99684 **         X <- A
99685 **         goto B
99686 **      A: setup for the SELECT
99687 **         loop over the tables in the SELECT
99688 **           load value into register R..R+n
99689 **           yield X
99690 **         end loop
99691 **         cleanup after the SELECT
99692 **         end co-routine R
99693 **      B: open temp table
99694 **      L: yield X, at EOF goto M
99695 **         insert row from R..R+n into temp table
99696 **         goto L
99697 **      M: open write cursor to <table> and its indices
99698 **         rewind temp table
99699 **      C: loop over rows of intermediate table
99700 **           transfer values form intermediate table into <table>
99701 **         end loop
99702 **      D: cleanup
99703 */
99704 SQLITE_PRIVATE void sqlite3Insert(
99705   Parse *pParse,        /* Parser context */
99706   SrcList *pTabList,    /* Name of table into which we are inserting */
99707   Select *pSelect,      /* A SELECT statement to use as the data source */
99708   IdList *pColumn,      /* Column names corresponding to IDLIST. */
99709   int onError           /* How to handle constraint errors */
99710 ){
99711   sqlite3 *db;          /* The main database structure */
99712   Table *pTab;          /* The table to insert into.  aka TABLE */
99713   char *zTab;           /* Name of the table into which we are inserting */
99714   const char *zDb;      /* Name of the database holding this table */
99715   int i, j, idx;        /* Loop counters */
99716   Vdbe *v;              /* Generate code into this virtual machine */
99717   Index *pIdx;          /* For looping over indices of the table */
99718   int nColumn;          /* Number of columns in the data */
99719   int nHidden = 0;      /* Number of hidden columns if TABLE is virtual */
99720   int iDataCur = 0;     /* VDBE cursor that is the main data repository */
99721   int iIdxCur = 0;      /* First index cursor */
99722   int ipkColumn = -1;   /* Column that is the INTEGER PRIMARY KEY */
99723   int endOfLoop;        /* Label for the end of the insertion loop */
99724   int srcTab = 0;       /* Data comes from this temporary cursor if >=0 */
99725   int addrInsTop = 0;   /* Jump to label "D" */
99726   int addrCont = 0;     /* Top of insert loop. Label "C" in templates 3 and 4 */
99727   SelectDest dest;      /* Destination for SELECT on rhs of INSERT */
99728   int iDb;              /* Index of database holding TABLE */
99729   Db *pDb;              /* The database containing table being inserted into */
99730   u8 useTempTable = 0;  /* Store SELECT results in intermediate table */
99731   u8 appendFlag = 0;    /* True if the insert is likely to be an append */
99732   u8 withoutRowid;      /* 0 for normal table.  1 for WITHOUT ROWID table */
99733   u8 bIdListInOrder = 1; /* True if IDLIST is in table order */
99734   ExprList *pList = 0;  /* List of VALUES() to be inserted  */
99735
99736   /* Register allocations */
99737   int regFromSelect = 0;/* Base register for data coming from SELECT */
99738   int regAutoinc = 0;   /* Register holding the AUTOINCREMENT counter */
99739   int regRowCount = 0;  /* Memory cell used for the row counter */
99740   int regIns;           /* Block of regs holding rowid+data being inserted */
99741   int regRowid;         /* registers holding insert rowid */
99742   int regData;          /* register holding first column to insert */
99743   int *aRegIdx = 0;     /* One register allocated to each index */
99744
99745 #ifndef SQLITE_OMIT_TRIGGER
99746   int isView;                 /* True if attempting to insert into a view */
99747   Trigger *pTrigger;          /* List of triggers on pTab, if required */
99748   int tmask;                  /* Mask of trigger times */
99749 #endif
99750
99751   db = pParse->db;
99752   memset(&dest, 0, sizeof(dest));
99753   if( pParse->nErr || db->mallocFailed ){
99754     goto insert_cleanup;
99755   }
99756
99757   /* If the Select object is really just a simple VALUES() list with a
99758   ** single row values (the common case) then keep that one row of values
99759   ** and go ahead and discard the Select object
99760   */
99761   if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
99762     pList = pSelect->pEList;
99763     pSelect->pEList = 0;
99764     sqlite3SelectDelete(db, pSelect);
99765     pSelect = 0;
99766   }
99767
99768   /* Locate the table into which we will be inserting new information.
99769   */
99770   assert( pTabList->nSrc==1 );
99771   zTab = pTabList->a[0].zName;
99772   if( NEVER(zTab==0) ) goto insert_cleanup;
99773   pTab = sqlite3SrcListLookup(pParse, pTabList);
99774   if( pTab==0 ){
99775     goto insert_cleanup;
99776   }
99777   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
99778   assert( iDb<db->nDb );
99779   pDb = &db->aDb[iDb];
99780   zDb = pDb->zName;
99781   if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
99782     goto insert_cleanup;
99783   }
99784   withoutRowid = !HasRowid(pTab);
99785
99786   /* Figure out if we have any triggers and if the table being
99787   ** inserted into is a view
99788   */
99789 #ifndef SQLITE_OMIT_TRIGGER
99790   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
99791   isView = pTab->pSelect!=0;
99792 #else
99793 # define pTrigger 0
99794 # define tmask 0
99795 # define isView 0
99796 #endif
99797 #ifdef SQLITE_OMIT_VIEW
99798 # undef isView
99799 # define isView 0
99800 #endif
99801   assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
99802
99803   /* If pTab is really a view, make sure it has been initialized.
99804   ** ViewGetColumnNames() is a no-op if pTab is not a view.
99805   */
99806   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
99807     goto insert_cleanup;
99808   }
99809
99810   /* Cannot insert into a read-only table.
99811   */
99812   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
99813     goto insert_cleanup;
99814   }
99815
99816   /* Allocate a VDBE
99817   */
99818   v = sqlite3GetVdbe(pParse);
99819   if( v==0 ) goto insert_cleanup;
99820   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
99821   sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
99822
99823 #ifndef SQLITE_OMIT_XFER_OPT
99824   /* If the statement is of the form
99825   **
99826   **       INSERT INTO <table1> SELECT * FROM <table2>;
99827   **
99828   ** Then special optimizations can be applied that make the transfer
99829   ** very fast and which reduce fragmentation of indices.
99830   **
99831   ** This is the 2nd template.
99832   */
99833   if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
99834     assert( !pTrigger );
99835     assert( pList==0 );
99836     goto insert_end;
99837   }
99838 #endif /* SQLITE_OMIT_XFER_OPT */
99839
99840   /* If this is an AUTOINCREMENT table, look up the sequence number in the
99841   ** sqlite_sequence table and store it in memory cell regAutoinc.
99842   */
99843   regAutoinc = autoIncBegin(pParse, iDb, pTab);
99844
99845   /* Allocate registers for holding the rowid of the new row,
99846   ** the content of the new row, and the assembled row record.
99847   */
99848   regRowid = regIns = pParse->nMem+1;
99849   pParse->nMem += pTab->nCol + 1;
99850   if( IsVirtual(pTab) ){
99851     regRowid++;
99852     pParse->nMem++;
99853   }
99854   regData = regRowid+1;
99855
99856   /* If the INSERT statement included an IDLIST term, then make sure
99857   ** all elements of the IDLIST really are columns of the table and 
99858   ** remember the column indices.
99859   **
99860   ** If the table has an INTEGER PRIMARY KEY column and that column
99861   ** is named in the IDLIST, then record in the ipkColumn variable
99862   ** the index into IDLIST of the primary key column.  ipkColumn is
99863   ** the index of the primary key as it appears in IDLIST, not as
99864   ** is appears in the original table.  (The index of the INTEGER
99865   ** PRIMARY KEY in the original table is pTab->iPKey.)
99866   */
99867   if( pColumn ){
99868     for(i=0; i<pColumn->nId; i++){
99869       pColumn->a[i].idx = -1;
99870     }
99871     for(i=0; i<pColumn->nId; i++){
99872       for(j=0; j<pTab->nCol; j++){
99873         if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
99874           pColumn->a[i].idx = j;
99875           if( i!=j ) bIdListInOrder = 0;
99876           if( j==pTab->iPKey ){
99877             ipkColumn = i;  assert( !withoutRowid );
99878           }
99879           break;
99880         }
99881       }
99882       if( j>=pTab->nCol ){
99883         if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
99884           ipkColumn = i;
99885           bIdListInOrder = 0;
99886         }else{
99887           sqlite3ErrorMsg(pParse, "table %S has no column named %s",
99888               pTabList, 0, pColumn->a[i].zName);
99889           pParse->checkSchema = 1;
99890           goto insert_cleanup;
99891         }
99892       }
99893     }
99894   }
99895
99896   /* Figure out how many columns of data are supplied.  If the data
99897   ** is coming from a SELECT statement, then generate a co-routine that
99898   ** produces a single row of the SELECT on each invocation.  The
99899   ** co-routine is the common header to the 3rd and 4th templates.
99900   */
99901   if( pSelect ){
99902     /* Data is coming from a SELECT.  Generate a co-routine to run the SELECT */
99903     int regYield;       /* Register holding co-routine entry-point */
99904     int addrTop;        /* Top of the co-routine */
99905     int rc;             /* Result code */
99906
99907     regYield = ++pParse->nMem;
99908     addrTop = sqlite3VdbeCurrentAddr(v) + 1;
99909     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
99910     sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
99911     dest.iSdst = bIdListInOrder ? regData : 0;
99912     dest.nSdst = pTab->nCol;
99913     rc = sqlite3Select(pParse, pSelect, &dest);
99914     regFromSelect = dest.iSdst;
99915     assert( pParse->nErr==0 || rc );
99916     if( rc || db->mallocFailed ) goto insert_cleanup;
99917     sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
99918     sqlite3VdbeJumpHere(v, addrTop - 1);                       /* label B: */
99919     assert( pSelect->pEList );
99920     nColumn = pSelect->pEList->nExpr;
99921
99922     /* Set useTempTable to TRUE if the result of the SELECT statement
99923     ** should be written into a temporary table (template 4).  Set to
99924     ** FALSE if each output row of the SELECT can be written directly into
99925     ** the destination table (template 3).
99926     **
99927     ** A temp table must be used if the table being updated is also one
99928     ** of the tables being read by the SELECT statement.  Also use a 
99929     ** temp table in the case of row triggers.
99930     */
99931     if( pTrigger || readsTable(pParse, iDb, pTab) ){
99932       useTempTable = 1;
99933     }
99934
99935     if( useTempTable ){
99936       /* Invoke the coroutine to extract information from the SELECT
99937       ** and add it to a transient table srcTab.  The code generated
99938       ** here is from the 4th template:
99939       **
99940       **      B: open temp table
99941       **      L: yield X, goto M at EOF
99942       **         insert row from R..R+n into temp table
99943       **         goto L
99944       **      M: ...
99945       */
99946       int regRec;          /* Register to hold packed record */
99947       int regTempRowid;    /* Register to hold temp table ROWID */
99948       int addrL;           /* Label "L" */
99949
99950       srcTab = pParse->nTab++;
99951       regRec = sqlite3GetTempReg(pParse);
99952       regTempRowid = sqlite3GetTempReg(pParse);
99953       sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
99954       addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
99955       sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
99956       sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
99957       sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
99958       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrL);
99959       sqlite3VdbeJumpHere(v, addrL);
99960       sqlite3ReleaseTempReg(pParse, regRec);
99961       sqlite3ReleaseTempReg(pParse, regTempRowid);
99962     }
99963   }else{
99964     /* This is the case if the data for the INSERT is coming from a VALUES
99965     ** clause
99966     */
99967     NameContext sNC;
99968     memset(&sNC, 0, sizeof(sNC));
99969     sNC.pParse = pParse;
99970     srcTab = -1;
99971     assert( useTempTable==0 );
99972     nColumn = pList ? pList->nExpr : 0;
99973     for(i=0; i<nColumn; i++){
99974       if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
99975         goto insert_cleanup;
99976       }
99977     }
99978   }
99979
99980   /* If there is no IDLIST term but the table has an integer primary
99981   ** key, the set the ipkColumn variable to the integer primary key 
99982   ** column index in the original table definition.
99983   */
99984   if( pColumn==0 && nColumn>0 ){
99985     ipkColumn = pTab->iPKey;
99986   }
99987
99988   /* Make sure the number of columns in the source data matches the number
99989   ** of columns to be inserted into the table.
99990   */
99991   if( IsVirtual(pTab) ){
99992     for(i=0; i<pTab->nCol; i++){
99993       nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
99994     }
99995   }
99996   if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
99997     sqlite3ErrorMsg(pParse, 
99998        "table %S has %d columns but %d values were supplied",
99999        pTabList, 0, pTab->nCol-nHidden, nColumn);
100000     goto insert_cleanup;
100001   }
100002   if( pColumn!=0 && nColumn!=pColumn->nId ){
100003     sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
100004     goto insert_cleanup;
100005   }
100006     
100007   /* Initialize the count of rows to be inserted
100008   */
100009   if( db->flags & SQLITE_CountRows ){
100010     regRowCount = ++pParse->nMem;
100011     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
100012   }
100013
100014   /* If this is not a view, open the table and and all indices */
100015   if( !isView ){
100016     int nIdx;
100017     nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1, 0,
100018                                       &iDataCur, &iIdxCur);
100019     aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
100020     if( aRegIdx==0 ){
100021       goto insert_cleanup;
100022     }
100023     for(i=0; i<nIdx; i++){
100024       aRegIdx[i] = ++pParse->nMem;
100025     }
100026   }
100027
100028   /* This is the top of the main insertion loop */
100029   if( useTempTable ){
100030     /* This block codes the top of loop only.  The complete loop is the
100031     ** following pseudocode (template 4):
100032     **
100033     **         rewind temp table, if empty goto D
100034     **      C: loop over rows of intermediate table
100035     **           transfer values form intermediate table into <table>
100036     **         end loop
100037     **      D: ...
100038     */
100039     addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
100040     addrCont = sqlite3VdbeCurrentAddr(v);
100041   }else if( pSelect ){
100042     /* This block codes the top of loop only.  The complete loop is the
100043     ** following pseudocode (template 3):
100044     **
100045     **      C: yield X, at EOF goto D
100046     **         insert the select result into <table> from R..R+n
100047     **         goto C
100048     **      D: ...
100049     */
100050     addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
100051     VdbeCoverage(v);
100052   }
100053
100054   /* Run the BEFORE and INSTEAD OF triggers, if there are any
100055   */
100056   endOfLoop = sqlite3VdbeMakeLabel(v);
100057   if( tmask & TRIGGER_BEFORE ){
100058     int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
100059
100060     /* build the NEW.* reference row.  Note that if there is an INTEGER
100061     ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
100062     ** translated into a unique ID for the row.  But on a BEFORE trigger,
100063     ** we do not know what the unique ID will be (because the insert has
100064     ** not happened yet) so we substitute a rowid of -1
100065     */
100066     if( ipkColumn<0 ){
100067       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
100068     }else{
100069       int j1;
100070       assert( !withoutRowid );
100071       if( useTempTable ){
100072         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
100073       }else{
100074         assert( pSelect==0 );  /* Otherwise useTempTable is true */
100075         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
100076       }
100077       j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
100078       sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
100079       sqlite3VdbeJumpHere(v, j1);
100080       sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
100081     }
100082
100083     /* Cannot have triggers on a virtual table. If it were possible,
100084     ** this block would have to account for hidden column.
100085     */
100086     assert( !IsVirtual(pTab) );
100087
100088     /* Create the new column data
100089     */
100090     for(i=0; i<pTab->nCol; i++){
100091       if( pColumn==0 ){
100092         j = i;
100093       }else{
100094         for(j=0; j<pColumn->nId; j++){
100095           if( pColumn->a[j].idx==i ) break;
100096         }
100097       }
100098       if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
100099         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
100100       }else if( useTempTable ){
100101         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1); 
100102       }else{
100103         assert( pSelect==0 ); /* Otherwise useTempTable is true */
100104         sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
100105       }
100106     }
100107
100108     /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
100109     ** do not attempt any conversions before assembling the record.
100110     ** If this is a real table, attempt conversions as required by the
100111     ** table column affinities.
100112     */
100113     if( !isView ){
100114       sqlite3TableAffinity(v, pTab, regCols+1);
100115     }
100116
100117     /* Fire BEFORE or INSTEAD OF triggers */
100118     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE, 
100119         pTab, regCols-pTab->nCol-1, onError, endOfLoop);
100120
100121     sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
100122   }
100123
100124   /* Compute the content of the next row to insert into a range of
100125   ** registers beginning at regIns.
100126   */
100127   if( !isView ){
100128     if( IsVirtual(pTab) ){
100129       /* The row that the VUpdate opcode will delete: none */
100130       sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
100131     }
100132     if( ipkColumn>=0 ){
100133       if( useTempTable ){
100134         sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
100135       }else if( pSelect ){
100136         sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
100137       }else{
100138         VdbeOp *pOp;
100139         sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
100140         pOp = sqlite3VdbeGetOp(v, -1);
100141         if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
100142           appendFlag = 1;
100143           pOp->opcode = OP_NewRowid;
100144           pOp->p1 = iDataCur;
100145           pOp->p2 = regRowid;
100146           pOp->p3 = regAutoinc;
100147         }
100148       }
100149       /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
100150       ** to generate a unique primary key value.
100151       */
100152       if( !appendFlag ){
100153         int j1;
100154         if( !IsVirtual(pTab) ){
100155           j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
100156           sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
100157           sqlite3VdbeJumpHere(v, j1);
100158         }else{
100159           j1 = sqlite3VdbeCurrentAddr(v);
100160           sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); VdbeCoverage(v);
100161         }
100162         sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
100163       }
100164     }else if( IsVirtual(pTab) || withoutRowid ){
100165       sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
100166     }else{
100167       sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
100168       appendFlag = 1;
100169     }
100170     autoIncStep(pParse, regAutoinc, regRowid);
100171
100172     /* Compute data for all columns of the new entry, beginning
100173     ** with the first column.
100174     */
100175     nHidden = 0;
100176     for(i=0; i<pTab->nCol; i++){
100177       int iRegStore = regRowid+1+i;
100178       if( i==pTab->iPKey ){
100179         /* The value of the INTEGER PRIMARY KEY column is always a NULL.
100180         ** Whenever this column is read, the rowid will be substituted
100181         ** in its place.  Hence, fill this column with a NULL to avoid
100182         ** taking up data space with information that will never be used.
100183         ** As there may be shallow copies of this value, make it a soft-NULL */
100184         sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
100185         continue;
100186       }
100187       if( pColumn==0 ){
100188         if( IsHiddenColumn(&pTab->aCol[i]) ){
100189           assert( IsVirtual(pTab) );
100190           j = -1;
100191           nHidden++;
100192         }else{
100193           j = i - nHidden;
100194         }
100195       }else{
100196         for(j=0; j<pColumn->nId; j++){
100197           if( pColumn->a[j].idx==i ) break;
100198         }
100199       }
100200       if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
100201         sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
100202       }else if( useTempTable ){
100203         sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore); 
100204       }else if( pSelect ){
100205         if( regFromSelect!=regData ){
100206           sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
100207         }
100208       }else{
100209         sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
100210       }
100211     }
100212
100213     /* Generate code to check constraints and generate index keys and
100214     ** do the insertion.
100215     */
100216 #ifndef SQLITE_OMIT_VIRTUALTABLE
100217     if( IsVirtual(pTab) ){
100218       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
100219       sqlite3VtabMakeWritable(pParse, pTab);
100220       sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
100221       sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
100222       sqlite3MayAbort(pParse);
100223     }else
100224 #endif
100225     {
100226       int isReplace;    /* Set to true if constraints may cause a replace */
100227       sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
100228           regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace
100229       );
100230       sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
100231       sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
100232                                regIns, aRegIdx, 0, appendFlag, isReplace==0);
100233     }
100234   }
100235
100236   /* Update the count of rows that are inserted
100237   */
100238   if( (db->flags & SQLITE_CountRows)!=0 ){
100239     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
100240   }
100241
100242   if( pTrigger ){
100243     /* Code AFTER triggers */
100244     sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER, 
100245         pTab, regData-2-pTab->nCol, onError, endOfLoop);
100246   }
100247
100248   /* The bottom of the main insertion loop, if the data source
100249   ** is a SELECT statement.
100250   */
100251   sqlite3VdbeResolveLabel(v, endOfLoop);
100252   if( useTempTable ){
100253     sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
100254     sqlite3VdbeJumpHere(v, addrInsTop);
100255     sqlite3VdbeAddOp1(v, OP_Close, srcTab);
100256   }else if( pSelect ){
100257     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
100258     sqlite3VdbeJumpHere(v, addrInsTop);
100259   }
100260
100261   if( !IsVirtual(pTab) && !isView ){
100262     /* Close all tables opened */
100263     if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
100264     for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
100265       sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
100266     }
100267   }
100268
100269 insert_end:
100270   /* Update the sqlite_sequence table by storing the content of the
100271   ** maximum rowid counter values recorded while inserting into
100272   ** autoincrement tables.
100273   */
100274   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
100275     sqlite3AutoincrementEnd(pParse);
100276   }
100277
100278   /*
100279   ** Return the number of rows inserted. If this routine is 
100280   ** generating code because of a call to sqlite3NestedParse(), do not
100281   ** invoke the callback function.
100282   */
100283   if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
100284     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
100285     sqlite3VdbeSetNumCols(v, 1);
100286     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
100287   }
100288
100289 insert_cleanup:
100290   sqlite3SrcListDelete(db, pTabList);
100291   sqlite3ExprListDelete(db, pList);
100292   sqlite3SelectDelete(db, pSelect);
100293   sqlite3IdListDelete(db, pColumn);
100294   sqlite3DbFree(db, aRegIdx);
100295 }
100296
100297 /* Make sure "isView" and other macros defined above are undefined. Otherwise
100298 ** they may interfere with compilation of other functions in this file
100299 ** (or in another file, if this file becomes part of the amalgamation).  */
100300 #ifdef isView
100301  #undef isView
100302 #endif
100303 #ifdef pTrigger
100304  #undef pTrigger
100305 #endif
100306 #ifdef tmask
100307  #undef tmask
100308 #endif
100309
100310 /*
100311 ** Generate code to do constraint checks prior to an INSERT or an UPDATE
100312 ** on table pTab.
100313 **
100314 ** The regNewData parameter is the first register in a range that contains
100315 ** the data to be inserted or the data after the update.  There will be
100316 ** pTab->nCol+1 registers in this range.  The first register (the one
100317 ** that regNewData points to) will contain the new rowid, or NULL in the
100318 ** case of a WITHOUT ROWID table.  The second register in the range will
100319 ** contain the content of the first table column.  The third register will
100320 ** contain the content of the second table column.  And so forth.
100321 **
100322 ** The regOldData parameter is similar to regNewData except that it contains
100323 ** the data prior to an UPDATE rather than afterwards.  regOldData is zero
100324 ** for an INSERT.  This routine can distinguish between UPDATE and INSERT by
100325 ** checking regOldData for zero.
100326 **
100327 ** For an UPDATE, the pkChng boolean is true if the true primary key (the
100328 ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
100329 ** might be modified by the UPDATE.  If pkChng is false, then the key of
100330 ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
100331 **
100332 ** For an INSERT, the pkChng boolean indicates whether or not the rowid
100333 ** was explicitly specified as part of the INSERT statement.  If pkChng
100334 ** is zero, it means that the either rowid is computed automatically or
100335 ** that the table is a WITHOUT ROWID table and has no rowid.  On an INSERT,
100336 ** pkChng will only be true if the INSERT statement provides an integer
100337 ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
100338 **
100339 ** The code generated by this routine will store new index entries into
100340 ** registers identified by aRegIdx[].  No index entry is created for
100341 ** indices where aRegIdx[i]==0.  The order of indices in aRegIdx[] is
100342 ** the same as the order of indices on the linked list of indices
100343 ** at pTab->pIndex.
100344 **
100345 ** The caller must have already opened writeable cursors on the main
100346 ** table and all applicable indices (that is to say, all indices for which
100347 ** aRegIdx[] is not zero).  iDataCur is the cursor for the main table when
100348 ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
100349 ** index when operating on a WITHOUT ROWID table.  iIdxCur is the cursor
100350 ** for the first index in the pTab->pIndex list.  Cursors for other indices
100351 ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
100352 **
100353 ** This routine also generates code to check constraints.  NOT NULL,
100354 ** CHECK, and UNIQUE constraints are all checked.  If a constraint fails,
100355 ** then the appropriate action is performed.  There are five possible
100356 ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
100357 **
100358 **  Constraint type  Action       What Happens
100359 **  ---------------  ----------   ----------------------------------------
100360 **  any              ROLLBACK     The current transaction is rolled back and
100361 **                                sqlite3_step() returns immediately with a
100362 **                                return code of SQLITE_CONSTRAINT.
100363 **
100364 **  any              ABORT        Back out changes from the current command
100365 **                                only (do not do a complete rollback) then
100366 **                                cause sqlite3_step() to return immediately
100367 **                                with SQLITE_CONSTRAINT.
100368 **
100369 **  any              FAIL         Sqlite3_step() returns immediately with a
100370 **                                return code of SQLITE_CONSTRAINT.  The
100371 **                                transaction is not rolled back and any
100372 **                                changes to prior rows are retained.
100373 **
100374 **  any              IGNORE       The attempt in insert or update the current
100375 **                                row is skipped, without throwing an error.
100376 **                                Processing continues with the next row.
100377 **                                (There is an immediate jump to ignoreDest.)
100378 **
100379 **  NOT NULL         REPLACE      The NULL value is replace by the default
100380 **                                value for that column.  If the default value
100381 **                                is NULL, the action is the same as ABORT.
100382 **
100383 **  UNIQUE           REPLACE      The other row that conflicts with the row
100384 **                                being inserted is removed.
100385 **
100386 **  CHECK            REPLACE      Illegal.  The results in an exception.
100387 **
100388 ** Which action to take is determined by the overrideError parameter.
100389 ** Or if overrideError==OE_Default, then the pParse->onError parameter
100390 ** is used.  Or if pParse->onError==OE_Default then the onError value
100391 ** for the constraint is used.
100392 */
100393 SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
100394   Parse *pParse,       /* The parser context */
100395   Table *pTab,         /* The table being inserted or updated */
100396   int *aRegIdx,        /* Use register aRegIdx[i] for index i.  0 for unused */
100397   int iDataCur,        /* Canonical data cursor (main table or PK index) */
100398   int iIdxCur,         /* First index cursor */
100399   int regNewData,      /* First register in a range holding values to insert */
100400   int regOldData,      /* Previous content.  0 for INSERTs */
100401   u8 pkChng,           /* Non-zero if the rowid or PRIMARY KEY changed */
100402   u8 overrideError,    /* Override onError to this if not OE_Default */
100403   int ignoreDest,      /* Jump to this label on an OE_Ignore resolution */
100404   int *pbMayReplace    /* OUT: Set to true if constraint may cause a replace */
100405 ){
100406   Vdbe *v;             /* VDBE under constrution */
100407   Index *pIdx;         /* Pointer to one of the indices */
100408   Index *pPk = 0;      /* The PRIMARY KEY index */
100409   sqlite3 *db;         /* Database connection */
100410   int i;               /* loop counter */
100411   int ix;              /* Index loop counter */
100412   int nCol;            /* Number of columns */
100413   int onError;         /* Conflict resolution strategy */
100414   int j1;              /* Address of jump instruction */
100415   int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
100416   int nPkField;        /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
100417   int ipkTop = 0;      /* Top of the rowid change constraint check */
100418   int ipkBottom = 0;   /* Bottom of the rowid change constraint check */
100419   u8 isUpdate;         /* True if this is an UPDATE operation */
100420   u8 bAffinityDone = 0;  /* True if the OP_Affinity operation has been run */
100421   int regRowid = -1;   /* Register holding ROWID value */
100422
100423   isUpdate = regOldData!=0;
100424   db = pParse->db;
100425   v = sqlite3GetVdbe(pParse);
100426   assert( v!=0 );
100427   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
100428   nCol = pTab->nCol;
100429   
100430   /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
100431   ** normal rowid tables.  nPkField is the number of key fields in the 
100432   ** pPk index or 1 for a rowid table.  In other words, nPkField is the
100433   ** number of fields in the true primary key of the table. */
100434   if( HasRowid(pTab) ){
100435     pPk = 0;
100436     nPkField = 1;
100437   }else{
100438     pPk = sqlite3PrimaryKeyIndex(pTab);
100439     nPkField = pPk->nKeyCol;
100440   }
100441
100442   /* Record that this module has started */
100443   VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
100444                      iDataCur, iIdxCur, regNewData, regOldData, pkChng));
100445
100446   /* Test all NOT NULL constraints.
100447   */
100448   for(i=0; i<nCol; i++){
100449     if( i==pTab->iPKey ){
100450       continue;
100451     }
100452     onError = pTab->aCol[i].notNull;
100453     if( onError==OE_None ) continue;
100454     if( overrideError!=OE_Default ){
100455       onError = overrideError;
100456     }else if( onError==OE_Default ){
100457       onError = OE_Abort;
100458     }
100459     if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
100460       onError = OE_Abort;
100461     }
100462     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
100463         || onError==OE_Ignore || onError==OE_Replace );
100464     switch( onError ){
100465       case OE_Abort:
100466         sqlite3MayAbort(pParse);
100467         /* Fall through */
100468       case OE_Rollback:
100469       case OE_Fail: {
100470         char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
100471                                     pTab->aCol[i].zName);
100472         sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
100473                           regNewData+1+i, zMsg, P4_DYNAMIC);
100474         sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
100475         VdbeCoverage(v);
100476         break;
100477       }
100478       case OE_Ignore: {
100479         sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
100480         VdbeCoverage(v);
100481         break;
100482       }
100483       default: {
100484         assert( onError==OE_Replace );
100485         j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); VdbeCoverage(v);
100486         sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
100487         sqlite3VdbeJumpHere(v, j1);
100488         break;
100489       }
100490     }
100491   }
100492
100493   /* Test all CHECK constraints
100494   */
100495 #ifndef SQLITE_OMIT_CHECK
100496   if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
100497     ExprList *pCheck = pTab->pCheck;
100498     pParse->ckBase = regNewData+1;
100499     onError = overrideError!=OE_Default ? overrideError : OE_Abort;
100500     for(i=0; i<pCheck->nExpr; i++){
100501       int allOk = sqlite3VdbeMakeLabel(v);
100502       sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
100503       if( onError==OE_Ignore ){
100504         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
100505       }else{
100506         char *zName = pCheck->a[i].zName;
100507         if( zName==0 ) zName = pTab->zName;
100508         if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
100509         sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
100510                               onError, zName, P4_TRANSIENT,
100511                               P5_ConstraintCheck);
100512       }
100513       sqlite3VdbeResolveLabel(v, allOk);
100514     }
100515   }
100516 #endif /* !defined(SQLITE_OMIT_CHECK) */
100517
100518   /* If rowid is changing, make sure the new rowid does not previously
100519   ** exist in the table.
100520   */
100521   if( pkChng && pPk==0 ){
100522     int addrRowidOk = sqlite3VdbeMakeLabel(v);
100523
100524     /* Figure out what action to take in case of a rowid collision */
100525     onError = pTab->keyConf;
100526     if( overrideError!=OE_Default ){
100527       onError = overrideError;
100528     }else if( onError==OE_Default ){
100529       onError = OE_Abort;
100530     }
100531
100532     if( isUpdate ){
100533       /* pkChng!=0 does not mean that the rowid has change, only that
100534       ** it might have changed.  Skip the conflict logic below if the rowid
100535       ** is unchanged. */
100536       sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
100537       sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
100538       VdbeCoverage(v);
100539     }
100540
100541     /* If the response to a rowid conflict is REPLACE but the response
100542     ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
100543     ** to defer the running of the rowid conflict checking until after
100544     ** the UNIQUE constraints have run.
100545     */
100546     if( onError==OE_Replace && overrideError!=OE_Replace ){
100547       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
100548         if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
100549           ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
100550           break;
100551         }
100552       }
100553     }
100554
100555     /* Check to see if the new rowid already exists in the table.  Skip
100556     ** the following conflict logic if it does not. */
100557     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
100558     VdbeCoverage(v);
100559
100560     /* Generate code that deals with a rowid collision */
100561     switch( onError ){
100562       default: {
100563         onError = OE_Abort;
100564         /* Fall thru into the next case */
100565       }
100566       case OE_Rollback:
100567       case OE_Abort:
100568       case OE_Fail: {
100569         sqlite3RowidConstraint(pParse, onError, pTab);
100570         break;
100571       }
100572       case OE_Replace: {
100573         /* If there are DELETE triggers on this table and the
100574         ** recursive-triggers flag is set, call GenerateRowDelete() to
100575         ** remove the conflicting row from the table. This will fire
100576         ** the triggers and remove both the table and index b-tree entries.
100577         **
100578         ** Otherwise, if there are no triggers or the recursive-triggers
100579         ** flag is not set, but the table has one or more indexes, call 
100580         ** GenerateRowIndexDelete(). This removes the index b-tree entries 
100581         ** only. The table b-tree entry will be replaced by the new entry 
100582         ** when it is inserted.  
100583         **
100584         ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
100585         ** also invoke MultiWrite() to indicate that this VDBE may require
100586         ** statement rollback (if the statement is aborted after the delete
100587         ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
100588         ** but being more selective here allows statements like:
100589         **
100590         **   REPLACE INTO t(rowid) VALUES($newrowid)
100591         **
100592         ** to run without a statement journal if there are no indexes on the
100593         ** table.
100594         */
100595         Trigger *pTrigger = 0;
100596         if( db->flags&SQLITE_RecTriggers ){
100597           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
100598         }
100599         if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
100600           sqlite3MultiWrite(pParse);
100601           sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
100602                                    regNewData, 1, 0, OE_Replace, 1);
100603         }else if( pTab->pIndex ){
100604           sqlite3MultiWrite(pParse);
100605           sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
100606         }
100607         seenReplace = 1;
100608         break;
100609       }
100610       case OE_Ignore: {
100611         /*assert( seenReplace==0 );*/
100612         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
100613         break;
100614       }
100615     }
100616     sqlite3VdbeResolveLabel(v, addrRowidOk);
100617     if( ipkTop ){
100618       ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
100619       sqlite3VdbeJumpHere(v, ipkTop);
100620     }
100621   }
100622
100623   /* Test all UNIQUE constraints by creating entries for each UNIQUE
100624   ** index and making sure that duplicate entries do not already exist.
100625   ** Compute the revised record entries for indices as we go.
100626   **
100627   ** This loop also handles the case of the PRIMARY KEY index for a
100628   ** WITHOUT ROWID table.
100629   */
100630   for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
100631     int regIdx;          /* Range of registers hold conent for pIdx */
100632     int regR;            /* Range of registers holding conflicting PK */
100633     int iThisCur;        /* Cursor for this UNIQUE index */
100634     int addrUniqueOk;    /* Jump here if the UNIQUE constraint is satisfied */
100635
100636     if( aRegIdx[ix]==0 ) continue;  /* Skip indices that do not change */
100637     if( bAffinityDone==0 ){
100638       sqlite3TableAffinity(v, pTab, regNewData+1);
100639       bAffinityDone = 1;
100640     }
100641     iThisCur = iIdxCur+ix;
100642     addrUniqueOk = sqlite3VdbeMakeLabel(v);
100643
100644     /* Skip partial indices for which the WHERE clause is not true */
100645     if( pIdx->pPartIdxWhere ){
100646       sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
100647       pParse->ckBase = regNewData+1;
100648       sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
100649                          SQLITE_JUMPIFNULL);
100650       pParse->ckBase = 0;
100651     }
100652
100653     /* Create a record for this index entry as it should appear after
100654     ** the insert or update.  Store that record in the aRegIdx[ix] register
100655     */
100656     regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
100657     for(i=0; i<pIdx->nColumn; i++){
100658       int iField = pIdx->aiColumn[i];
100659       int x;
100660       if( iField<0 || iField==pTab->iPKey ){
100661         if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
100662         x = regNewData;
100663         regRowid =  pIdx->pPartIdxWhere ? -1 : regIdx+i;
100664       }else{
100665         x = iField + regNewData + 1;
100666       }
100667       sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
100668       VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
100669     }
100670     sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
100671     VdbeComment((v, "for %s", pIdx->zName));
100672     sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
100673
100674     /* In an UPDATE operation, if this index is the PRIMARY KEY index 
100675     ** of a WITHOUT ROWID table and there has been no change the
100676     ** primary key, then no collision is possible.  The collision detection
100677     ** logic below can all be skipped. */
100678     if( isUpdate && pPk==pIdx && pkChng==0 ){
100679       sqlite3VdbeResolveLabel(v, addrUniqueOk);
100680       continue;
100681     }
100682
100683     /* Find out what action to take in case there is a uniqueness conflict */
100684     onError = pIdx->onError;
100685     if( onError==OE_None ){ 
100686       sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
100687       sqlite3VdbeResolveLabel(v, addrUniqueOk);
100688       continue;  /* pIdx is not a UNIQUE index */
100689     }
100690     if( overrideError!=OE_Default ){
100691       onError = overrideError;
100692     }else if( onError==OE_Default ){
100693       onError = OE_Abort;
100694     }
100695     
100696     /* Check to see if the new index entry will be unique */
100697     sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
100698                          regIdx, pIdx->nKeyCol); VdbeCoverage(v);
100699
100700     /* Generate code to handle collisions */
100701     regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
100702     if( isUpdate || onError==OE_Replace ){
100703       if( HasRowid(pTab) ){
100704         sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
100705         /* Conflict only if the rowid of the existing index entry
100706         ** is different from old-rowid */
100707         if( isUpdate ){
100708           sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
100709           sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
100710           VdbeCoverage(v);
100711         }
100712       }else{
100713         int x;
100714         /* Extract the PRIMARY KEY from the end of the index entry and
100715         ** store it in registers regR..regR+nPk-1 */
100716         if( pIdx!=pPk ){
100717           for(i=0; i<pPk->nKeyCol; i++){
100718             x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
100719             sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
100720             VdbeComment((v, "%s.%s", pTab->zName,
100721                          pTab->aCol[pPk->aiColumn[i]].zName));
100722           }
100723         }
100724         if( isUpdate ){
100725           /* If currently processing the PRIMARY KEY of a WITHOUT ROWID 
100726           ** table, only conflict if the new PRIMARY KEY values are actually
100727           ** different from the old.
100728           **
100729           ** For a UNIQUE index, only conflict if the PRIMARY KEY values
100730           ** of the matched index row are different from the original PRIMARY
100731           ** KEY values of this row before the update.  */
100732           int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
100733           int op = OP_Ne;
100734           int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
100735   
100736           for(i=0; i<pPk->nKeyCol; i++){
100737             char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
100738             x = pPk->aiColumn[i];
100739             if( i==(pPk->nKeyCol-1) ){
100740               addrJump = addrUniqueOk;
100741               op = OP_Eq;
100742             }
100743             sqlite3VdbeAddOp4(v, op, 
100744                 regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
100745             );
100746             sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
100747             VdbeCoverageIf(v, op==OP_Eq);
100748             VdbeCoverageIf(v, op==OP_Ne);
100749           }
100750         }
100751       }
100752     }
100753
100754     /* Generate code that executes if the new index entry is not unique */
100755     assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
100756         || onError==OE_Ignore || onError==OE_Replace );
100757     switch( onError ){
100758       case OE_Rollback:
100759       case OE_Abort:
100760       case OE_Fail: {
100761         sqlite3UniqueConstraint(pParse, onError, pIdx);
100762         break;
100763       }
100764       case OE_Ignore: {
100765         sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
100766         break;
100767       }
100768       default: {
100769         Trigger *pTrigger = 0;
100770         assert( onError==OE_Replace );
100771         sqlite3MultiWrite(pParse);
100772         if( db->flags&SQLITE_RecTriggers ){
100773           pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
100774         }
100775         sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
100776                                  regR, nPkField, 0, OE_Replace, pIdx==pPk);
100777         seenReplace = 1;
100778         break;
100779       }
100780     }
100781     sqlite3VdbeResolveLabel(v, addrUniqueOk);
100782     sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
100783     if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
100784   }
100785   if( ipkTop ){
100786     sqlite3VdbeAddOp2(v, OP_Goto, 0, ipkTop+1);
100787     sqlite3VdbeJumpHere(v, ipkBottom);
100788   }
100789   
100790   *pbMayReplace = seenReplace;
100791   VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
100792 }
100793
100794 /*
100795 ** This routine generates code to finish the INSERT or UPDATE operation
100796 ** that was started by a prior call to sqlite3GenerateConstraintChecks.
100797 ** A consecutive range of registers starting at regNewData contains the
100798 ** rowid and the content to be inserted.
100799 **
100800 ** The arguments to this routine should be the same as the first six
100801 ** arguments to sqlite3GenerateConstraintChecks.
100802 */
100803 SQLITE_PRIVATE void sqlite3CompleteInsertion(
100804   Parse *pParse,      /* The parser context */
100805   Table *pTab,        /* the table into which we are inserting */
100806   int iDataCur,       /* Cursor of the canonical data source */
100807   int iIdxCur,        /* First index cursor */
100808   int regNewData,     /* Range of content */
100809   int *aRegIdx,       /* Register used by each index.  0 for unused indices */
100810   int isUpdate,       /* True for UPDATE, False for INSERT */
100811   int appendBias,     /* True if this is likely to be an append */
100812   int useSeekResult   /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
100813 ){
100814   Vdbe *v;            /* Prepared statements under construction */
100815   Index *pIdx;        /* An index being inserted or updated */
100816   u8 pik_flags;       /* flag values passed to the btree insert */
100817   int regData;        /* Content registers (after the rowid) */
100818   int regRec;         /* Register holding assembled record for the table */
100819   int i;              /* Loop counter */
100820   u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
100821
100822   v = sqlite3GetVdbe(pParse);
100823   assert( v!=0 );
100824   assert( pTab->pSelect==0 );  /* This table is not a VIEW */
100825   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
100826     if( aRegIdx[i]==0 ) continue;
100827     bAffinityDone = 1;
100828     if( pIdx->pPartIdxWhere ){
100829       sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
100830       VdbeCoverage(v);
100831     }
100832     sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
100833     pik_flags = 0;
100834     if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
100835     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
100836       assert( pParse->nested==0 );
100837       pik_flags |= OPFLAG_NCHANGE;
100838     }
100839     if( pik_flags )  sqlite3VdbeChangeP5(v, pik_flags);
100840   }
100841   if( !HasRowid(pTab) ) return;
100842   regData = regNewData + 1;
100843   regRec = sqlite3GetTempReg(pParse);
100844   sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
100845   if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
100846   sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
100847   if( pParse->nested ){
100848     pik_flags = 0;
100849   }else{
100850     pik_flags = OPFLAG_NCHANGE;
100851     pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
100852   }
100853   if( appendBias ){
100854     pik_flags |= OPFLAG_APPEND;
100855   }
100856   if( useSeekResult ){
100857     pik_flags |= OPFLAG_USESEEKRESULT;
100858   }
100859   sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
100860   if( !pParse->nested ){
100861     sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
100862   }
100863   sqlite3VdbeChangeP5(v, pik_flags);
100864 }
100865
100866 /*
100867 ** Allocate cursors for the pTab table and all its indices and generate
100868 ** code to open and initialized those cursors.
100869 **
100870 ** The cursor for the object that contains the complete data (normally
100871 ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
100872 ** ROWID table) is returned in *piDataCur.  The first index cursor is
100873 ** returned in *piIdxCur.  The number of indices is returned.
100874 **
100875 ** Use iBase as the first cursor (either the *piDataCur for rowid tables
100876 ** or the first index for WITHOUT ROWID tables) if it is non-negative.
100877 ** If iBase is negative, then allocate the next available cursor.
100878 **
100879 ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
100880 ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
100881 ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
100882 ** pTab->pIndex list.
100883 **
100884 ** If pTab is a virtual table, then this routine is a no-op and the
100885 ** *piDataCur and *piIdxCur values are left uninitialized.
100886 */
100887 SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
100888   Parse *pParse,   /* Parsing context */
100889   Table *pTab,     /* Table to be opened */
100890   int op,          /* OP_OpenRead or OP_OpenWrite */
100891   int iBase,       /* Use this for the table cursor, if there is one */
100892   u8 *aToOpen,     /* If not NULL: boolean for each table and index */
100893   int *piDataCur,  /* Write the database source cursor number here */
100894   int *piIdxCur    /* Write the first index cursor number here */
100895 ){
100896   int i;
100897   int iDb;
100898   int iDataCur;
100899   Index *pIdx;
100900   Vdbe *v;
100901
100902   assert( op==OP_OpenRead || op==OP_OpenWrite );
100903   if( IsVirtual(pTab) ){
100904     /* This routine is a no-op for virtual tables. Leave the output
100905     ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
100906     ** can detect if they are used by mistake in the caller. */
100907     return 0;
100908   }
100909   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
100910   v = sqlite3GetVdbe(pParse);
100911   assert( v!=0 );
100912   if( iBase<0 ) iBase = pParse->nTab;
100913   iDataCur = iBase++;
100914   if( piDataCur ) *piDataCur = iDataCur;
100915   if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
100916     sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
100917   }else{
100918     sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
100919   }
100920   if( piIdxCur ) *piIdxCur = iBase;
100921   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
100922     int iIdxCur = iBase++;
100923     assert( pIdx->pSchema==pTab->pSchema );
100924     if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) && piDataCur ){
100925       *piDataCur = iIdxCur;
100926     }
100927     if( aToOpen==0 || aToOpen[i+1] ){
100928       sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
100929       sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
100930       VdbeComment((v, "%s", pIdx->zName));
100931     }
100932   }
100933   if( iBase>pParse->nTab ) pParse->nTab = iBase;
100934   return i;
100935 }
100936
100937
100938 #ifdef SQLITE_TEST
100939 /*
100940 ** The following global variable is incremented whenever the
100941 ** transfer optimization is used.  This is used for testing
100942 ** purposes only - to make sure the transfer optimization really
100943 ** is happening when it is supposed to.
100944 */
100945 SQLITE_API int sqlite3_xferopt_count;
100946 #endif /* SQLITE_TEST */
100947
100948
100949 #ifndef SQLITE_OMIT_XFER_OPT
100950 /*
100951 ** Check to collation names to see if they are compatible.
100952 */
100953 static int xferCompatibleCollation(const char *z1, const char *z2){
100954   if( z1==0 ){
100955     return z2==0;
100956   }
100957   if( z2==0 ){
100958     return 0;
100959   }
100960   return sqlite3StrICmp(z1, z2)==0;
100961 }
100962
100963
100964 /*
100965 ** Check to see if index pSrc is compatible as a source of data
100966 ** for index pDest in an insert transfer optimization.  The rules
100967 ** for a compatible index:
100968 **
100969 **    *   The index is over the same set of columns
100970 **    *   The same DESC and ASC markings occurs on all columns
100971 **    *   The same onError processing (OE_Abort, OE_Ignore, etc)
100972 **    *   The same collating sequence on each column
100973 **    *   The index has the exact same WHERE clause
100974 */
100975 static int xferCompatibleIndex(Index *pDest, Index *pSrc){
100976   int i;
100977   assert( pDest && pSrc );
100978   assert( pDest->pTable!=pSrc->pTable );
100979   if( pDest->nKeyCol!=pSrc->nKeyCol ){
100980     return 0;   /* Different number of columns */
100981   }
100982   if( pDest->onError!=pSrc->onError ){
100983     return 0;   /* Different conflict resolution strategies */
100984   }
100985   for(i=0; i<pSrc->nKeyCol; i++){
100986     if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
100987       return 0;   /* Different columns indexed */
100988     }
100989     if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
100990       return 0;   /* Different sort orders */
100991     }
100992     if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
100993       return 0;   /* Different collating sequences */
100994     }
100995   }
100996   if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
100997     return 0;     /* Different WHERE clauses */
100998   }
100999
101000   /* If no test above fails then the indices must be compatible */
101001   return 1;
101002 }
101003
101004 /*
101005 ** Attempt the transfer optimization on INSERTs of the form
101006 **
101007 **     INSERT INTO tab1 SELECT * FROM tab2;
101008 **
101009 ** The xfer optimization transfers raw records from tab2 over to tab1.  
101010 ** Columns are not decoded and reassembled, which greatly improves
101011 ** performance.  Raw index records are transferred in the same way.
101012 **
101013 ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
101014 ** There are lots of rules for determining compatibility - see comments
101015 ** embedded in the code for details.
101016 **
101017 ** This routine returns TRUE if the optimization is guaranteed to be used.
101018 ** Sometimes the xfer optimization will only work if the destination table
101019 ** is empty - a factor that can only be determined at run-time.  In that
101020 ** case, this routine generates code for the xfer optimization but also
101021 ** does a test to see if the destination table is empty and jumps over the
101022 ** xfer optimization code if the test fails.  In that case, this routine
101023 ** returns FALSE so that the caller will know to go ahead and generate
101024 ** an unoptimized transfer.  This routine also returns FALSE if there
101025 ** is no chance that the xfer optimization can be applied.
101026 **
101027 ** This optimization is particularly useful at making VACUUM run faster.
101028 */
101029 static int xferOptimization(
101030   Parse *pParse,        /* Parser context */
101031   Table *pDest,         /* The table we are inserting into */
101032   Select *pSelect,      /* A SELECT statement to use as the data source */
101033   int onError,          /* How to handle constraint errors */
101034   int iDbDest           /* The database of pDest */
101035 ){
101036   ExprList *pEList;                /* The result set of the SELECT */
101037   Table *pSrc;                     /* The table in the FROM clause of SELECT */
101038   Index *pSrcIdx, *pDestIdx;       /* Source and destination indices */
101039   struct SrcList_item *pItem;      /* An element of pSelect->pSrc */
101040   int i;                           /* Loop counter */
101041   int iDbSrc;                      /* The database of pSrc */
101042   int iSrc, iDest;                 /* Cursors from source and destination */
101043   int addr1, addr2;                /* Loop addresses */
101044   int emptyDestTest = 0;           /* Address of test for empty pDest */
101045   int emptySrcTest = 0;            /* Address of test for empty pSrc */
101046   Vdbe *v;                         /* The VDBE we are building */
101047   int regAutoinc;                  /* Memory register used by AUTOINC */
101048   int destHasUniqueIdx = 0;        /* True if pDest has a UNIQUE index */
101049   int regData, regRowid;           /* Registers holding data and rowid */
101050
101051   if( pSelect==0 ){
101052     return 0;   /* Must be of the form  INSERT INTO ... SELECT ... */
101053   }
101054   if( pParse->pWith || pSelect->pWith ){
101055     /* Do not attempt to process this query if there are an WITH clauses
101056     ** attached to it. Proceeding may generate a false "no such table: xxx"
101057     ** error if pSelect reads from a CTE named "xxx".  */
101058     return 0;
101059   }
101060   if( sqlite3TriggerList(pParse, pDest) ){
101061     return 0;   /* tab1 must not have triggers */
101062   }
101063 #ifndef SQLITE_OMIT_VIRTUALTABLE
101064   if( pDest->tabFlags & TF_Virtual ){
101065     return 0;   /* tab1 must not be a virtual table */
101066   }
101067 #endif
101068   if( onError==OE_Default ){
101069     if( pDest->iPKey>=0 ) onError = pDest->keyConf;
101070     if( onError==OE_Default ) onError = OE_Abort;
101071   }
101072   assert(pSelect->pSrc);   /* allocated even if there is no FROM clause */
101073   if( pSelect->pSrc->nSrc!=1 ){
101074     return 0;   /* FROM clause must have exactly one term */
101075   }
101076   if( pSelect->pSrc->a[0].pSelect ){
101077     return 0;   /* FROM clause cannot contain a subquery */
101078   }
101079   if( pSelect->pWhere ){
101080     return 0;   /* SELECT may not have a WHERE clause */
101081   }
101082   if( pSelect->pOrderBy ){
101083     return 0;   /* SELECT may not have an ORDER BY clause */
101084   }
101085   /* Do not need to test for a HAVING clause.  If HAVING is present but
101086   ** there is no ORDER BY, we will get an error. */
101087   if( pSelect->pGroupBy ){
101088     return 0;   /* SELECT may not have a GROUP BY clause */
101089   }
101090   if( pSelect->pLimit ){
101091     return 0;   /* SELECT may not have a LIMIT clause */
101092   }
101093   assert( pSelect->pOffset==0 );  /* Must be so if pLimit==0 */
101094   if( pSelect->pPrior ){
101095     return 0;   /* SELECT may not be a compound query */
101096   }
101097   if( pSelect->selFlags & SF_Distinct ){
101098     return 0;   /* SELECT may not be DISTINCT */
101099   }
101100   pEList = pSelect->pEList;
101101   assert( pEList!=0 );
101102   if( pEList->nExpr!=1 ){
101103     return 0;   /* The result set must have exactly one column */
101104   }
101105   assert( pEList->a[0].pExpr );
101106   if( pEList->a[0].pExpr->op!=TK_ALL ){
101107     return 0;   /* The result set must be the special operator "*" */
101108   }
101109
101110   /* At this point we have established that the statement is of the
101111   ** correct syntactic form to participate in this optimization.  Now
101112   ** we have to check the semantics.
101113   */
101114   pItem = pSelect->pSrc->a;
101115   pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
101116   if( pSrc==0 ){
101117     return 0;   /* FROM clause does not contain a real table */
101118   }
101119   if( pSrc==pDest ){
101120     return 0;   /* tab1 and tab2 may not be the same table */
101121   }
101122   if( HasRowid(pDest)!=HasRowid(pSrc) ){
101123     return 0;   /* source and destination must both be WITHOUT ROWID or not */
101124   }
101125 #ifndef SQLITE_OMIT_VIRTUALTABLE
101126   if( pSrc->tabFlags & TF_Virtual ){
101127     return 0;   /* tab2 must not be a virtual table */
101128   }
101129 #endif
101130   if( pSrc->pSelect ){
101131     return 0;   /* tab2 may not be a view */
101132   }
101133   if( pDest->nCol!=pSrc->nCol ){
101134     return 0;   /* Number of columns must be the same in tab1 and tab2 */
101135   }
101136   if( pDest->iPKey!=pSrc->iPKey ){
101137     return 0;   /* Both tables must have the same INTEGER PRIMARY KEY */
101138   }
101139   for(i=0; i<pDest->nCol; i++){
101140     Column *pDestCol = &pDest->aCol[i];
101141     Column *pSrcCol = &pSrc->aCol[i];
101142     if( pDestCol->affinity!=pSrcCol->affinity ){
101143       return 0;    /* Affinity must be the same on all columns */
101144     }
101145     if( !xferCompatibleCollation(pDestCol->zColl, pSrcCol->zColl) ){
101146       return 0;    /* Collating sequence must be the same on all columns */
101147     }
101148     if( pDestCol->notNull && !pSrcCol->notNull ){
101149       return 0;    /* tab2 must be NOT NULL if tab1 is */
101150     }
101151     /* Default values for second and subsequent columns need to match. */
101152     if( i>0
101153      && ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0) 
101154          || (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0))
101155     ){
101156       return 0;    /* Default values must be the same for all columns */
101157     }
101158   }
101159   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
101160     if( IsUniqueIndex(pDestIdx) ){
101161       destHasUniqueIdx = 1;
101162     }
101163     for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
101164       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
101165     }
101166     if( pSrcIdx==0 ){
101167       return 0;    /* pDestIdx has no corresponding index in pSrc */
101168     }
101169   }
101170 #ifndef SQLITE_OMIT_CHECK
101171   if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
101172     return 0;   /* Tables have different CHECK constraints.  Ticket #2252 */
101173   }
101174 #endif
101175 #ifndef SQLITE_OMIT_FOREIGN_KEY
101176   /* Disallow the transfer optimization if the destination table constains
101177   ** any foreign key constraints.  This is more restrictive than necessary.
101178   ** But the main beneficiary of the transfer optimization is the VACUUM 
101179   ** command, and the VACUUM command disables foreign key constraints.  So
101180   ** the extra complication to make this rule less restrictive is probably
101181   ** not worth the effort.  Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
101182   */
101183   if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
101184     return 0;
101185   }
101186 #endif
101187   if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
101188     return 0;  /* xfer opt does not play well with PRAGMA count_changes */
101189   }
101190
101191   /* If we get this far, it means that the xfer optimization is at
101192   ** least a possibility, though it might only work if the destination
101193   ** table (tab1) is initially empty.
101194   */
101195 #ifdef SQLITE_TEST
101196   sqlite3_xferopt_count++;
101197 #endif
101198   iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
101199   v = sqlite3GetVdbe(pParse);
101200   sqlite3CodeVerifySchema(pParse, iDbSrc);
101201   iSrc = pParse->nTab++;
101202   iDest = pParse->nTab++;
101203   regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
101204   regData = sqlite3GetTempReg(pParse);
101205   regRowid = sqlite3GetTempReg(pParse);
101206   sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
101207   assert( HasRowid(pDest) || destHasUniqueIdx );
101208   if( (pDest->iPKey<0 && pDest->pIndex!=0)          /* (1) */
101209    || destHasUniqueIdx                              /* (2) */
101210    || (onError!=OE_Abort && onError!=OE_Rollback)   /* (3) */
101211   ){
101212     /* In some circumstances, we are able to run the xfer optimization
101213     ** only if the destination table is initially empty.  This code makes
101214     ** that determination.  Conditions under which the destination must
101215     ** be empty:
101216     **
101217     ** (1) There is no INTEGER PRIMARY KEY but there are indices.
101218     **     (If the destination is not initially empty, the rowid fields
101219     **     of index entries might need to change.)
101220     **
101221     ** (2) The destination has a unique index.  (The xfer optimization 
101222     **     is unable to test uniqueness.)
101223     **
101224     ** (3) onError is something other than OE_Abort and OE_Rollback.
101225     */
101226     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
101227     emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
101228     sqlite3VdbeJumpHere(v, addr1);
101229   }
101230   if( HasRowid(pSrc) ){
101231     sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
101232     emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
101233     if( pDest->iPKey>=0 ){
101234       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
101235       addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
101236       VdbeCoverage(v);
101237       sqlite3RowidConstraint(pParse, onError, pDest);
101238       sqlite3VdbeJumpHere(v, addr2);
101239       autoIncStep(pParse, regAutoinc, regRowid);
101240     }else if( pDest->pIndex==0 ){
101241       addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
101242     }else{
101243       addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
101244       assert( (pDest->tabFlags & TF_Autoincrement)==0 );
101245     }
101246     sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
101247     sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
101248     sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
101249     sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
101250     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
101251     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
101252     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
101253   }else{
101254     sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
101255     sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
101256   }
101257   for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
101258     for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
101259       if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
101260     }
101261     assert( pSrcIdx );
101262     sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
101263     sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
101264     VdbeComment((v, "%s", pSrcIdx->zName));
101265     sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
101266     sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
101267     sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
101268     VdbeComment((v, "%s", pDestIdx->zName));
101269     addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
101270     sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
101271     sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
101272     sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
101273     sqlite3VdbeJumpHere(v, addr1);
101274     sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
101275     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
101276   }
101277   if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
101278   sqlite3ReleaseTempReg(pParse, regRowid);
101279   sqlite3ReleaseTempReg(pParse, regData);
101280   if( emptyDestTest ){
101281     sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
101282     sqlite3VdbeJumpHere(v, emptyDestTest);
101283     sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
101284     return 0;
101285   }else{
101286     return 1;
101287   }
101288 }
101289 #endif /* SQLITE_OMIT_XFER_OPT */
101290
101291 /************** End of insert.c **********************************************/
101292 /************** Begin file legacy.c ******************************************/
101293 /*
101294 ** 2001 September 15
101295 **
101296 ** The author disclaims copyright to this source code.  In place of
101297 ** a legal notice, here is a blessing:
101298 **
101299 **    May you do good and not evil.
101300 **    May you find forgiveness for yourself and forgive others.
101301 **    May you share freely, never taking more than you give.
101302 **
101303 *************************************************************************
101304 ** Main file for the SQLite library.  The routines in this file
101305 ** implement the programmer interface to the library.  Routines in
101306 ** other files are for internal use by SQLite and should not be
101307 ** accessed by users of the library.
101308 */
101309
101310
101311 /*
101312 ** Execute SQL code.  Return one of the SQLITE_ success/failure
101313 ** codes.  Also write an error message into memory obtained from
101314 ** malloc() and make *pzErrMsg point to that message.
101315 **
101316 ** If the SQL is a query, then for each row in the query result
101317 ** the xCallback() function is called.  pArg becomes the first
101318 ** argument to xCallback().  If xCallback=NULL then no callback
101319 ** is invoked, even for queries.
101320 */
101321 SQLITE_API int SQLITE_STDCALL sqlite3_exec(
101322   sqlite3 *db,                /* The database on which the SQL executes */
101323   const char *zSql,           /* The SQL to be executed */
101324   sqlite3_callback xCallback, /* Invoke this callback routine */
101325   void *pArg,                 /* First argument to xCallback() */
101326   char **pzErrMsg             /* Write error messages here */
101327 ){
101328   int rc = SQLITE_OK;         /* Return code */
101329   const char *zLeftover;      /* Tail of unprocessed SQL */
101330   sqlite3_stmt *pStmt = 0;    /* The current SQL statement */
101331   char **azCols = 0;          /* Names of result columns */
101332   int callbackIsInit;         /* True if callback data is initialized */
101333
101334   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
101335   if( zSql==0 ) zSql = "";
101336
101337   sqlite3_mutex_enter(db->mutex);
101338   sqlite3Error(db, SQLITE_OK);
101339   while( rc==SQLITE_OK && zSql[0] ){
101340     int nCol;
101341     char **azVals = 0;
101342
101343     pStmt = 0;
101344     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
101345     assert( rc==SQLITE_OK || pStmt==0 );
101346     if( rc!=SQLITE_OK ){
101347       continue;
101348     }
101349     if( !pStmt ){
101350       /* this happens for a comment or white-space */
101351       zSql = zLeftover;
101352       continue;
101353     }
101354
101355     callbackIsInit = 0;
101356     nCol = sqlite3_column_count(pStmt);
101357
101358     while( 1 ){
101359       int i;
101360       rc = sqlite3_step(pStmt);
101361
101362       /* Invoke the callback function if required */
101363       if( xCallback && (SQLITE_ROW==rc || 
101364           (SQLITE_DONE==rc && !callbackIsInit
101365                            && db->flags&SQLITE_NullCallback)) ){
101366         if( !callbackIsInit ){
101367           azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
101368           if( azCols==0 ){
101369             goto exec_out;
101370           }
101371           for(i=0; i<nCol; i++){
101372             azCols[i] = (char *)sqlite3_column_name(pStmt, i);
101373             /* sqlite3VdbeSetColName() installs column names as UTF8
101374             ** strings so there is no way for sqlite3_column_name() to fail. */
101375             assert( azCols[i]!=0 );
101376           }
101377           callbackIsInit = 1;
101378         }
101379         if( rc==SQLITE_ROW ){
101380           azVals = &azCols[nCol];
101381           for(i=0; i<nCol; i++){
101382             azVals[i] = (char *)sqlite3_column_text(pStmt, i);
101383             if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
101384               db->mallocFailed = 1;
101385               goto exec_out;
101386             }
101387           }
101388         }
101389         if( xCallback(pArg, nCol, azVals, azCols) ){
101390           /* EVIDENCE-OF: R-38229-40159 If the callback function to
101391           ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
101392           ** return SQLITE_ABORT. */
101393           rc = SQLITE_ABORT;
101394           sqlite3VdbeFinalize((Vdbe *)pStmt);
101395           pStmt = 0;
101396           sqlite3Error(db, SQLITE_ABORT);
101397           goto exec_out;
101398         }
101399       }
101400
101401       if( rc!=SQLITE_ROW ){
101402         rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
101403         pStmt = 0;
101404         zSql = zLeftover;
101405         while( sqlite3Isspace(zSql[0]) ) zSql++;
101406         break;
101407       }
101408     }
101409
101410     sqlite3DbFree(db, azCols);
101411     azCols = 0;
101412   }
101413
101414 exec_out:
101415   if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
101416   sqlite3DbFree(db, azCols);
101417
101418   rc = sqlite3ApiExit(db, rc);
101419   if( rc!=SQLITE_OK && pzErrMsg ){
101420     int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
101421     *pzErrMsg = sqlite3Malloc(nErrMsg);
101422     if( *pzErrMsg ){
101423       memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
101424     }else{
101425       rc = SQLITE_NOMEM;
101426       sqlite3Error(db, SQLITE_NOMEM);
101427     }
101428   }else if( pzErrMsg ){
101429     *pzErrMsg = 0;
101430   }
101431
101432   assert( (rc&db->errMask)==rc );
101433   sqlite3_mutex_leave(db->mutex);
101434   return rc;
101435 }
101436
101437 /************** End of legacy.c **********************************************/
101438 /************** Begin file loadext.c *****************************************/
101439 /*
101440 ** 2006 June 7
101441 **
101442 ** The author disclaims copyright to this source code.  In place of
101443 ** a legal notice, here is a blessing:
101444 **
101445 **    May you do good and not evil.
101446 **    May you find forgiveness for yourself and forgive others.
101447 **    May you share freely, never taking more than you give.
101448 **
101449 *************************************************************************
101450 ** This file contains code used to dynamically load extensions into
101451 ** the SQLite library.
101452 */
101453
101454 #ifndef SQLITE_CORE
101455   #define SQLITE_CORE 1  /* Disable the API redefinition in sqlite3ext.h */
101456 #endif
101457 /************** Include sqlite3ext.h in the middle of loadext.c **************/
101458 /************** Begin file sqlite3ext.h **************************************/
101459 /*
101460 ** 2006 June 7
101461 **
101462 ** The author disclaims copyright to this source code.  In place of
101463 ** a legal notice, here is a blessing:
101464 **
101465 **    May you do good and not evil.
101466 **    May you find forgiveness for yourself and forgive others.
101467 **    May you share freely, never taking more than you give.
101468 **
101469 *************************************************************************
101470 ** This header file defines the SQLite interface for use by
101471 ** shared libraries that want to be imported as extensions into
101472 ** an SQLite instance.  Shared libraries that intend to be loaded
101473 ** as extensions by SQLite should #include this file instead of 
101474 ** sqlite3.h.
101475 */
101476 #ifndef _SQLITE3EXT_H_
101477 #define _SQLITE3EXT_H_
101478
101479 typedef struct sqlite3_api_routines sqlite3_api_routines;
101480
101481 /*
101482 ** The following structure holds pointers to all of the SQLite API
101483 ** routines.
101484 **
101485 ** WARNING:  In order to maintain backwards compatibility, add new
101486 ** interfaces to the end of this structure only.  If you insert new
101487 ** interfaces in the middle of this structure, then older different
101488 ** versions of SQLite will not be able to load each other's shared
101489 ** libraries!
101490 */
101491 struct sqlite3_api_routines {
101492   void * (*aggregate_context)(sqlite3_context*,int nBytes);
101493   int  (*aggregate_count)(sqlite3_context*);
101494   int  (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
101495   int  (*bind_double)(sqlite3_stmt*,int,double);
101496   int  (*bind_int)(sqlite3_stmt*,int,int);
101497   int  (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
101498   int  (*bind_null)(sqlite3_stmt*,int);
101499   int  (*bind_parameter_count)(sqlite3_stmt*);
101500   int  (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
101501   const char * (*bind_parameter_name)(sqlite3_stmt*,int);
101502   int  (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
101503   int  (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
101504   int  (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
101505   int  (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
101506   int  (*busy_timeout)(sqlite3*,int ms);
101507   int  (*changes)(sqlite3*);
101508   int  (*close)(sqlite3*);
101509   int  (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
101510                            int eTextRep,const char*));
101511   int  (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
101512                              int eTextRep,const void*));
101513   const void * (*column_blob)(sqlite3_stmt*,int iCol);
101514   int  (*column_bytes)(sqlite3_stmt*,int iCol);
101515   int  (*column_bytes16)(sqlite3_stmt*,int iCol);
101516   int  (*column_count)(sqlite3_stmt*pStmt);
101517   const char * (*column_database_name)(sqlite3_stmt*,int);
101518   const void * (*column_database_name16)(sqlite3_stmt*,int);
101519   const char * (*column_decltype)(sqlite3_stmt*,int i);
101520   const void * (*column_decltype16)(sqlite3_stmt*,int);
101521   double  (*column_double)(sqlite3_stmt*,int iCol);
101522   int  (*column_int)(sqlite3_stmt*,int iCol);
101523   sqlite_int64  (*column_int64)(sqlite3_stmt*,int iCol);
101524   const char * (*column_name)(sqlite3_stmt*,int);
101525   const void * (*column_name16)(sqlite3_stmt*,int);
101526   const char * (*column_origin_name)(sqlite3_stmt*,int);
101527   const void * (*column_origin_name16)(sqlite3_stmt*,int);
101528   const char * (*column_table_name)(sqlite3_stmt*,int);
101529   const void * (*column_table_name16)(sqlite3_stmt*,int);
101530   const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
101531   const void * (*column_text16)(sqlite3_stmt*,int iCol);
101532   int  (*column_type)(sqlite3_stmt*,int iCol);
101533   sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
101534   void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
101535   int  (*complete)(const char*sql);
101536   int  (*complete16)(const void*sql);
101537   int  (*create_collation)(sqlite3*,const char*,int,void*,
101538                            int(*)(void*,int,const void*,int,const void*));
101539   int  (*create_collation16)(sqlite3*,const void*,int,void*,
101540                              int(*)(void*,int,const void*,int,const void*));
101541   int  (*create_function)(sqlite3*,const char*,int,int,void*,
101542                           void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
101543                           void (*xStep)(sqlite3_context*,int,sqlite3_value**),
101544                           void (*xFinal)(sqlite3_context*));
101545   int  (*create_function16)(sqlite3*,const void*,int,int,void*,
101546                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
101547                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
101548                             void (*xFinal)(sqlite3_context*));
101549   int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
101550   int  (*data_count)(sqlite3_stmt*pStmt);
101551   sqlite3 * (*db_handle)(sqlite3_stmt*);
101552   int (*declare_vtab)(sqlite3*,const char*);
101553   int  (*enable_shared_cache)(int);
101554   int  (*errcode)(sqlite3*db);
101555   const char * (*errmsg)(sqlite3*);
101556   const void * (*errmsg16)(sqlite3*);
101557   int  (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
101558   int  (*expired)(sqlite3_stmt*);
101559   int  (*finalize)(sqlite3_stmt*pStmt);
101560   void  (*free)(void*);
101561   void  (*free_table)(char**result);
101562   int  (*get_autocommit)(sqlite3*);
101563   void * (*get_auxdata)(sqlite3_context*,int);
101564   int  (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
101565   int  (*global_recover)(void);
101566   void  (*interruptx)(sqlite3*);
101567   sqlite_int64  (*last_insert_rowid)(sqlite3*);
101568   const char * (*libversion)(void);
101569   int  (*libversion_number)(void);
101570   void *(*malloc)(int);
101571   char * (*mprintf)(const char*,...);
101572   int  (*open)(const char*,sqlite3**);
101573   int  (*open16)(const void*,sqlite3**);
101574   int  (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
101575   int  (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
101576   void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
101577   void  (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
101578   void *(*realloc)(void*,int);
101579   int  (*reset)(sqlite3_stmt*pStmt);
101580   void  (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
101581   void  (*result_double)(sqlite3_context*,double);
101582   void  (*result_error)(sqlite3_context*,const char*,int);
101583   void  (*result_error16)(sqlite3_context*,const void*,int);
101584   void  (*result_int)(sqlite3_context*,int);
101585   void  (*result_int64)(sqlite3_context*,sqlite_int64);
101586   void  (*result_null)(sqlite3_context*);
101587   void  (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
101588   void  (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
101589   void  (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
101590   void  (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
101591   void  (*result_value)(sqlite3_context*,sqlite3_value*);
101592   void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
101593   int  (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
101594                          const char*,const char*),void*);
101595   void  (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
101596   char * (*snprintf)(int,char*,const char*,...);
101597   int  (*step)(sqlite3_stmt*);
101598   int  (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
101599                                 char const**,char const**,int*,int*,int*);
101600   void  (*thread_cleanup)(void);
101601   int  (*total_changes)(sqlite3*);
101602   void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
101603   int  (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
101604   void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
101605                                          sqlite_int64),void*);
101606   void * (*user_data)(sqlite3_context*);
101607   const void * (*value_blob)(sqlite3_value*);
101608   int  (*value_bytes)(sqlite3_value*);
101609   int  (*value_bytes16)(sqlite3_value*);
101610   double  (*value_double)(sqlite3_value*);
101611   int  (*value_int)(sqlite3_value*);
101612   sqlite_int64  (*value_int64)(sqlite3_value*);
101613   int  (*value_numeric_type)(sqlite3_value*);
101614   const unsigned char * (*value_text)(sqlite3_value*);
101615   const void * (*value_text16)(sqlite3_value*);
101616   const void * (*value_text16be)(sqlite3_value*);
101617   const void * (*value_text16le)(sqlite3_value*);
101618   int  (*value_type)(sqlite3_value*);
101619   char *(*vmprintf)(const char*,va_list);
101620   /* Added ??? */
101621   int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
101622   /* Added by 3.3.13 */
101623   int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
101624   int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
101625   int (*clear_bindings)(sqlite3_stmt*);
101626   /* Added by 3.4.1 */
101627   int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
101628                           void (*xDestroy)(void *));
101629   /* Added by 3.5.0 */
101630   int (*bind_zeroblob)(sqlite3_stmt*,int,int);
101631   int (*blob_bytes)(sqlite3_blob*);
101632   int (*blob_close)(sqlite3_blob*);
101633   int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
101634                    int,sqlite3_blob**);
101635   int (*blob_read)(sqlite3_blob*,void*,int,int);
101636   int (*blob_write)(sqlite3_blob*,const void*,int,int);
101637   int (*create_collation_v2)(sqlite3*,const char*,int,void*,
101638                              int(*)(void*,int,const void*,int,const void*),
101639                              void(*)(void*));
101640   int (*file_control)(sqlite3*,const char*,int,void*);
101641   sqlite3_int64 (*memory_highwater)(int);
101642   sqlite3_int64 (*memory_used)(void);
101643   sqlite3_mutex *(*mutex_alloc)(int);
101644   void (*mutex_enter)(sqlite3_mutex*);
101645   void (*mutex_free)(sqlite3_mutex*);
101646   void (*mutex_leave)(sqlite3_mutex*);
101647   int (*mutex_try)(sqlite3_mutex*);
101648   int (*open_v2)(const char*,sqlite3**,int,const char*);
101649   int (*release_memory)(int);
101650   void (*result_error_nomem)(sqlite3_context*);
101651   void (*result_error_toobig)(sqlite3_context*);
101652   int (*sleep)(int);
101653   void (*soft_heap_limit)(int);
101654   sqlite3_vfs *(*vfs_find)(const char*);
101655   int (*vfs_register)(sqlite3_vfs*,int);
101656   int (*vfs_unregister)(sqlite3_vfs*);
101657   int (*xthreadsafe)(void);
101658   void (*result_zeroblob)(sqlite3_context*,int);
101659   void (*result_error_code)(sqlite3_context*,int);
101660   int (*test_control)(int, ...);
101661   void (*randomness)(int,void*);
101662   sqlite3 *(*context_db_handle)(sqlite3_context*);
101663   int (*extended_result_codes)(sqlite3*,int);
101664   int (*limit)(sqlite3*,int,int);
101665   sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
101666   const char *(*sql)(sqlite3_stmt*);
101667   int (*status)(int,int*,int*,int);
101668   int (*backup_finish)(sqlite3_backup*);
101669   sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
101670   int (*backup_pagecount)(sqlite3_backup*);
101671   int (*backup_remaining)(sqlite3_backup*);
101672   int (*backup_step)(sqlite3_backup*,int);
101673   const char *(*compileoption_get)(int);
101674   int (*compileoption_used)(const char*);
101675   int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
101676                             void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
101677                             void (*xStep)(sqlite3_context*,int,sqlite3_value**),
101678                             void (*xFinal)(sqlite3_context*),
101679                             void(*xDestroy)(void*));
101680   int (*db_config)(sqlite3*,int,...);
101681   sqlite3_mutex *(*db_mutex)(sqlite3*);
101682   int (*db_status)(sqlite3*,int,int*,int*,int);
101683   int (*extended_errcode)(sqlite3*);
101684   void (*log)(int,const char*,...);
101685   sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
101686   const char *(*sourceid)(void);
101687   int (*stmt_status)(sqlite3_stmt*,int,int);
101688   int (*strnicmp)(const char*,const char*,int);
101689   int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
101690   int (*wal_autocheckpoint)(sqlite3*,int);
101691   int (*wal_checkpoint)(sqlite3*,const char*);
101692   void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
101693   int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
101694   int (*vtab_config)(sqlite3*,int op,...);
101695   int (*vtab_on_conflict)(sqlite3*);
101696   /* Version 3.7.16 and later */
101697   int (*close_v2)(sqlite3*);
101698   const char *(*db_filename)(sqlite3*,const char*);
101699   int (*db_readonly)(sqlite3*,const char*);
101700   int (*db_release_memory)(sqlite3*);
101701   const char *(*errstr)(int);
101702   int (*stmt_busy)(sqlite3_stmt*);
101703   int (*stmt_readonly)(sqlite3_stmt*);
101704   int (*stricmp)(const char*,const char*);
101705   int (*uri_boolean)(const char*,const char*,int);
101706   sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
101707   const char *(*uri_parameter)(const char*,const char*);
101708   char *(*vsnprintf)(int,char*,const char*,va_list);
101709   int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
101710   /* Version 3.8.7 and later */
101711   int (*auto_extension)(void(*)(void));
101712   int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
101713                      void(*)(void*));
101714   int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
101715                       void(*)(void*),unsigned char);
101716   int (*cancel_auto_extension)(void(*)(void));
101717   int (*load_extension)(sqlite3*,const char*,const char*,char**);
101718   void *(*malloc64)(sqlite3_uint64);
101719   sqlite3_uint64 (*msize)(void*);
101720   void *(*realloc64)(void*,sqlite3_uint64);
101721   void (*reset_auto_extension)(void);
101722   void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
101723                         void(*)(void*));
101724   void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
101725                          void(*)(void*), unsigned char);
101726   int (*strglob)(const char*,const char*);
101727 };
101728
101729 /*
101730 ** The following macros redefine the API routines so that they are
101731 ** redirected through the global sqlite3_api structure.
101732 **
101733 ** This header file is also used by the loadext.c source file
101734 ** (part of the main SQLite library - not an extension) so that
101735 ** it can get access to the sqlite3_api_routines structure
101736 ** definition.  But the main library does not want to redefine
101737 ** the API.  So the redefinition macros are only valid if the
101738 ** SQLITE_CORE macros is undefined.
101739 */
101740 #ifndef SQLITE_CORE
101741 #define sqlite3_aggregate_context      sqlite3_api->aggregate_context
101742 #ifndef SQLITE_OMIT_DEPRECATED
101743 #define sqlite3_aggregate_count        sqlite3_api->aggregate_count
101744 #endif
101745 #define sqlite3_bind_blob              sqlite3_api->bind_blob
101746 #define sqlite3_bind_double            sqlite3_api->bind_double
101747 #define sqlite3_bind_int               sqlite3_api->bind_int
101748 #define sqlite3_bind_int64             sqlite3_api->bind_int64
101749 #define sqlite3_bind_null              sqlite3_api->bind_null
101750 #define sqlite3_bind_parameter_count   sqlite3_api->bind_parameter_count
101751 #define sqlite3_bind_parameter_index   sqlite3_api->bind_parameter_index
101752 #define sqlite3_bind_parameter_name    sqlite3_api->bind_parameter_name
101753 #define sqlite3_bind_text              sqlite3_api->bind_text
101754 #define sqlite3_bind_text16            sqlite3_api->bind_text16
101755 #define sqlite3_bind_value             sqlite3_api->bind_value
101756 #define sqlite3_busy_handler           sqlite3_api->busy_handler
101757 #define sqlite3_busy_timeout           sqlite3_api->busy_timeout
101758 #define sqlite3_changes                sqlite3_api->changes
101759 #define sqlite3_close                  sqlite3_api->close
101760 #define sqlite3_collation_needed       sqlite3_api->collation_needed
101761 #define sqlite3_collation_needed16     sqlite3_api->collation_needed16
101762 #define sqlite3_column_blob            sqlite3_api->column_blob
101763 #define sqlite3_column_bytes           sqlite3_api->column_bytes
101764 #define sqlite3_column_bytes16         sqlite3_api->column_bytes16
101765 #define sqlite3_column_count           sqlite3_api->column_count
101766 #define sqlite3_column_database_name   sqlite3_api->column_database_name
101767 #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
101768 #define sqlite3_column_decltype        sqlite3_api->column_decltype
101769 #define sqlite3_column_decltype16      sqlite3_api->column_decltype16
101770 #define sqlite3_column_double          sqlite3_api->column_double
101771 #define sqlite3_column_int             sqlite3_api->column_int
101772 #define sqlite3_column_int64           sqlite3_api->column_int64
101773 #define sqlite3_column_name            sqlite3_api->column_name
101774 #define sqlite3_column_name16          sqlite3_api->column_name16
101775 #define sqlite3_column_origin_name     sqlite3_api->column_origin_name
101776 #define sqlite3_column_origin_name16   sqlite3_api->column_origin_name16
101777 #define sqlite3_column_table_name      sqlite3_api->column_table_name
101778 #define sqlite3_column_table_name16    sqlite3_api->column_table_name16
101779 #define sqlite3_column_text            sqlite3_api->column_text
101780 #define sqlite3_column_text16          sqlite3_api->column_text16
101781 #define sqlite3_column_type            sqlite3_api->column_type
101782 #define sqlite3_column_value           sqlite3_api->column_value
101783 #define sqlite3_commit_hook            sqlite3_api->commit_hook
101784 #define sqlite3_complete               sqlite3_api->complete
101785 #define sqlite3_complete16             sqlite3_api->complete16
101786 #define sqlite3_create_collation       sqlite3_api->create_collation
101787 #define sqlite3_create_collation16     sqlite3_api->create_collation16
101788 #define sqlite3_create_function        sqlite3_api->create_function
101789 #define sqlite3_create_function16      sqlite3_api->create_function16
101790 #define sqlite3_create_module          sqlite3_api->create_module
101791 #define sqlite3_create_module_v2       sqlite3_api->create_module_v2
101792 #define sqlite3_data_count             sqlite3_api->data_count
101793 #define sqlite3_db_handle              sqlite3_api->db_handle
101794 #define sqlite3_declare_vtab           sqlite3_api->declare_vtab
101795 #define sqlite3_enable_shared_cache    sqlite3_api->enable_shared_cache
101796 #define sqlite3_errcode                sqlite3_api->errcode
101797 #define sqlite3_errmsg                 sqlite3_api->errmsg
101798 #define sqlite3_errmsg16               sqlite3_api->errmsg16
101799 #define sqlite3_exec                   sqlite3_api->exec
101800 #ifndef SQLITE_OMIT_DEPRECATED
101801 #define sqlite3_expired                sqlite3_api->expired
101802 #endif
101803 #define sqlite3_finalize               sqlite3_api->finalize
101804 #define sqlite3_free                   sqlite3_api->free
101805 #define sqlite3_free_table             sqlite3_api->free_table
101806 #define sqlite3_get_autocommit         sqlite3_api->get_autocommit
101807 #define sqlite3_get_auxdata            sqlite3_api->get_auxdata
101808 #define sqlite3_get_table              sqlite3_api->get_table
101809 #ifndef SQLITE_OMIT_DEPRECATED
101810 #define sqlite3_global_recover         sqlite3_api->global_recover
101811 #endif
101812 #define sqlite3_interrupt              sqlite3_api->interruptx
101813 #define sqlite3_last_insert_rowid      sqlite3_api->last_insert_rowid
101814 #define sqlite3_libversion             sqlite3_api->libversion
101815 #define sqlite3_libversion_number      sqlite3_api->libversion_number
101816 #define sqlite3_malloc                 sqlite3_api->malloc
101817 #define sqlite3_mprintf                sqlite3_api->mprintf
101818 #define sqlite3_open                   sqlite3_api->open
101819 #define sqlite3_open16                 sqlite3_api->open16
101820 #define sqlite3_prepare                sqlite3_api->prepare
101821 #define sqlite3_prepare16              sqlite3_api->prepare16
101822 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
101823 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
101824 #define sqlite3_profile                sqlite3_api->profile
101825 #define sqlite3_progress_handler       sqlite3_api->progress_handler
101826 #define sqlite3_realloc                sqlite3_api->realloc
101827 #define sqlite3_reset                  sqlite3_api->reset
101828 #define sqlite3_result_blob            sqlite3_api->result_blob
101829 #define sqlite3_result_double          sqlite3_api->result_double
101830 #define sqlite3_result_error           sqlite3_api->result_error
101831 #define sqlite3_result_error16         sqlite3_api->result_error16
101832 #define sqlite3_result_int             sqlite3_api->result_int
101833 #define sqlite3_result_int64           sqlite3_api->result_int64
101834 #define sqlite3_result_null            sqlite3_api->result_null
101835 #define sqlite3_result_text            sqlite3_api->result_text
101836 #define sqlite3_result_text16          sqlite3_api->result_text16
101837 #define sqlite3_result_text16be        sqlite3_api->result_text16be
101838 #define sqlite3_result_text16le        sqlite3_api->result_text16le
101839 #define sqlite3_result_value           sqlite3_api->result_value
101840 #define sqlite3_rollback_hook          sqlite3_api->rollback_hook
101841 #define sqlite3_set_authorizer         sqlite3_api->set_authorizer
101842 #define sqlite3_set_auxdata            sqlite3_api->set_auxdata
101843 #define sqlite3_snprintf               sqlite3_api->snprintf
101844 #define sqlite3_step                   sqlite3_api->step
101845 #define sqlite3_table_column_metadata  sqlite3_api->table_column_metadata
101846 #define sqlite3_thread_cleanup         sqlite3_api->thread_cleanup
101847 #define sqlite3_total_changes          sqlite3_api->total_changes
101848 #define sqlite3_trace                  sqlite3_api->trace
101849 #ifndef SQLITE_OMIT_DEPRECATED
101850 #define sqlite3_transfer_bindings      sqlite3_api->transfer_bindings
101851 #endif
101852 #define sqlite3_update_hook            sqlite3_api->update_hook
101853 #define sqlite3_user_data              sqlite3_api->user_data
101854 #define sqlite3_value_blob             sqlite3_api->value_blob
101855 #define sqlite3_value_bytes            sqlite3_api->value_bytes
101856 #define sqlite3_value_bytes16          sqlite3_api->value_bytes16
101857 #define sqlite3_value_double           sqlite3_api->value_double
101858 #define sqlite3_value_int              sqlite3_api->value_int
101859 #define sqlite3_value_int64            sqlite3_api->value_int64
101860 #define sqlite3_value_numeric_type     sqlite3_api->value_numeric_type
101861 #define sqlite3_value_text             sqlite3_api->value_text
101862 #define sqlite3_value_text16           sqlite3_api->value_text16
101863 #define sqlite3_value_text16be         sqlite3_api->value_text16be
101864 #define sqlite3_value_text16le         sqlite3_api->value_text16le
101865 #define sqlite3_value_type             sqlite3_api->value_type
101866 #define sqlite3_vmprintf               sqlite3_api->vmprintf
101867 #define sqlite3_overload_function      sqlite3_api->overload_function
101868 #define sqlite3_prepare_v2             sqlite3_api->prepare_v2
101869 #define sqlite3_prepare16_v2           sqlite3_api->prepare16_v2
101870 #define sqlite3_clear_bindings         sqlite3_api->clear_bindings
101871 #define sqlite3_bind_zeroblob          sqlite3_api->bind_zeroblob
101872 #define sqlite3_blob_bytes             sqlite3_api->blob_bytes
101873 #define sqlite3_blob_close             sqlite3_api->blob_close
101874 #define sqlite3_blob_open              sqlite3_api->blob_open
101875 #define sqlite3_blob_read              sqlite3_api->blob_read
101876 #define sqlite3_blob_write             sqlite3_api->blob_write
101877 #define sqlite3_create_collation_v2    sqlite3_api->create_collation_v2
101878 #define sqlite3_file_control           sqlite3_api->file_control
101879 #define sqlite3_memory_highwater       sqlite3_api->memory_highwater
101880 #define sqlite3_memory_used            sqlite3_api->memory_used
101881 #define sqlite3_mutex_alloc            sqlite3_api->mutex_alloc
101882 #define sqlite3_mutex_enter            sqlite3_api->mutex_enter
101883 #define sqlite3_mutex_free             sqlite3_api->mutex_free
101884 #define sqlite3_mutex_leave            sqlite3_api->mutex_leave
101885 #define sqlite3_mutex_try              sqlite3_api->mutex_try
101886 #define sqlite3_open_v2                sqlite3_api->open_v2
101887 #define sqlite3_release_memory         sqlite3_api->release_memory
101888 #define sqlite3_result_error_nomem     sqlite3_api->result_error_nomem
101889 #define sqlite3_result_error_toobig    sqlite3_api->result_error_toobig
101890 #define sqlite3_sleep                  sqlite3_api->sleep
101891 #define sqlite3_soft_heap_limit        sqlite3_api->soft_heap_limit
101892 #define sqlite3_vfs_find               sqlite3_api->vfs_find
101893 #define sqlite3_vfs_register           sqlite3_api->vfs_register
101894 #define sqlite3_vfs_unregister         sqlite3_api->vfs_unregister
101895 #define sqlite3_threadsafe             sqlite3_api->xthreadsafe
101896 #define sqlite3_result_zeroblob        sqlite3_api->result_zeroblob
101897 #define sqlite3_result_error_code      sqlite3_api->result_error_code
101898 #define sqlite3_test_control           sqlite3_api->test_control
101899 #define sqlite3_randomness             sqlite3_api->randomness
101900 #define sqlite3_context_db_handle      sqlite3_api->context_db_handle
101901 #define sqlite3_extended_result_codes  sqlite3_api->extended_result_codes
101902 #define sqlite3_limit                  sqlite3_api->limit
101903 #define sqlite3_next_stmt              sqlite3_api->next_stmt
101904 #define sqlite3_sql                    sqlite3_api->sql
101905 #define sqlite3_status                 sqlite3_api->status
101906 #define sqlite3_backup_finish          sqlite3_api->backup_finish
101907 #define sqlite3_backup_init            sqlite3_api->backup_init
101908 #define sqlite3_backup_pagecount       sqlite3_api->backup_pagecount
101909 #define sqlite3_backup_remaining       sqlite3_api->backup_remaining
101910 #define sqlite3_backup_step            sqlite3_api->backup_step
101911 #define sqlite3_compileoption_get      sqlite3_api->compileoption_get
101912 #define sqlite3_compileoption_used     sqlite3_api->compileoption_used
101913 #define sqlite3_create_function_v2     sqlite3_api->create_function_v2
101914 #define sqlite3_db_config              sqlite3_api->db_config
101915 #define sqlite3_db_mutex               sqlite3_api->db_mutex
101916 #define sqlite3_db_status              sqlite3_api->db_status
101917 #define sqlite3_extended_errcode       sqlite3_api->extended_errcode
101918 #define sqlite3_log                    sqlite3_api->log
101919 #define sqlite3_soft_heap_limit64      sqlite3_api->soft_heap_limit64
101920 #define sqlite3_sourceid               sqlite3_api->sourceid
101921 #define sqlite3_stmt_status            sqlite3_api->stmt_status
101922 #define sqlite3_strnicmp               sqlite3_api->strnicmp
101923 #define sqlite3_unlock_notify          sqlite3_api->unlock_notify
101924 #define sqlite3_wal_autocheckpoint     sqlite3_api->wal_autocheckpoint
101925 #define sqlite3_wal_checkpoint         sqlite3_api->wal_checkpoint
101926 #define sqlite3_wal_hook               sqlite3_api->wal_hook
101927 #define sqlite3_blob_reopen            sqlite3_api->blob_reopen
101928 #define sqlite3_vtab_config            sqlite3_api->vtab_config
101929 #define sqlite3_vtab_on_conflict       sqlite3_api->vtab_on_conflict
101930 /* Version 3.7.16 and later */
101931 #define sqlite3_close_v2               sqlite3_api->close_v2
101932 #define sqlite3_db_filename            sqlite3_api->db_filename
101933 #define sqlite3_db_readonly            sqlite3_api->db_readonly
101934 #define sqlite3_db_release_memory      sqlite3_api->db_release_memory
101935 #define sqlite3_errstr                 sqlite3_api->errstr
101936 #define sqlite3_stmt_busy              sqlite3_api->stmt_busy
101937 #define sqlite3_stmt_readonly          sqlite3_api->stmt_readonly
101938 #define sqlite3_stricmp                sqlite3_api->stricmp
101939 #define sqlite3_uri_boolean            sqlite3_api->uri_boolean
101940 #define sqlite3_uri_int64              sqlite3_api->uri_int64
101941 #define sqlite3_uri_parameter          sqlite3_api->uri_parameter
101942 #define sqlite3_uri_vsnprintf          sqlite3_api->vsnprintf
101943 #define sqlite3_wal_checkpoint_v2      sqlite3_api->wal_checkpoint_v2
101944 /* Version 3.8.7 and later */
101945 #define sqlite3_auto_extension         sqlite3_api->auto_extension
101946 #define sqlite3_bind_blob64            sqlite3_api->bind_blob64
101947 #define sqlite3_bind_text64            sqlite3_api->bind_text64
101948 #define sqlite3_cancel_auto_extension  sqlite3_api->cancel_auto_extension
101949 #define sqlite3_load_extension         sqlite3_api->load_extension
101950 #define sqlite3_malloc64               sqlite3_api->malloc64
101951 #define sqlite3_msize                  sqlite3_api->msize
101952 #define sqlite3_realloc64              sqlite3_api->realloc64
101953 #define sqlite3_reset_auto_extension   sqlite3_api->reset_auto_extension
101954 #define sqlite3_result_blob64          sqlite3_api->result_blob64
101955 #define sqlite3_result_text64          sqlite3_api->result_text64
101956 #define sqlite3_strglob                sqlite3_api->strglob
101957 #endif /* SQLITE_CORE */
101958
101959 #ifndef SQLITE_CORE
101960   /* This case when the file really is being compiled as a loadable 
101961   ** extension */
101962 # define SQLITE_EXTENSION_INIT1     const sqlite3_api_routines *sqlite3_api=0;
101963 # define SQLITE_EXTENSION_INIT2(v)  sqlite3_api=v;
101964 # define SQLITE_EXTENSION_INIT3     \
101965     extern const sqlite3_api_routines *sqlite3_api;
101966 #else
101967   /* This case when the file is being statically linked into the 
101968   ** application */
101969 # define SQLITE_EXTENSION_INIT1     /*no-op*/
101970 # define SQLITE_EXTENSION_INIT2(v)  (void)v; /* unused parameter */
101971 # define SQLITE_EXTENSION_INIT3     /*no-op*/
101972 #endif
101973
101974 #endif /* _SQLITE3EXT_H_ */
101975
101976 /************** End of sqlite3ext.h ******************************************/
101977 /************** Continuing where we left off in loadext.c ********************/
101978 /* #include <string.h> */
101979
101980 #ifndef SQLITE_OMIT_LOAD_EXTENSION
101981
101982 /*
101983 ** Some API routines are omitted when various features are
101984 ** excluded from a build of SQLite.  Substitute a NULL pointer
101985 ** for any missing APIs.
101986 */
101987 #ifndef SQLITE_ENABLE_COLUMN_METADATA
101988 # define sqlite3_column_database_name   0
101989 # define sqlite3_column_database_name16 0
101990 # define sqlite3_column_table_name      0
101991 # define sqlite3_column_table_name16    0
101992 # define sqlite3_column_origin_name     0
101993 # define sqlite3_column_origin_name16   0
101994 #endif
101995
101996 #ifdef SQLITE_OMIT_AUTHORIZATION
101997 # define sqlite3_set_authorizer         0
101998 #endif
101999
102000 #ifdef SQLITE_OMIT_UTF16
102001 # define sqlite3_bind_text16            0
102002 # define sqlite3_collation_needed16     0
102003 # define sqlite3_column_decltype16      0
102004 # define sqlite3_column_name16          0
102005 # define sqlite3_column_text16          0
102006 # define sqlite3_complete16             0
102007 # define sqlite3_create_collation16     0
102008 # define sqlite3_create_function16      0
102009 # define sqlite3_errmsg16               0
102010 # define sqlite3_open16                 0
102011 # define sqlite3_prepare16              0
102012 # define sqlite3_prepare16_v2           0
102013 # define sqlite3_result_error16         0
102014 # define sqlite3_result_text16          0
102015 # define sqlite3_result_text16be        0
102016 # define sqlite3_result_text16le        0
102017 # define sqlite3_value_text16           0
102018 # define sqlite3_value_text16be         0
102019 # define sqlite3_value_text16le         0
102020 # define sqlite3_column_database_name16 0
102021 # define sqlite3_column_table_name16    0
102022 # define sqlite3_column_origin_name16   0
102023 #endif
102024
102025 #ifdef SQLITE_OMIT_COMPLETE
102026 # define sqlite3_complete 0
102027 # define sqlite3_complete16 0
102028 #endif
102029
102030 #ifdef SQLITE_OMIT_DECLTYPE
102031 # define sqlite3_column_decltype16      0
102032 # define sqlite3_column_decltype        0
102033 #endif
102034
102035 #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
102036 # define sqlite3_progress_handler 0
102037 #endif
102038
102039 #ifdef SQLITE_OMIT_VIRTUALTABLE
102040 # define sqlite3_create_module 0
102041 # define sqlite3_create_module_v2 0
102042 # define sqlite3_declare_vtab 0
102043 # define sqlite3_vtab_config 0
102044 # define sqlite3_vtab_on_conflict 0
102045 #endif
102046
102047 #ifdef SQLITE_OMIT_SHARED_CACHE
102048 # define sqlite3_enable_shared_cache 0
102049 #endif
102050
102051 #ifdef SQLITE_OMIT_TRACE
102052 # define sqlite3_profile       0
102053 # define sqlite3_trace         0
102054 #endif
102055
102056 #ifdef SQLITE_OMIT_GET_TABLE
102057 # define sqlite3_free_table    0
102058 # define sqlite3_get_table     0
102059 #endif
102060
102061 #ifdef SQLITE_OMIT_INCRBLOB
102062 #define sqlite3_bind_zeroblob  0
102063 #define sqlite3_blob_bytes     0
102064 #define sqlite3_blob_close     0
102065 #define sqlite3_blob_open      0
102066 #define sqlite3_blob_read      0
102067 #define sqlite3_blob_write     0
102068 #define sqlite3_blob_reopen    0
102069 #endif
102070
102071 /*
102072 ** The following structure contains pointers to all SQLite API routines.
102073 ** A pointer to this structure is passed into extensions when they are
102074 ** loaded so that the extension can make calls back into the SQLite
102075 ** library.
102076 **
102077 ** When adding new APIs, add them to the bottom of this structure
102078 ** in order to preserve backwards compatibility.
102079 **
102080 ** Extensions that use newer APIs should first call the
102081 ** sqlite3_libversion_number() to make sure that the API they
102082 ** intend to use is supported by the library.  Extensions should
102083 ** also check to make sure that the pointer to the function is
102084 ** not NULL before calling it.
102085 */
102086 static const sqlite3_api_routines sqlite3Apis = {
102087   sqlite3_aggregate_context,
102088 #ifndef SQLITE_OMIT_DEPRECATED
102089   sqlite3_aggregate_count,
102090 #else
102091   0,
102092 #endif
102093   sqlite3_bind_blob,
102094   sqlite3_bind_double,
102095   sqlite3_bind_int,
102096   sqlite3_bind_int64,
102097   sqlite3_bind_null,
102098   sqlite3_bind_parameter_count,
102099   sqlite3_bind_parameter_index,
102100   sqlite3_bind_parameter_name,
102101   sqlite3_bind_text,
102102   sqlite3_bind_text16,
102103   sqlite3_bind_value,
102104   sqlite3_busy_handler,
102105   sqlite3_busy_timeout,
102106   sqlite3_changes,
102107   sqlite3_close,
102108   sqlite3_collation_needed,
102109   sqlite3_collation_needed16,
102110   sqlite3_column_blob,
102111   sqlite3_column_bytes,
102112   sqlite3_column_bytes16,
102113   sqlite3_column_count,
102114   sqlite3_column_database_name,
102115   sqlite3_column_database_name16,
102116   sqlite3_column_decltype,
102117   sqlite3_column_decltype16,
102118   sqlite3_column_double,
102119   sqlite3_column_int,
102120   sqlite3_column_int64,
102121   sqlite3_column_name,
102122   sqlite3_column_name16,
102123   sqlite3_column_origin_name,
102124   sqlite3_column_origin_name16,
102125   sqlite3_column_table_name,
102126   sqlite3_column_table_name16,
102127   sqlite3_column_text,
102128   sqlite3_column_text16,
102129   sqlite3_column_type,
102130   sqlite3_column_value,
102131   sqlite3_commit_hook,
102132   sqlite3_complete,
102133   sqlite3_complete16,
102134   sqlite3_create_collation,
102135   sqlite3_create_collation16,
102136   sqlite3_create_function,
102137   sqlite3_create_function16,
102138   sqlite3_create_module,
102139   sqlite3_data_count,
102140   sqlite3_db_handle,
102141   sqlite3_declare_vtab,
102142   sqlite3_enable_shared_cache,
102143   sqlite3_errcode,
102144   sqlite3_errmsg,
102145   sqlite3_errmsg16,
102146   sqlite3_exec,
102147 #ifndef SQLITE_OMIT_DEPRECATED
102148   sqlite3_expired,
102149 #else
102150   0,
102151 #endif
102152   sqlite3_finalize,
102153   sqlite3_free,
102154   sqlite3_free_table,
102155   sqlite3_get_autocommit,
102156   sqlite3_get_auxdata,
102157   sqlite3_get_table,
102158   0,     /* Was sqlite3_global_recover(), but that function is deprecated */
102159   sqlite3_interrupt,
102160   sqlite3_last_insert_rowid,
102161   sqlite3_libversion,
102162   sqlite3_libversion_number,
102163   sqlite3_malloc,
102164   sqlite3_mprintf,
102165   sqlite3_open,
102166   sqlite3_open16,
102167   sqlite3_prepare,
102168   sqlite3_prepare16,
102169   sqlite3_profile,
102170   sqlite3_progress_handler,
102171   sqlite3_realloc,
102172   sqlite3_reset,
102173   sqlite3_result_blob,
102174   sqlite3_result_double,
102175   sqlite3_result_error,
102176   sqlite3_result_error16,
102177   sqlite3_result_int,
102178   sqlite3_result_int64,
102179   sqlite3_result_null,
102180   sqlite3_result_text,
102181   sqlite3_result_text16,
102182   sqlite3_result_text16be,
102183   sqlite3_result_text16le,
102184   sqlite3_result_value,
102185   sqlite3_rollback_hook,
102186   sqlite3_set_authorizer,
102187   sqlite3_set_auxdata,
102188   sqlite3_snprintf,
102189   sqlite3_step,
102190   sqlite3_table_column_metadata,
102191 #ifndef SQLITE_OMIT_DEPRECATED
102192   sqlite3_thread_cleanup,
102193 #else
102194   0,
102195 #endif
102196   sqlite3_total_changes,
102197   sqlite3_trace,
102198 #ifndef SQLITE_OMIT_DEPRECATED
102199   sqlite3_transfer_bindings,
102200 #else
102201   0,
102202 #endif
102203   sqlite3_update_hook,
102204   sqlite3_user_data,
102205   sqlite3_value_blob,
102206   sqlite3_value_bytes,
102207   sqlite3_value_bytes16,
102208   sqlite3_value_double,
102209   sqlite3_value_int,
102210   sqlite3_value_int64,
102211   sqlite3_value_numeric_type,
102212   sqlite3_value_text,
102213   sqlite3_value_text16,
102214   sqlite3_value_text16be,
102215   sqlite3_value_text16le,
102216   sqlite3_value_type,
102217   sqlite3_vmprintf,
102218   /*
102219   ** The original API set ends here.  All extensions can call any
102220   ** of the APIs above provided that the pointer is not NULL.  But
102221   ** before calling APIs that follow, extension should check the
102222   ** sqlite3_libversion_number() to make sure they are dealing with
102223   ** a library that is new enough to support that API.
102224   *************************************************************************
102225   */
102226   sqlite3_overload_function,
102227
102228   /*
102229   ** Added after 3.3.13
102230   */
102231   sqlite3_prepare_v2,
102232   sqlite3_prepare16_v2,
102233   sqlite3_clear_bindings,
102234
102235   /*
102236   ** Added for 3.4.1
102237   */
102238   sqlite3_create_module_v2,
102239
102240   /*
102241   ** Added for 3.5.0
102242   */
102243   sqlite3_bind_zeroblob,
102244   sqlite3_blob_bytes,
102245   sqlite3_blob_close,
102246   sqlite3_blob_open,
102247   sqlite3_blob_read,
102248   sqlite3_blob_write,
102249   sqlite3_create_collation_v2,
102250   sqlite3_file_control,
102251   sqlite3_memory_highwater,
102252   sqlite3_memory_used,
102253 #ifdef SQLITE_MUTEX_OMIT
102254   0, 
102255   0, 
102256   0,
102257   0,
102258   0,
102259 #else
102260   sqlite3_mutex_alloc,
102261   sqlite3_mutex_enter,
102262   sqlite3_mutex_free,
102263   sqlite3_mutex_leave,
102264   sqlite3_mutex_try,
102265 #endif
102266   sqlite3_open_v2,
102267   sqlite3_release_memory,
102268   sqlite3_result_error_nomem,
102269   sqlite3_result_error_toobig,
102270   sqlite3_sleep,
102271   sqlite3_soft_heap_limit,
102272   sqlite3_vfs_find,
102273   sqlite3_vfs_register,
102274   sqlite3_vfs_unregister,
102275
102276   /*
102277   ** Added for 3.5.8
102278   */
102279   sqlite3_threadsafe,
102280   sqlite3_result_zeroblob,
102281   sqlite3_result_error_code,
102282   sqlite3_test_control,
102283   sqlite3_randomness,
102284   sqlite3_context_db_handle,
102285
102286   /*
102287   ** Added for 3.6.0
102288   */
102289   sqlite3_extended_result_codes,
102290   sqlite3_limit,
102291   sqlite3_next_stmt,
102292   sqlite3_sql,
102293   sqlite3_status,
102294
102295   /*
102296   ** Added for 3.7.4
102297   */
102298   sqlite3_backup_finish,
102299   sqlite3_backup_init,
102300   sqlite3_backup_pagecount,
102301   sqlite3_backup_remaining,
102302   sqlite3_backup_step,
102303 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
102304   sqlite3_compileoption_get,
102305   sqlite3_compileoption_used,
102306 #else
102307   0,
102308   0,
102309 #endif
102310   sqlite3_create_function_v2,
102311   sqlite3_db_config,
102312   sqlite3_db_mutex,
102313   sqlite3_db_status,
102314   sqlite3_extended_errcode,
102315   sqlite3_log,
102316   sqlite3_soft_heap_limit64,
102317   sqlite3_sourceid,
102318   sqlite3_stmt_status,
102319   sqlite3_strnicmp,
102320 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
102321   sqlite3_unlock_notify,
102322 #else
102323   0,
102324 #endif
102325 #ifndef SQLITE_OMIT_WAL
102326   sqlite3_wal_autocheckpoint,
102327   sqlite3_wal_checkpoint,
102328   sqlite3_wal_hook,
102329 #else
102330   0,
102331   0,
102332   0,
102333 #endif
102334   sqlite3_blob_reopen,
102335   sqlite3_vtab_config,
102336   sqlite3_vtab_on_conflict,
102337   sqlite3_close_v2,
102338   sqlite3_db_filename,
102339   sqlite3_db_readonly,
102340   sqlite3_db_release_memory,
102341   sqlite3_errstr,
102342   sqlite3_stmt_busy,
102343   sqlite3_stmt_readonly,
102344   sqlite3_stricmp,
102345   sqlite3_uri_boolean,
102346   sqlite3_uri_int64,
102347   sqlite3_uri_parameter,
102348   sqlite3_vsnprintf,
102349   sqlite3_wal_checkpoint_v2,
102350   /* Version 3.8.7 and later */
102351   sqlite3_auto_extension,
102352   sqlite3_bind_blob64,
102353   sqlite3_bind_text64,
102354   sqlite3_cancel_auto_extension,
102355   sqlite3_load_extension,
102356   sqlite3_malloc64,
102357   sqlite3_msize,
102358   sqlite3_realloc64,
102359   sqlite3_reset_auto_extension,
102360   sqlite3_result_blob64,
102361   sqlite3_result_text64,
102362   sqlite3_strglob
102363 };
102364
102365 /*
102366 ** Attempt to load an SQLite extension library contained in the file
102367 ** zFile.  The entry point is zProc.  zProc may be 0 in which case a
102368 ** default entry point name (sqlite3_extension_init) is used.  Use
102369 ** of the default name is recommended.
102370 **
102371 ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
102372 **
102373 ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with 
102374 ** error message text.  The calling function should free this memory
102375 ** by calling sqlite3DbFree(db, ).
102376 */
102377 static int sqlite3LoadExtension(
102378   sqlite3 *db,          /* Load the extension into this database connection */
102379   const char *zFile,    /* Name of the shared library containing extension */
102380   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
102381   char **pzErrMsg       /* Put error message here if not 0 */
102382 ){
102383   sqlite3_vfs *pVfs = db->pVfs;
102384   void *handle;
102385   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
102386   char *zErrmsg = 0;
102387   const char *zEntry;
102388   char *zAltEntry = 0;
102389   void **aHandle;
102390   int nMsg = 300 + sqlite3Strlen30(zFile);
102391   int ii;
102392
102393   /* Shared library endings to try if zFile cannot be loaded as written */
102394   static const char *azEndings[] = {
102395 #if SQLITE_OS_WIN
102396      "dll"   
102397 #elif defined(__APPLE__)
102398      "dylib"
102399 #else
102400      "so"
102401 #endif
102402   };
102403
102404
102405   if( pzErrMsg ) *pzErrMsg = 0;
102406
102407   /* Ticket #1863.  To avoid a creating security problems for older
102408   ** applications that relink against newer versions of SQLite, the
102409   ** ability to run load_extension is turned off by default.  One
102410   ** must call sqlite3_enable_load_extension() to turn on extension
102411   ** loading.  Otherwise you get the following error.
102412   */
102413   if( (db->flags & SQLITE_LoadExtension)==0 ){
102414     if( pzErrMsg ){
102415       *pzErrMsg = sqlite3_mprintf("not authorized");
102416     }
102417     return SQLITE_ERROR;
102418   }
102419
102420   zEntry = zProc ? zProc : "sqlite3_extension_init";
102421
102422   handle = sqlite3OsDlOpen(pVfs, zFile);
102423 #if SQLITE_OS_UNIX || SQLITE_OS_WIN
102424   for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
102425     char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
102426     if( zAltFile==0 ) return SQLITE_NOMEM;
102427     handle = sqlite3OsDlOpen(pVfs, zAltFile);
102428     sqlite3_free(zAltFile);
102429   }
102430 #endif
102431   if( handle==0 ){
102432     if( pzErrMsg ){
102433       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
102434       if( zErrmsg ){
102435         sqlite3_snprintf(nMsg, zErrmsg, 
102436             "unable to open shared library [%s]", zFile);
102437         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
102438       }
102439     }
102440     return SQLITE_ERROR;
102441   }
102442   xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
102443                    sqlite3OsDlSym(pVfs, handle, zEntry);
102444
102445   /* If no entry point was specified and the default legacy
102446   ** entry point name "sqlite3_extension_init" was not found, then
102447   ** construct an entry point name "sqlite3_X_init" where the X is
102448   ** replaced by the lowercase value of every ASCII alphabetic 
102449   ** character in the filename after the last "/" upto the first ".",
102450   ** and eliding the first three characters if they are "lib".  
102451   ** Examples:
102452   **
102453   **    /usr/local/lib/libExample5.4.3.so ==>  sqlite3_example_init
102454   **    C:/lib/mathfuncs.dll              ==>  sqlite3_mathfuncs_init
102455   */
102456   if( xInit==0 && zProc==0 ){
102457     int iFile, iEntry, c;
102458     int ncFile = sqlite3Strlen30(zFile);
102459     zAltEntry = sqlite3_malloc(ncFile+30);
102460     if( zAltEntry==0 ){
102461       sqlite3OsDlClose(pVfs, handle);
102462       return SQLITE_NOMEM;
102463     }
102464     memcpy(zAltEntry, "sqlite3_", 8);
102465     for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
102466     iFile++;
102467     if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
102468     for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
102469       if( sqlite3Isalpha(c) ){
102470         zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
102471       }
102472     }
102473     memcpy(zAltEntry+iEntry, "_init", 6);
102474     zEntry = zAltEntry;
102475     xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
102476                      sqlite3OsDlSym(pVfs, handle, zEntry);
102477   }
102478   if( xInit==0 ){
102479     if( pzErrMsg ){
102480       nMsg += sqlite3Strlen30(zEntry);
102481       *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
102482       if( zErrmsg ){
102483         sqlite3_snprintf(nMsg, zErrmsg,
102484             "no entry point [%s] in shared library [%s]", zEntry, zFile);
102485         sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
102486       }
102487     }
102488     sqlite3OsDlClose(pVfs, handle);
102489     sqlite3_free(zAltEntry);
102490     return SQLITE_ERROR;
102491   }
102492   sqlite3_free(zAltEntry);
102493   if( xInit(db, &zErrmsg, &sqlite3Apis) ){
102494     if( pzErrMsg ){
102495       *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
102496     }
102497     sqlite3_free(zErrmsg);
102498     sqlite3OsDlClose(pVfs, handle);
102499     return SQLITE_ERROR;
102500   }
102501
102502   /* Append the new shared library handle to the db->aExtension array. */
102503   aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
102504   if( aHandle==0 ){
102505     return SQLITE_NOMEM;
102506   }
102507   if( db->nExtension>0 ){
102508     memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
102509   }
102510   sqlite3DbFree(db, db->aExtension);
102511   db->aExtension = aHandle;
102512
102513   db->aExtension[db->nExtension++] = handle;
102514   return SQLITE_OK;
102515 }
102516 SQLITE_API int SQLITE_STDCALL sqlite3_load_extension(
102517   sqlite3 *db,          /* Load the extension into this database connection */
102518   const char *zFile,    /* Name of the shared library containing extension */
102519   const char *zProc,    /* Entry point.  Use "sqlite3_extension_init" if 0 */
102520   char **pzErrMsg       /* Put error message here if not 0 */
102521 ){
102522   int rc;
102523   sqlite3_mutex_enter(db->mutex);
102524   rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
102525   rc = sqlite3ApiExit(db, rc);
102526   sqlite3_mutex_leave(db->mutex);
102527   return rc;
102528 }
102529
102530 /*
102531 ** Call this routine when the database connection is closing in order
102532 ** to clean up loaded extensions
102533 */
102534 SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
102535   int i;
102536   assert( sqlite3_mutex_held(db->mutex) );
102537   for(i=0; i<db->nExtension; i++){
102538     sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
102539   }
102540   sqlite3DbFree(db, db->aExtension);
102541 }
102542
102543 /*
102544 ** Enable or disable extension loading.  Extension loading is disabled by
102545 ** default so as not to open security holes in older applications.
102546 */
102547 SQLITE_API int SQLITE_STDCALL sqlite3_enable_load_extension(sqlite3 *db, int onoff){
102548   sqlite3_mutex_enter(db->mutex);
102549   if( onoff ){
102550     db->flags |= SQLITE_LoadExtension;
102551   }else{
102552     db->flags &= ~SQLITE_LoadExtension;
102553   }
102554   sqlite3_mutex_leave(db->mutex);
102555   return SQLITE_OK;
102556 }
102557
102558 #endif /* SQLITE_OMIT_LOAD_EXTENSION */
102559
102560 /*
102561 ** The auto-extension code added regardless of whether or not extension
102562 ** loading is supported.  We need a dummy sqlite3Apis pointer for that
102563 ** code if regular extension loading is not available.  This is that
102564 ** dummy pointer.
102565 */
102566 #ifdef SQLITE_OMIT_LOAD_EXTENSION
102567 static const sqlite3_api_routines sqlite3Apis = { 0 };
102568 #endif
102569
102570
102571 /*
102572 ** The following object holds the list of automatically loaded
102573 ** extensions.
102574 **
102575 ** This list is shared across threads.  The SQLITE_MUTEX_STATIC_MASTER
102576 ** mutex must be held while accessing this list.
102577 */
102578 typedef struct sqlite3AutoExtList sqlite3AutoExtList;
102579 static SQLITE_WSD struct sqlite3AutoExtList {
102580   int nExt;              /* Number of entries in aExt[] */          
102581   void (**aExt)(void);   /* Pointers to the extension init functions */
102582 } sqlite3Autoext = { 0, 0 };
102583
102584 /* The "wsdAutoext" macro will resolve to the autoextension
102585 ** state vector.  If writable static data is unsupported on the target,
102586 ** we have to locate the state vector at run-time.  In the more common
102587 ** case where writable static data is supported, wsdStat can refer directly
102588 ** to the "sqlite3Autoext" state vector declared above.
102589 */
102590 #ifdef SQLITE_OMIT_WSD
102591 # define wsdAutoextInit \
102592   sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
102593 # define wsdAutoext x[0]
102594 #else
102595 # define wsdAutoextInit
102596 # define wsdAutoext sqlite3Autoext
102597 #endif
102598
102599
102600 /*
102601 ** Register a statically linked extension that is automatically
102602 ** loaded by every new database connection.
102603 */
102604 SQLITE_API int SQLITE_STDCALL sqlite3_auto_extension(void (*xInit)(void)){
102605   int rc = SQLITE_OK;
102606 #ifndef SQLITE_OMIT_AUTOINIT
102607   rc = sqlite3_initialize();
102608   if( rc ){
102609     return rc;
102610   }else
102611 #endif
102612   {
102613     int i;
102614 #if SQLITE_THREADSAFE
102615     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
102616 #endif
102617     wsdAutoextInit;
102618     sqlite3_mutex_enter(mutex);
102619     for(i=0; i<wsdAutoext.nExt; i++){
102620       if( wsdAutoext.aExt[i]==xInit ) break;
102621     }
102622     if( i==wsdAutoext.nExt ){
102623       int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
102624       void (**aNew)(void);
102625       aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
102626       if( aNew==0 ){
102627         rc = SQLITE_NOMEM;
102628       }else{
102629         wsdAutoext.aExt = aNew;
102630         wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
102631         wsdAutoext.nExt++;
102632       }
102633     }
102634     sqlite3_mutex_leave(mutex);
102635     assert( (rc&0xff)==rc );
102636     return rc;
102637   }
102638 }
102639
102640 /*
102641 ** Cancel a prior call to sqlite3_auto_extension.  Remove xInit from the
102642 ** set of routines that is invoked for each new database connection, if it
102643 ** is currently on the list.  If xInit is not on the list, then this
102644 ** routine is a no-op.
102645 **
102646 ** Return 1 if xInit was found on the list and removed.  Return 0 if xInit
102647 ** was not on the list.
102648 */
102649 SQLITE_API int SQLITE_STDCALL sqlite3_cancel_auto_extension(void (*xInit)(void)){
102650 #if SQLITE_THREADSAFE
102651   sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
102652 #endif
102653   int i;
102654   int n = 0;
102655   wsdAutoextInit;
102656   sqlite3_mutex_enter(mutex);
102657   for(i=wsdAutoext.nExt-1; i>=0; i--){
102658     if( wsdAutoext.aExt[i]==xInit ){
102659       wsdAutoext.nExt--;
102660       wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
102661       n++;
102662       break;
102663     }
102664   }
102665   sqlite3_mutex_leave(mutex);
102666   return n;
102667 }
102668
102669 /*
102670 ** Reset the automatic extension loading mechanism.
102671 */
102672 SQLITE_API void SQLITE_STDCALL sqlite3_reset_auto_extension(void){
102673 #ifndef SQLITE_OMIT_AUTOINIT
102674   if( sqlite3_initialize()==SQLITE_OK )
102675 #endif
102676   {
102677 #if SQLITE_THREADSAFE
102678     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
102679 #endif
102680     wsdAutoextInit;
102681     sqlite3_mutex_enter(mutex);
102682     sqlite3_free(wsdAutoext.aExt);
102683     wsdAutoext.aExt = 0;
102684     wsdAutoext.nExt = 0;
102685     sqlite3_mutex_leave(mutex);
102686   }
102687 }
102688
102689 /*
102690 ** Load all automatic extensions.
102691 **
102692 ** If anything goes wrong, set an error in the database connection.
102693 */
102694 SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
102695   int i;
102696   int go = 1;
102697   int rc;
102698   int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
102699
102700   wsdAutoextInit;
102701   if( wsdAutoext.nExt==0 ){
102702     /* Common case: early out without every having to acquire a mutex */
102703     return;
102704   }
102705   for(i=0; go; i++){
102706     char *zErrmsg;
102707 #if SQLITE_THREADSAFE
102708     sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
102709 #endif
102710     sqlite3_mutex_enter(mutex);
102711     if( i>=wsdAutoext.nExt ){
102712       xInit = 0;
102713       go = 0;
102714     }else{
102715       xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
102716               wsdAutoext.aExt[i];
102717     }
102718     sqlite3_mutex_leave(mutex);
102719     zErrmsg = 0;
102720     if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
102721       sqlite3ErrorWithMsg(db, rc,
102722             "automatic extension loading failed: %s", zErrmsg);
102723       go = 0;
102724     }
102725     sqlite3_free(zErrmsg);
102726   }
102727 }
102728
102729 /************** End of loadext.c *********************************************/
102730 /************** Begin file pragma.c ******************************************/
102731 /*
102732 ** 2003 April 6
102733 **
102734 ** The author disclaims copyright to this source code.  In place of
102735 ** a legal notice, here is a blessing:
102736 **
102737 **    May you do good and not evil.
102738 **    May you find forgiveness for yourself and forgive others.
102739 **    May you share freely, never taking more than you give.
102740 **
102741 *************************************************************************
102742 ** This file contains code used to implement the PRAGMA command.
102743 */
102744
102745 #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
102746 #  if defined(__APPLE__)
102747 #    define SQLITE_ENABLE_LOCKING_STYLE 1
102748 #  else
102749 #    define SQLITE_ENABLE_LOCKING_STYLE 0
102750 #  endif
102751 #endif
102752
102753 /***************************************************************************
102754 ** The "pragma.h" include file is an automatically generated file that
102755 ** that includes the PragType_XXXX macro definitions and the aPragmaName[]
102756 ** object.  This ensures that the aPragmaName[] table is arranged in
102757 ** lexicographical order to facility a binary search of the pragma name.
102758 ** Do not edit pragma.h directly.  Edit and rerun the script in at 
102759 ** ../tool/mkpragmatab.tcl. */
102760 /************** Include pragma.h in the middle of pragma.c *******************/
102761 /************** Begin file pragma.h ******************************************/
102762 /* DO NOT EDIT!
102763 ** This file is automatically generated by the script at
102764 ** ../tool/mkpragmatab.tcl.  To update the set of pragmas, edit
102765 ** that script and rerun it.
102766 */
102767 #define PragTyp_HEADER_VALUE                   0
102768 #define PragTyp_AUTO_VACUUM                    1
102769 #define PragTyp_FLAG                           2
102770 #define PragTyp_BUSY_TIMEOUT                   3
102771 #define PragTyp_CACHE_SIZE                     4
102772 #define PragTyp_CASE_SENSITIVE_LIKE            5
102773 #define PragTyp_COLLATION_LIST                 6
102774 #define PragTyp_COMPILE_OPTIONS                7
102775 #define PragTyp_DATA_STORE_DIRECTORY           8
102776 #define PragTyp_DATABASE_LIST                  9
102777 #define PragTyp_DEFAULT_CACHE_SIZE            10
102778 #define PragTyp_ENCODING                      11
102779 #define PragTyp_FOREIGN_KEY_CHECK             12
102780 #define PragTyp_FOREIGN_KEY_LIST              13
102781 #define PragTyp_INCREMENTAL_VACUUM            14
102782 #define PragTyp_INDEX_INFO                    15
102783 #define PragTyp_INDEX_LIST                    16
102784 #define PragTyp_INTEGRITY_CHECK               17
102785 #define PragTyp_JOURNAL_MODE                  18
102786 #define PragTyp_JOURNAL_SIZE_LIMIT            19
102787 #define PragTyp_LOCK_PROXY_FILE               20
102788 #define PragTyp_LOCKING_MODE                  21
102789 #define PragTyp_PAGE_COUNT                    22
102790 #define PragTyp_MMAP_SIZE                     23
102791 #define PragTyp_PAGE_SIZE                     24
102792 #define PragTyp_SECURE_DELETE                 25
102793 #define PragTyp_SHRINK_MEMORY                 26
102794 #define PragTyp_SOFT_HEAP_LIMIT               27
102795 #define PragTyp_STATS                         28
102796 #define PragTyp_SYNCHRONOUS                   29
102797 #define PragTyp_TABLE_INFO                    30
102798 #define PragTyp_TEMP_STORE                    31
102799 #define PragTyp_TEMP_STORE_DIRECTORY          32
102800 #define PragTyp_THREADS                       33
102801 #define PragTyp_WAL_AUTOCHECKPOINT            34
102802 #define PragTyp_WAL_CHECKPOINT                35
102803 #define PragTyp_ACTIVATE_EXTENSIONS           36
102804 #define PragTyp_HEXKEY                        37
102805 #define PragTyp_KEY                           38
102806 #define PragTyp_REKEY                         39
102807 #define PragTyp_LOCK_STATUS                   40
102808 #define PragTyp_PARSER_TRACE                  41
102809 #define PragFlag_NeedSchema           0x01
102810 #define PragFlag_ReadOnly             0x02
102811 static const struct sPragmaNames {
102812   const char *const zName;  /* Name of pragma */
102813   u8 ePragTyp;              /* PragTyp_XXX value */
102814   u8 mPragFlag;             /* Zero or more PragFlag_XXX values */
102815   u32 iArg;                 /* Extra argument */
102816 } aPragmaNames[] = {
102817 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
102818   { /* zName:     */ "activate_extensions",
102819     /* ePragTyp:  */ PragTyp_ACTIVATE_EXTENSIONS,
102820     /* ePragFlag: */ 0,
102821     /* iArg:      */ 0 },
102822 #endif
102823 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
102824   { /* zName:     */ "application_id",
102825     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
102826     /* ePragFlag: */ 0,
102827     /* iArg:      */ BTREE_APPLICATION_ID },
102828 #endif
102829 #if !defined(SQLITE_OMIT_AUTOVACUUM)
102830   { /* zName:     */ "auto_vacuum",
102831     /* ePragTyp:  */ PragTyp_AUTO_VACUUM,
102832     /* ePragFlag: */ PragFlag_NeedSchema,
102833     /* iArg:      */ 0 },
102834 #endif
102835 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
102836 #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
102837   { /* zName:     */ "automatic_index",
102838     /* ePragTyp:  */ PragTyp_FLAG,
102839     /* ePragFlag: */ 0,
102840     /* iArg:      */ SQLITE_AutoIndex },
102841 #endif
102842 #endif
102843   { /* zName:     */ "busy_timeout",
102844     /* ePragTyp:  */ PragTyp_BUSY_TIMEOUT,
102845     /* ePragFlag: */ 0,
102846     /* iArg:      */ 0 },
102847 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
102848   { /* zName:     */ "cache_size",
102849     /* ePragTyp:  */ PragTyp_CACHE_SIZE,
102850     /* ePragFlag: */ PragFlag_NeedSchema,
102851     /* iArg:      */ 0 },
102852 #endif
102853 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
102854   { /* zName:     */ "cache_spill",
102855     /* ePragTyp:  */ PragTyp_FLAG,
102856     /* ePragFlag: */ 0,
102857     /* iArg:      */ SQLITE_CacheSpill },
102858 #endif
102859   { /* zName:     */ "case_sensitive_like",
102860     /* ePragTyp:  */ PragTyp_CASE_SENSITIVE_LIKE,
102861     /* ePragFlag: */ 0,
102862     /* iArg:      */ 0 },
102863 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
102864   { /* zName:     */ "checkpoint_fullfsync",
102865     /* ePragTyp:  */ PragTyp_FLAG,
102866     /* ePragFlag: */ 0,
102867     /* iArg:      */ SQLITE_CkptFullFSync },
102868 #endif
102869 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
102870   { /* zName:     */ "collation_list",
102871     /* ePragTyp:  */ PragTyp_COLLATION_LIST,
102872     /* ePragFlag: */ 0,
102873     /* iArg:      */ 0 },
102874 #endif
102875 #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
102876   { /* zName:     */ "compile_options",
102877     /* ePragTyp:  */ PragTyp_COMPILE_OPTIONS,
102878     /* ePragFlag: */ 0,
102879     /* iArg:      */ 0 },
102880 #endif
102881 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
102882   { /* zName:     */ "count_changes",
102883     /* ePragTyp:  */ PragTyp_FLAG,
102884     /* ePragFlag: */ 0,
102885     /* iArg:      */ SQLITE_CountRows },
102886 #endif
102887 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
102888   { /* zName:     */ "data_store_directory",
102889     /* ePragTyp:  */ PragTyp_DATA_STORE_DIRECTORY,
102890     /* ePragFlag: */ 0,
102891     /* iArg:      */ 0 },
102892 #endif
102893 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
102894   { /* zName:     */ "data_version",
102895     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
102896     /* ePragFlag: */ PragFlag_ReadOnly,
102897     /* iArg:      */ BTREE_DATA_VERSION },
102898 #endif
102899 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
102900   { /* zName:     */ "database_list",
102901     /* ePragTyp:  */ PragTyp_DATABASE_LIST,
102902     /* ePragFlag: */ PragFlag_NeedSchema,
102903     /* iArg:      */ 0 },
102904 #endif
102905 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
102906   { /* zName:     */ "default_cache_size",
102907     /* ePragTyp:  */ PragTyp_DEFAULT_CACHE_SIZE,
102908     /* ePragFlag: */ PragFlag_NeedSchema,
102909     /* iArg:      */ 0 },
102910 #endif
102911 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
102912 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
102913   { /* zName:     */ "defer_foreign_keys",
102914     /* ePragTyp:  */ PragTyp_FLAG,
102915     /* ePragFlag: */ 0,
102916     /* iArg:      */ SQLITE_DeferFKs },
102917 #endif
102918 #endif
102919 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
102920   { /* zName:     */ "empty_result_callbacks",
102921     /* ePragTyp:  */ PragTyp_FLAG,
102922     /* ePragFlag: */ 0,
102923     /* iArg:      */ SQLITE_NullCallback },
102924 #endif
102925 #if !defined(SQLITE_OMIT_UTF16)
102926   { /* zName:     */ "encoding",
102927     /* ePragTyp:  */ PragTyp_ENCODING,
102928     /* ePragFlag: */ 0,
102929     /* iArg:      */ 0 },
102930 #endif
102931 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
102932   { /* zName:     */ "foreign_key_check",
102933     /* ePragTyp:  */ PragTyp_FOREIGN_KEY_CHECK,
102934     /* ePragFlag: */ PragFlag_NeedSchema,
102935     /* iArg:      */ 0 },
102936 #endif
102937 #if !defined(SQLITE_OMIT_FOREIGN_KEY)
102938   { /* zName:     */ "foreign_key_list",
102939     /* ePragTyp:  */ PragTyp_FOREIGN_KEY_LIST,
102940     /* ePragFlag: */ PragFlag_NeedSchema,
102941     /* iArg:      */ 0 },
102942 #endif
102943 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
102944 #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
102945   { /* zName:     */ "foreign_keys",
102946     /* ePragTyp:  */ PragTyp_FLAG,
102947     /* ePragFlag: */ 0,
102948     /* iArg:      */ SQLITE_ForeignKeys },
102949 #endif
102950 #endif
102951 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
102952   { /* zName:     */ "freelist_count",
102953     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
102954     /* ePragFlag: */ PragFlag_ReadOnly,
102955     /* iArg:      */ BTREE_FREE_PAGE_COUNT },
102956 #endif
102957 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
102958   { /* zName:     */ "full_column_names",
102959     /* ePragTyp:  */ PragTyp_FLAG,
102960     /* ePragFlag: */ 0,
102961     /* iArg:      */ SQLITE_FullColNames },
102962   { /* zName:     */ "fullfsync",
102963     /* ePragTyp:  */ PragTyp_FLAG,
102964     /* ePragFlag: */ 0,
102965     /* iArg:      */ SQLITE_FullFSync },
102966 #endif
102967 #if defined(SQLITE_HAS_CODEC)
102968   { /* zName:     */ "hexkey",
102969     /* ePragTyp:  */ PragTyp_HEXKEY,
102970     /* ePragFlag: */ 0,
102971     /* iArg:      */ 0 },
102972   { /* zName:     */ "hexrekey",
102973     /* ePragTyp:  */ PragTyp_HEXKEY,
102974     /* ePragFlag: */ 0,
102975     /* iArg:      */ 0 },
102976 #endif
102977 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
102978 #if !defined(SQLITE_OMIT_CHECK)
102979   { /* zName:     */ "ignore_check_constraints",
102980     /* ePragTyp:  */ PragTyp_FLAG,
102981     /* ePragFlag: */ 0,
102982     /* iArg:      */ SQLITE_IgnoreChecks },
102983 #endif
102984 #endif
102985 #if !defined(SQLITE_OMIT_AUTOVACUUM)
102986   { /* zName:     */ "incremental_vacuum",
102987     /* ePragTyp:  */ PragTyp_INCREMENTAL_VACUUM,
102988     /* ePragFlag: */ PragFlag_NeedSchema,
102989     /* iArg:      */ 0 },
102990 #endif
102991 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
102992   { /* zName:     */ "index_info",
102993     /* ePragTyp:  */ PragTyp_INDEX_INFO,
102994     /* ePragFlag: */ PragFlag_NeedSchema,
102995     /* iArg:      */ 0 },
102996   { /* zName:     */ "index_list",
102997     /* ePragTyp:  */ PragTyp_INDEX_LIST,
102998     /* ePragFlag: */ PragFlag_NeedSchema,
102999     /* iArg:      */ 0 },
103000   { /* zName:     */ "index_xinfo",
103001     /* ePragTyp:  */ PragTyp_INDEX_INFO,
103002     /* ePragFlag: */ PragFlag_NeedSchema,
103003     /* iArg:      */ 1 },
103004 #endif
103005 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
103006   { /* zName:     */ "integrity_check",
103007     /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
103008     /* ePragFlag: */ PragFlag_NeedSchema,
103009     /* iArg:      */ 0 },
103010 #endif
103011 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
103012   { /* zName:     */ "journal_mode",
103013     /* ePragTyp:  */ PragTyp_JOURNAL_MODE,
103014     /* ePragFlag: */ PragFlag_NeedSchema,
103015     /* iArg:      */ 0 },
103016   { /* zName:     */ "journal_size_limit",
103017     /* ePragTyp:  */ PragTyp_JOURNAL_SIZE_LIMIT,
103018     /* ePragFlag: */ 0,
103019     /* iArg:      */ 0 },
103020 #endif
103021 #if defined(SQLITE_HAS_CODEC)
103022   { /* zName:     */ "key",
103023     /* ePragTyp:  */ PragTyp_KEY,
103024     /* ePragFlag: */ 0,
103025     /* iArg:      */ 0 },
103026 #endif
103027 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103028   { /* zName:     */ "legacy_file_format",
103029     /* ePragTyp:  */ PragTyp_FLAG,
103030     /* ePragFlag: */ 0,
103031     /* iArg:      */ SQLITE_LegacyFileFmt },
103032 #endif
103033 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
103034   { /* zName:     */ "lock_proxy_file",
103035     /* ePragTyp:  */ PragTyp_LOCK_PROXY_FILE,
103036     /* ePragFlag: */ 0,
103037     /* iArg:      */ 0 },
103038 #endif
103039 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
103040   { /* zName:     */ "lock_status",
103041     /* ePragTyp:  */ PragTyp_LOCK_STATUS,
103042     /* ePragFlag: */ 0,
103043     /* iArg:      */ 0 },
103044 #endif
103045 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
103046   { /* zName:     */ "locking_mode",
103047     /* ePragTyp:  */ PragTyp_LOCKING_MODE,
103048     /* ePragFlag: */ 0,
103049     /* iArg:      */ 0 },
103050   { /* zName:     */ "max_page_count",
103051     /* ePragTyp:  */ PragTyp_PAGE_COUNT,
103052     /* ePragFlag: */ PragFlag_NeedSchema,
103053     /* iArg:      */ 0 },
103054   { /* zName:     */ "mmap_size",
103055     /* ePragTyp:  */ PragTyp_MMAP_SIZE,
103056     /* ePragFlag: */ 0,
103057     /* iArg:      */ 0 },
103058   { /* zName:     */ "page_count",
103059     /* ePragTyp:  */ PragTyp_PAGE_COUNT,
103060     /* ePragFlag: */ PragFlag_NeedSchema,
103061     /* iArg:      */ 0 },
103062   { /* zName:     */ "page_size",
103063     /* ePragTyp:  */ PragTyp_PAGE_SIZE,
103064     /* ePragFlag: */ 0,
103065     /* iArg:      */ 0 },
103066 #endif
103067 #if defined(SQLITE_DEBUG)
103068   { /* zName:     */ "parser_trace",
103069     /* ePragTyp:  */ PragTyp_PARSER_TRACE,
103070     /* ePragFlag: */ 0,
103071     /* iArg:      */ 0 },
103072 #endif
103073 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103074   { /* zName:     */ "query_only",
103075     /* ePragTyp:  */ PragTyp_FLAG,
103076     /* ePragFlag: */ 0,
103077     /* iArg:      */ SQLITE_QueryOnly },
103078 #endif
103079 #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
103080   { /* zName:     */ "quick_check",
103081     /* ePragTyp:  */ PragTyp_INTEGRITY_CHECK,
103082     /* ePragFlag: */ PragFlag_NeedSchema,
103083     /* iArg:      */ 0 },
103084 #endif
103085 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103086   { /* zName:     */ "read_uncommitted",
103087     /* ePragTyp:  */ PragTyp_FLAG,
103088     /* ePragFlag: */ 0,
103089     /* iArg:      */ SQLITE_ReadUncommitted },
103090   { /* zName:     */ "recursive_triggers",
103091     /* ePragTyp:  */ PragTyp_FLAG,
103092     /* ePragFlag: */ 0,
103093     /* iArg:      */ SQLITE_RecTriggers },
103094 #endif
103095 #if defined(SQLITE_HAS_CODEC)
103096   { /* zName:     */ "rekey",
103097     /* ePragTyp:  */ PragTyp_REKEY,
103098     /* ePragFlag: */ 0,
103099     /* iArg:      */ 0 },
103100 #endif
103101 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103102   { /* zName:     */ "reverse_unordered_selects",
103103     /* ePragTyp:  */ PragTyp_FLAG,
103104     /* ePragFlag: */ 0,
103105     /* iArg:      */ SQLITE_ReverseOrder },
103106 #endif
103107 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
103108   { /* zName:     */ "schema_version",
103109     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
103110     /* ePragFlag: */ 0,
103111     /* iArg:      */ BTREE_SCHEMA_VERSION },
103112 #endif
103113 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
103114   { /* zName:     */ "secure_delete",
103115     /* ePragTyp:  */ PragTyp_SECURE_DELETE,
103116     /* ePragFlag: */ 0,
103117     /* iArg:      */ 0 },
103118 #endif
103119 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103120   { /* zName:     */ "short_column_names",
103121     /* ePragTyp:  */ PragTyp_FLAG,
103122     /* ePragFlag: */ 0,
103123     /* iArg:      */ SQLITE_ShortColNames },
103124 #endif
103125   { /* zName:     */ "shrink_memory",
103126     /* ePragTyp:  */ PragTyp_SHRINK_MEMORY,
103127     /* ePragFlag: */ 0,
103128     /* iArg:      */ 0 },
103129   { /* zName:     */ "soft_heap_limit",
103130     /* ePragTyp:  */ PragTyp_SOFT_HEAP_LIMIT,
103131     /* ePragFlag: */ 0,
103132     /* iArg:      */ 0 },
103133 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103134 #if defined(SQLITE_DEBUG)
103135   { /* zName:     */ "sql_trace",
103136     /* ePragTyp:  */ PragTyp_FLAG,
103137     /* ePragFlag: */ 0,
103138     /* iArg:      */ SQLITE_SqlTrace },
103139 #endif
103140 #endif
103141 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
103142   { /* zName:     */ "stats",
103143     /* ePragTyp:  */ PragTyp_STATS,
103144     /* ePragFlag: */ PragFlag_NeedSchema,
103145     /* iArg:      */ 0 },
103146 #endif
103147 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
103148   { /* zName:     */ "synchronous",
103149     /* ePragTyp:  */ PragTyp_SYNCHRONOUS,
103150     /* ePragFlag: */ PragFlag_NeedSchema,
103151     /* iArg:      */ 0 },
103152 #endif
103153 #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
103154   { /* zName:     */ "table_info",
103155     /* ePragTyp:  */ PragTyp_TABLE_INFO,
103156     /* ePragFlag: */ PragFlag_NeedSchema,
103157     /* iArg:      */ 0 },
103158 #endif
103159 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
103160   { /* zName:     */ "temp_store",
103161     /* ePragTyp:  */ PragTyp_TEMP_STORE,
103162     /* ePragFlag: */ 0,
103163     /* iArg:      */ 0 },
103164   { /* zName:     */ "temp_store_directory",
103165     /* ePragTyp:  */ PragTyp_TEMP_STORE_DIRECTORY,
103166     /* ePragFlag: */ 0,
103167     /* iArg:      */ 0 },
103168 #endif
103169   { /* zName:     */ "threads",
103170     /* ePragTyp:  */ PragTyp_THREADS,
103171     /* ePragFlag: */ 0,
103172     /* iArg:      */ 0 },
103173 #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
103174   { /* zName:     */ "user_version",
103175     /* ePragTyp:  */ PragTyp_HEADER_VALUE,
103176     /* ePragFlag: */ 0,
103177     /* iArg:      */ BTREE_USER_VERSION },
103178 #endif
103179 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103180 #if defined(SQLITE_DEBUG)
103181   { /* zName:     */ "vdbe_addoptrace",
103182     /* ePragTyp:  */ PragTyp_FLAG,
103183     /* ePragFlag: */ 0,
103184     /* iArg:      */ SQLITE_VdbeAddopTrace },
103185   { /* zName:     */ "vdbe_debug",
103186     /* ePragTyp:  */ PragTyp_FLAG,
103187     /* ePragFlag: */ 0,
103188     /* iArg:      */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
103189   { /* zName:     */ "vdbe_eqp",
103190     /* ePragTyp:  */ PragTyp_FLAG,
103191     /* ePragFlag: */ 0,
103192     /* iArg:      */ SQLITE_VdbeEQP },
103193   { /* zName:     */ "vdbe_listing",
103194     /* ePragTyp:  */ PragTyp_FLAG,
103195     /* ePragFlag: */ 0,
103196     /* iArg:      */ SQLITE_VdbeListing },
103197   { /* zName:     */ "vdbe_trace",
103198     /* ePragTyp:  */ PragTyp_FLAG,
103199     /* ePragFlag: */ 0,
103200     /* iArg:      */ SQLITE_VdbeTrace },
103201 #endif
103202 #endif
103203 #if !defined(SQLITE_OMIT_WAL)
103204   { /* zName:     */ "wal_autocheckpoint",
103205     /* ePragTyp:  */ PragTyp_WAL_AUTOCHECKPOINT,
103206     /* ePragFlag: */ 0,
103207     /* iArg:      */ 0 },
103208   { /* zName:     */ "wal_checkpoint",
103209     /* ePragTyp:  */ PragTyp_WAL_CHECKPOINT,
103210     /* ePragFlag: */ PragFlag_NeedSchema,
103211     /* iArg:      */ 0 },
103212 #endif
103213 #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
103214   { /* zName:     */ "writable_schema",
103215     /* ePragTyp:  */ PragTyp_FLAG,
103216     /* ePragFlag: */ 0,
103217     /* iArg:      */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
103218 #endif
103219 };
103220 /* Number of pragmas: 59 on by default, 72 total. */
103221
103222 /************** End of pragma.h **********************************************/
103223 /************** Continuing where we left off in pragma.c *********************/
103224
103225 /*
103226 ** Interpret the given string as a safety level.  Return 0 for OFF,
103227 ** 1 for ON or NORMAL and 2 for FULL.  Return 1 for an empty or 
103228 ** unrecognized string argument.  The FULL option is disallowed
103229 ** if the omitFull parameter it 1.
103230 **
103231 ** Note that the values returned are one less that the values that
103232 ** should be passed into sqlite3BtreeSetSafetyLevel().  The is done
103233 ** to support legacy SQL code.  The safety level used to be boolean
103234 ** and older scripts may have used numbers 0 for OFF and 1 for ON.
103235 */
103236 static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
103237                              /* 123456789 123456789 */
103238   static const char zText[] = "onoffalseyestruefull";
103239   static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
103240   static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
103241   static const u8 iValue[] =  {1, 0, 0, 0, 1, 1, 2};
103242   int i, n;
103243   if( sqlite3Isdigit(*z) ){
103244     return (u8)sqlite3Atoi(z);
103245   }
103246   n = sqlite3Strlen30(z);
103247   for(i=0; i<ArraySize(iLength)-omitFull; i++){
103248     if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
103249       return iValue[i];
103250     }
103251   }
103252   return dflt;
103253 }
103254
103255 /*
103256 ** Interpret the given string as a boolean value.
103257 */
103258 SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
103259   return getSafetyLevel(z,1,dflt)!=0;
103260 }
103261
103262 /* The sqlite3GetBoolean() function is used by other modules but the
103263 ** remainder of this file is specific to PRAGMA processing.  So omit
103264 ** the rest of the file if PRAGMAs are omitted from the build.
103265 */
103266 #if !defined(SQLITE_OMIT_PRAGMA)
103267
103268 /*
103269 ** Interpret the given string as a locking mode value.
103270 */
103271 static int getLockingMode(const char *z){
103272   if( z ){
103273     if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
103274     if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
103275   }
103276   return PAGER_LOCKINGMODE_QUERY;
103277 }
103278
103279 #ifndef SQLITE_OMIT_AUTOVACUUM
103280 /*
103281 ** Interpret the given string as an auto-vacuum mode value.
103282 **
103283 ** The following strings, "none", "full" and "incremental" are 
103284 ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
103285 */
103286 static int getAutoVacuum(const char *z){
103287   int i;
103288   if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
103289   if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
103290   if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
103291   i = sqlite3Atoi(z);
103292   return (u8)((i>=0&&i<=2)?i:0);
103293 }
103294 #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
103295
103296 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
103297 /*
103298 ** Interpret the given string as a temp db location. Return 1 for file
103299 ** backed temporary databases, 2 for the Red-Black tree in memory database
103300 ** and 0 to use the compile-time default.
103301 */
103302 static int getTempStore(const char *z){
103303   if( z[0]>='0' && z[0]<='2' ){
103304     return z[0] - '0';
103305   }else if( sqlite3StrICmp(z, "file")==0 ){
103306     return 1;
103307   }else if( sqlite3StrICmp(z, "memory")==0 ){
103308     return 2;
103309   }else{
103310     return 0;
103311   }
103312 }
103313 #endif /* SQLITE_PAGER_PRAGMAS */
103314
103315 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
103316 /*
103317 ** Invalidate temp storage, either when the temp storage is changed
103318 ** from default, or when 'file' and the temp_store_directory has changed
103319 */
103320 static int invalidateTempStorage(Parse *pParse){
103321   sqlite3 *db = pParse->db;
103322   if( db->aDb[1].pBt!=0 ){
103323     if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
103324       sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
103325         "from within a transaction");
103326       return SQLITE_ERROR;
103327     }
103328     sqlite3BtreeClose(db->aDb[1].pBt);
103329     db->aDb[1].pBt = 0;
103330     sqlite3ResetAllSchemasOfConnection(db);
103331   }
103332   return SQLITE_OK;
103333 }
103334 #endif /* SQLITE_PAGER_PRAGMAS */
103335
103336 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
103337 /*
103338 ** If the TEMP database is open, close it and mark the database schema
103339 ** as needing reloading.  This must be done when using the SQLITE_TEMP_STORE
103340 ** or DEFAULT_TEMP_STORE pragmas.
103341 */
103342 static int changeTempStorage(Parse *pParse, const char *zStorageType){
103343   int ts = getTempStore(zStorageType);
103344   sqlite3 *db = pParse->db;
103345   if( db->temp_store==ts ) return SQLITE_OK;
103346   if( invalidateTempStorage( pParse ) != SQLITE_OK ){
103347     return SQLITE_ERROR;
103348   }
103349   db->temp_store = (u8)ts;
103350   return SQLITE_OK;
103351 }
103352 #endif /* SQLITE_PAGER_PRAGMAS */
103353
103354 /*
103355 ** Generate code to return a single integer value.
103356 */
103357 static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
103358   Vdbe *v = sqlite3GetVdbe(pParse);
103359   int mem = ++pParse->nMem;
103360   i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
103361   if( pI64 ){
103362     memcpy(pI64, &value, sizeof(value));
103363   }
103364   sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
103365   sqlite3VdbeSetNumCols(v, 1);
103366   sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
103367   sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
103368 }
103369
103370
103371 /*
103372 ** Set the safety_level and pager flags for pager iDb.  Or if iDb<0
103373 ** set these values for all pagers.
103374 */
103375 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
103376 static void setAllPagerFlags(sqlite3 *db){
103377   if( db->autoCommit ){
103378     Db *pDb = db->aDb;
103379     int n = db->nDb;
103380     assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
103381     assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
103382     assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
103383     assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
103384              ==  PAGER_FLAGS_MASK );
103385     assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
103386     while( (n--) > 0 ){
103387       if( pDb->pBt ){
103388         sqlite3BtreeSetPagerFlags(pDb->pBt,
103389                  pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
103390       }
103391       pDb++;
103392     }
103393   }
103394 }
103395 #else
103396 # define setAllPagerFlags(X)  /* no-op */
103397 #endif
103398
103399
103400 /*
103401 ** Return a human-readable name for a constraint resolution action.
103402 */
103403 #ifndef SQLITE_OMIT_FOREIGN_KEY
103404 static const char *actionName(u8 action){
103405   const char *zName;
103406   switch( action ){
103407     case OE_SetNull:  zName = "SET NULL";        break;
103408     case OE_SetDflt:  zName = "SET DEFAULT";     break;
103409     case OE_Cascade:  zName = "CASCADE";         break;
103410     case OE_Restrict: zName = "RESTRICT";        break;
103411     default:          zName = "NO ACTION";  
103412                       assert( action==OE_None ); break;
103413   }
103414   return zName;
103415 }
103416 #endif
103417
103418
103419 /*
103420 ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
103421 ** defined in pager.h. This function returns the associated lowercase
103422 ** journal-mode name.
103423 */
103424 SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
103425   static char * const azModeName[] = {
103426     "delete", "persist", "off", "truncate", "memory"
103427 #ifndef SQLITE_OMIT_WAL
103428      , "wal"
103429 #endif
103430   };
103431   assert( PAGER_JOURNALMODE_DELETE==0 );
103432   assert( PAGER_JOURNALMODE_PERSIST==1 );
103433   assert( PAGER_JOURNALMODE_OFF==2 );
103434   assert( PAGER_JOURNALMODE_TRUNCATE==3 );
103435   assert( PAGER_JOURNALMODE_MEMORY==4 );
103436   assert( PAGER_JOURNALMODE_WAL==5 );
103437   assert( eMode>=0 && eMode<=ArraySize(azModeName) );
103438
103439   if( eMode==ArraySize(azModeName) ) return 0;
103440   return azModeName[eMode];
103441 }
103442
103443 /*
103444 ** Process a pragma statement.  
103445 **
103446 ** Pragmas are of this form:
103447 **
103448 **      PRAGMA [database.]id [= value]
103449 **
103450 ** The identifier might also be a string.  The value is a string, and
103451 ** identifier, or a number.  If minusFlag is true, then the value is
103452 ** a number that was preceded by a minus sign.
103453 **
103454 ** If the left side is "database.id" then pId1 is the database name
103455 ** and pId2 is the id.  If the left side is just "id" then pId1 is the
103456 ** id and pId2 is any empty string.
103457 */
103458 SQLITE_PRIVATE void sqlite3Pragma(
103459   Parse *pParse, 
103460   Token *pId1,        /* First part of [database.]id field */
103461   Token *pId2,        /* Second part of [database.]id field, or NULL */
103462   Token *pValue,      /* Token for <value>, or NULL */
103463   int minusFlag       /* True if a '-' sign preceded <value> */
103464 ){
103465   char *zLeft = 0;       /* Nul-terminated UTF-8 string <id> */
103466   char *zRight = 0;      /* Nul-terminated UTF-8 string <value>, or NULL */
103467   const char *zDb = 0;   /* The database name */
103468   Token *pId;            /* Pointer to <id> token */
103469   char *aFcntl[4];       /* Argument to SQLITE_FCNTL_PRAGMA */
103470   int iDb;               /* Database index for <database> */
103471   int lwr, upr, mid = 0;       /* Binary search bounds */
103472   int rc;                      /* return value form SQLITE_FCNTL_PRAGMA */
103473   sqlite3 *db = pParse->db;    /* The database connection */
103474   Db *pDb;                     /* The specific database being pragmaed */
103475   Vdbe *v = sqlite3GetVdbe(pParse);  /* Prepared statement */
103476   const struct sPragmaNames *pPragma;
103477
103478   if( v==0 ) return;
103479   sqlite3VdbeRunOnlyOnce(v);
103480   pParse->nMem = 2;
103481
103482   /* Interpret the [database.] part of the pragma statement. iDb is the
103483   ** index of the database this pragma is being applied to in db.aDb[]. */
103484   iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
103485   if( iDb<0 ) return;
103486   pDb = &db->aDb[iDb];
103487
103488   /* If the temp database has been explicitly named as part of the 
103489   ** pragma, make sure it is open. 
103490   */
103491   if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
103492     return;
103493   }
103494
103495   zLeft = sqlite3NameFromToken(db, pId);
103496   if( !zLeft ) return;
103497   if( minusFlag ){
103498     zRight = sqlite3MPrintf(db, "-%T", pValue);
103499   }else{
103500     zRight = sqlite3NameFromToken(db, pValue);
103501   }
103502
103503   assert( pId2 );
103504   zDb = pId2->n>0 ? pDb->zName : 0;
103505   if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
103506     goto pragma_out;
103507   }
103508
103509   /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
103510   ** connection.  If it returns SQLITE_OK, then assume that the VFS
103511   ** handled the pragma and generate a no-op prepared statement.
103512   **
103513   ** IMPLEMENTATION-OF: R-12238-55120 Whenever a PRAGMA statement is parsed,
103514   ** an SQLITE_FCNTL_PRAGMA file control is sent to the open sqlite3_file
103515   ** object corresponding to the database file to which the pragma
103516   ** statement refers.
103517   **
103518   ** IMPLEMENTATION-OF: R-29875-31678 The argument to the SQLITE_FCNTL_PRAGMA
103519   ** file control is an array of pointers to strings (char**) in which the
103520   ** second element of the array is the name of the pragma and the third
103521   ** element is the argument to the pragma or NULL if the pragma has no
103522   ** argument.
103523   */
103524   aFcntl[0] = 0;
103525   aFcntl[1] = zLeft;
103526   aFcntl[2] = zRight;
103527   aFcntl[3] = 0;
103528   db->busyHandler.nBusy = 0;
103529   rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
103530   if( rc==SQLITE_OK ){
103531     if( aFcntl[0] ){
103532       int mem = ++pParse->nMem;
103533       sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
103534       sqlite3VdbeSetNumCols(v, 1);
103535       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
103536       sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
103537       sqlite3_free(aFcntl[0]);
103538     }
103539     goto pragma_out;
103540   }
103541   if( rc!=SQLITE_NOTFOUND ){
103542     if( aFcntl[0] ){
103543       sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
103544       sqlite3_free(aFcntl[0]);
103545     }
103546     pParse->nErr++;
103547     pParse->rc = rc;
103548     goto pragma_out;
103549   }
103550
103551   /* Locate the pragma in the lookup table */
103552   lwr = 0;
103553   upr = ArraySize(aPragmaNames)-1;
103554   while( lwr<=upr ){
103555     mid = (lwr+upr)/2;
103556     rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
103557     if( rc==0 ) break;
103558     if( rc<0 ){
103559       upr = mid - 1;
103560     }else{
103561       lwr = mid + 1;
103562     }
103563   }
103564   if( lwr>upr ) goto pragma_out;
103565   pPragma = &aPragmaNames[mid];
103566
103567   /* Make sure the database schema is loaded if the pragma requires that */
103568   if( (pPragma->mPragFlag & PragFlag_NeedSchema)!=0 ){
103569     if( sqlite3ReadSchema(pParse) ) goto pragma_out;
103570   }
103571
103572   /* Jump to the appropriate pragma handler */
103573   switch( pPragma->ePragTyp ){
103574   
103575 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
103576   /*
103577   **  PRAGMA [database.]default_cache_size
103578   **  PRAGMA [database.]default_cache_size=N
103579   **
103580   ** The first form reports the current persistent setting for the
103581   ** page cache size.  The value returned is the maximum number of
103582   ** pages in the page cache.  The second form sets both the current
103583   ** page cache size value and the persistent page cache size value
103584   ** stored in the database file.
103585   **
103586   ** Older versions of SQLite would set the default cache size to a
103587   ** negative number to indicate synchronous=OFF.  These days, synchronous
103588   ** is always on by default regardless of the sign of the default cache
103589   ** size.  But continue to take the absolute value of the default cache
103590   ** size of historical compatibility.
103591   */
103592   case PragTyp_DEFAULT_CACHE_SIZE: {
103593     static const int iLn = VDBE_OFFSET_LINENO(2);
103594     static const VdbeOpList getCacheSize[] = {
103595       { OP_Transaction, 0, 0,        0},                         /* 0 */
103596       { OP_ReadCookie,  0, 1,        BTREE_DEFAULT_CACHE_SIZE},  /* 1 */
103597       { OP_IfPos,       1, 8,        0},
103598       { OP_Integer,     0, 2,        0},
103599       { OP_Subtract,    1, 2,        1},
103600       { OP_IfPos,       1, 8,        0},
103601       { OP_Integer,     0, 1,        0},                         /* 6 */
103602       { OP_Noop,        0, 0,        0},
103603       { OP_ResultRow,   1, 1,        0},
103604     };
103605     int addr;
103606     sqlite3VdbeUsesBtree(v, iDb);
103607     if( !zRight ){
103608       sqlite3VdbeSetNumCols(v, 1);
103609       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
103610       pParse->nMem += 2;
103611       addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize,iLn);
103612       sqlite3VdbeChangeP1(v, addr, iDb);
103613       sqlite3VdbeChangeP1(v, addr+1, iDb);
103614       sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
103615     }else{
103616       int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
103617       sqlite3BeginWriteOperation(pParse, 0, iDb);
103618       sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
103619       sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
103620       assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
103621       pDb->pSchema->cache_size = size;
103622       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
103623     }
103624     break;
103625   }
103626 #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
103627
103628 #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
103629   /*
103630   **  PRAGMA [database.]page_size
103631   **  PRAGMA [database.]page_size=N
103632   **
103633   ** The first form reports the current setting for the
103634   ** database page size in bytes.  The second form sets the
103635   ** database page size value.  The value can only be set if
103636   ** the database has not yet been created.
103637   */
103638   case PragTyp_PAGE_SIZE: {
103639     Btree *pBt = pDb->pBt;
103640     assert( pBt!=0 );
103641     if( !zRight ){
103642       int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
103643       returnSingleInt(pParse, "page_size", size);
103644     }else{
103645       /* Malloc may fail when setting the page-size, as there is an internal
103646       ** buffer that the pager module resizes using sqlite3_realloc().
103647       */
103648       db->nextPagesize = sqlite3Atoi(zRight);
103649       if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
103650         db->mallocFailed = 1;
103651       }
103652     }
103653     break;
103654   }
103655
103656   /*
103657   **  PRAGMA [database.]secure_delete
103658   **  PRAGMA [database.]secure_delete=ON/OFF
103659   **
103660   ** The first form reports the current setting for the
103661   ** secure_delete flag.  The second form changes the secure_delete
103662   ** flag setting and reports thenew value.
103663   */
103664   case PragTyp_SECURE_DELETE: {
103665     Btree *pBt = pDb->pBt;
103666     int b = -1;
103667     assert( pBt!=0 );
103668     if( zRight ){
103669       b = sqlite3GetBoolean(zRight, 0);
103670     }
103671     if( pId2->n==0 && b>=0 ){
103672       int ii;
103673       for(ii=0; ii<db->nDb; ii++){
103674         sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
103675       }
103676     }
103677     b = sqlite3BtreeSecureDelete(pBt, b);
103678     returnSingleInt(pParse, "secure_delete", b);
103679     break;
103680   }
103681
103682   /*
103683   **  PRAGMA [database.]max_page_count
103684   **  PRAGMA [database.]max_page_count=N
103685   **
103686   ** The first form reports the current setting for the
103687   ** maximum number of pages in the database file.  The 
103688   ** second form attempts to change this setting.  Both
103689   ** forms return the current setting.
103690   **
103691   ** The absolute value of N is used.  This is undocumented and might
103692   ** change.  The only purpose is to provide an easy way to test
103693   ** the sqlite3AbsInt32() function.
103694   **
103695   **  PRAGMA [database.]page_count
103696   **
103697   ** Return the number of pages in the specified database.
103698   */
103699   case PragTyp_PAGE_COUNT: {
103700     int iReg;
103701     sqlite3CodeVerifySchema(pParse, iDb);
103702     iReg = ++pParse->nMem;
103703     if( sqlite3Tolower(zLeft[0])=='p' ){
103704       sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
103705     }else{
103706       sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg, 
103707                         sqlite3AbsInt32(sqlite3Atoi(zRight)));
103708     }
103709     sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
103710     sqlite3VdbeSetNumCols(v, 1);
103711     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
103712     break;
103713   }
103714
103715   /*
103716   **  PRAGMA [database.]locking_mode
103717   **  PRAGMA [database.]locking_mode = (normal|exclusive)
103718   */
103719   case PragTyp_LOCKING_MODE: {
103720     const char *zRet = "normal";
103721     int eMode = getLockingMode(zRight);
103722
103723     if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
103724       /* Simple "PRAGMA locking_mode;" statement. This is a query for
103725       ** the current default locking mode (which may be different to
103726       ** the locking-mode of the main database).
103727       */
103728       eMode = db->dfltLockMode;
103729     }else{
103730       Pager *pPager;
103731       if( pId2->n==0 ){
103732         /* This indicates that no database name was specified as part
103733         ** of the PRAGMA command. In this case the locking-mode must be
103734         ** set on all attached databases, as well as the main db file.
103735         **
103736         ** Also, the sqlite3.dfltLockMode variable is set so that
103737         ** any subsequently attached databases also use the specified
103738         ** locking mode.
103739         */
103740         int ii;
103741         assert(pDb==&db->aDb[0]);
103742         for(ii=2; ii<db->nDb; ii++){
103743           pPager = sqlite3BtreePager(db->aDb[ii].pBt);
103744           sqlite3PagerLockingMode(pPager, eMode);
103745         }
103746         db->dfltLockMode = (u8)eMode;
103747       }
103748       pPager = sqlite3BtreePager(pDb->pBt);
103749       eMode = sqlite3PagerLockingMode(pPager, eMode);
103750     }
103751
103752     assert( eMode==PAGER_LOCKINGMODE_NORMAL
103753             || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
103754     if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
103755       zRet = "exclusive";
103756     }
103757     sqlite3VdbeSetNumCols(v, 1);
103758     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
103759     sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
103760     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
103761     break;
103762   }
103763
103764   /*
103765   **  PRAGMA [database.]journal_mode
103766   **  PRAGMA [database.]journal_mode =
103767   **                      (delete|persist|off|truncate|memory|wal|off)
103768   */
103769   case PragTyp_JOURNAL_MODE: {
103770     int eMode;        /* One of the PAGER_JOURNALMODE_XXX symbols */
103771     int ii;           /* Loop counter */
103772
103773     sqlite3VdbeSetNumCols(v, 1);
103774     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
103775
103776     if( zRight==0 ){
103777       /* If there is no "=MODE" part of the pragma, do a query for the
103778       ** current mode */
103779       eMode = PAGER_JOURNALMODE_QUERY;
103780     }else{
103781       const char *zMode;
103782       int n = sqlite3Strlen30(zRight);
103783       for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
103784         if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
103785       }
103786       if( !zMode ){
103787         /* If the "=MODE" part does not match any known journal mode,
103788         ** then do a query */
103789         eMode = PAGER_JOURNALMODE_QUERY;
103790       }
103791     }
103792     if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
103793       /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
103794       iDb = 0;
103795       pId2->n = 1;
103796     }
103797     for(ii=db->nDb-1; ii>=0; ii--){
103798       if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
103799         sqlite3VdbeUsesBtree(v, ii);
103800         sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
103801       }
103802     }
103803     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
103804     break;
103805   }
103806
103807   /*
103808   **  PRAGMA [database.]journal_size_limit
103809   **  PRAGMA [database.]journal_size_limit=N
103810   **
103811   ** Get or set the size limit on rollback journal files.
103812   */
103813   case PragTyp_JOURNAL_SIZE_LIMIT: {
103814     Pager *pPager = sqlite3BtreePager(pDb->pBt);
103815     i64 iLimit = -2;
103816     if( zRight ){
103817       sqlite3DecOrHexToI64(zRight, &iLimit);
103818       if( iLimit<-1 ) iLimit = -1;
103819     }
103820     iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
103821     returnSingleInt(pParse, "journal_size_limit", iLimit);
103822     break;
103823   }
103824
103825 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
103826
103827   /*
103828   **  PRAGMA [database.]auto_vacuum
103829   **  PRAGMA [database.]auto_vacuum=N
103830   **
103831   ** Get or set the value of the database 'auto-vacuum' parameter.
103832   ** The value is one of:  0 NONE 1 FULL 2 INCREMENTAL
103833   */
103834 #ifndef SQLITE_OMIT_AUTOVACUUM
103835   case PragTyp_AUTO_VACUUM: {
103836     Btree *pBt = pDb->pBt;
103837     assert( pBt!=0 );
103838     if( !zRight ){
103839       returnSingleInt(pParse, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
103840     }else{
103841       int eAuto = getAutoVacuum(zRight);
103842       assert( eAuto>=0 && eAuto<=2 );
103843       db->nextAutovac = (u8)eAuto;
103844       /* Call SetAutoVacuum() to set initialize the internal auto and
103845       ** incr-vacuum flags. This is required in case this connection
103846       ** creates the database file. It is important that it is created
103847       ** as an auto-vacuum capable db.
103848       */
103849       rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
103850       if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
103851         /* When setting the auto_vacuum mode to either "full" or 
103852         ** "incremental", write the value of meta[6] in the database
103853         ** file. Before writing to meta[6], check that meta[3] indicates
103854         ** that this really is an auto-vacuum capable database.
103855         */
103856         static const int iLn = VDBE_OFFSET_LINENO(2);
103857         static const VdbeOpList setMeta6[] = {
103858           { OP_Transaction,    0,         1,                 0},    /* 0 */
103859           { OP_ReadCookie,     0,         1,         BTREE_LARGEST_ROOT_PAGE},
103860           { OP_If,             1,         0,                 0},    /* 2 */
103861           { OP_Halt,           SQLITE_OK, OE_Abort,          0},    /* 3 */
103862           { OP_Integer,        0,         1,                 0},    /* 4 */
103863           { OP_SetCookie,      0,         BTREE_INCR_VACUUM, 1},    /* 5 */
103864         };
103865         int iAddr;
103866         iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
103867         sqlite3VdbeChangeP1(v, iAddr, iDb);
103868         sqlite3VdbeChangeP1(v, iAddr+1, iDb);
103869         sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
103870         sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
103871         sqlite3VdbeChangeP1(v, iAddr+5, iDb);
103872         sqlite3VdbeUsesBtree(v, iDb);
103873       }
103874     }
103875     break;
103876   }
103877 #endif
103878
103879   /*
103880   **  PRAGMA [database.]incremental_vacuum(N)
103881   **
103882   ** Do N steps of incremental vacuuming on a database.
103883   */
103884 #ifndef SQLITE_OMIT_AUTOVACUUM
103885   case PragTyp_INCREMENTAL_VACUUM: {
103886     int iLimit, addr;
103887     if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
103888       iLimit = 0x7fffffff;
103889     }
103890     sqlite3BeginWriteOperation(pParse, 0, iDb);
103891     sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
103892     addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
103893     sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
103894     sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
103895     sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
103896     sqlite3VdbeJumpHere(v, addr);
103897     break;
103898   }
103899 #endif
103900
103901 #ifndef SQLITE_OMIT_PAGER_PRAGMAS
103902   /*
103903   **  PRAGMA [database.]cache_size
103904   **  PRAGMA [database.]cache_size=N
103905   **
103906   ** The first form reports the current local setting for the
103907   ** page cache size. The second form sets the local
103908   ** page cache size value.  If N is positive then that is the
103909   ** number of pages in the cache.  If N is negative, then the
103910   ** number of pages is adjusted so that the cache uses -N kibibytes
103911   ** of memory.
103912   */
103913   case PragTyp_CACHE_SIZE: {
103914     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
103915     if( !zRight ){
103916       returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
103917     }else{
103918       int size = sqlite3Atoi(zRight);
103919       pDb->pSchema->cache_size = size;
103920       sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
103921     }
103922     break;
103923   }
103924
103925   /*
103926   **  PRAGMA [database.]mmap_size(N)
103927   **
103928   ** Used to set mapping size limit. The mapping size limit is
103929   ** used to limit the aggregate size of all memory mapped regions of the
103930   ** database file. If this parameter is set to zero, then memory mapping
103931   ** is not used at all.  If N is negative, then the default memory map
103932   ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
103933   ** The parameter N is measured in bytes.
103934   **
103935   ** This value is advisory.  The underlying VFS is free to memory map
103936   ** as little or as much as it wants.  Except, if N is set to 0 then the
103937   ** upper layers will never invoke the xFetch interfaces to the VFS.
103938   */
103939   case PragTyp_MMAP_SIZE: {
103940     sqlite3_int64 sz;
103941 #if SQLITE_MAX_MMAP_SIZE>0
103942     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
103943     if( zRight ){
103944       int ii;
103945       sqlite3DecOrHexToI64(zRight, &sz);
103946       if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
103947       if( pId2->n==0 ) db->szMmap = sz;
103948       for(ii=db->nDb-1; ii>=0; ii--){
103949         if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
103950           sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
103951         }
103952       }
103953     }
103954     sz = -1;
103955     rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
103956 #else
103957     sz = 0;
103958     rc = SQLITE_OK;
103959 #endif
103960     if( rc==SQLITE_OK ){
103961       returnSingleInt(pParse, "mmap_size", sz);
103962     }else if( rc!=SQLITE_NOTFOUND ){
103963       pParse->nErr++;
103964       pParse->rc = rc;
103965     }
103966     break;
103967   }
103968
103969   /*
103970   **   PRAGMA temp_store
103971   **   PRAGMA temp_store = "default"|"memory"|"file"
103972   **
103973   ** Return or set the local value of the temp_store flag.  Changing
103974   ** the local value does not make changes to the disk file and the default
103975   ** value will be restored the next time the database is opened.
103976   **
103977   ** Note that it is possible for the library compile-time options to
103978   ** override this setting
103979   */
103980   case PragTyp_TEMP_STORE: {
103981     if( !zRight ){
103982       returnSingleInt(pParse, "temp_store", db->temp_store);
103983     }else{
103984       changeTempStorage(pParse, zRight);
103985     }
103986     break;
103987   }
103988
103989   /*
103990   **   PRAGMA temp_store_directory
103991   **   PRAGMA temp_store_directory = ""|"directory_name"
103992   **
103993   ** Return or set the local value of the temp_store_directory flag.  Changing
103994   ** the value sets a specific directory to be used for temporary files.
103995   ** Setting to a null string reverts to the default temporary directory search.
103996   ** If temporary directory is changed, then invalidateTempStorage.
103997   **
103998   */
103999   case PragTyp_TEMP_STORE_DIRECTORY: {
104000     if( !zRight ){
104001       if( sqlite3_temp_directory ){
104002         sqlite3VdbeSetNumCols(v, 1);
104003         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
104004             "temp_store_directory", SQLITE_STATIC);
104005         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
104006         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
104007       }
104008     }else{
104009 #ifndef SQLITE_OMIT_WSD
104010       if( zRight[0] ){
104011         int res;
104012         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
104013         if( rc!=SQLITE_OK || res==0 ){
104014           sqlite3ErrorMsg(pParse, "not a writable directory");
104015           goto pragma_out;
104016         }
104017       }
104018       if( SQLITE_TEMP_STORE==0
104019        || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
104020        || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
104021       ){
104022         invalidateTempStorage(pParse);
104023       }
104024       sqlite3_free(sqlite3_temp_directory);
104025       if( zRight[0] ){
104026         sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
104027       }else{
104028         sqlite3_temp_directory = 0;
104029       }
104030 #endif /* SQLITE_OMIT_WSD */
104031     }
104032     break;
104033   }
104034
104035 #if SQLITE_OS_WIN
104036   /*
104037   **   PRAGMA data_store_directory
104038   **   PRAGMA data_store_directory = ""|"directory_name"
104039   **
104040   ** Return or set the local value of the data_store_directory flag.  Changing
104041   ** the value sets a specific directory to be used for database files that
104042   ** were specified with a relative pathname.  Setting to a null string reverts
104043   ** to the default database directory, which for database files specified with
104044   ** a relative path will probably be based on the current directory for the
104045   ** process.  Database file specified with an absolute path are not impacted
104046   ** by this setting, regardless of its value.
104047   **
104048   */
104049   case PragTyp_DATA_STORE_DIRECTORY: {
104050     if( !zRight ){
104051       if( sqlite3_data_directory ){
104052         sqlite3VdbeSetNumCols(v, 1);
104053         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
104054             "data_store_directory", SQLITE_STATIC);
104055         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
104056         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
104057       }
104058     }else{
104059 #ifndef SQLITE_OMIT_WSD
104060       if( zRight[0] ){
104061         int res;
104062         rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
104063         if( rc!=SQLITE_OK || res==0 ){
104064           sqlite3ErrorMsg(pParse, "not a writable directory");
104065           goto pragma_out;
104066         }
104067       }
104068       sqlite3_free(sqlite3_data_directory);
104069       if( zRight[0] ){
104070         sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
104071       }else{
104072         sqlite3_data_directory = 0;
104073       }
104074 #endif /* SQLITE_OMIT_WSD */
104075     }
104076     break;
104077   }
104078 #endif
104079
104080 #if SQLITE_ENABLE_LOCKING_STYLE
104081   /*
104082   **   PRAGMA [database.]lock_proxy_file
104083   **   PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
104084   **
104085   ** Return or set the value of the lock_proxy_file flag.  Changing
104086   ** the value sets a specific file to be used for database access locks.
104087   **
104088   */
104089   case PragTyp_LOCK_PROXY_FILE: {
104090     if( !zRight ){
104091       Pager *pPager = sqlite3BtreePager(pDb->pBt);
104092       char *proxy_file_path = NULL;
104093       sqlite3_file *pFile = sqlite3PagerFile(pPager);
104094       sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE, 
104095                            &proxy_file_path);
104096       
104097       if( proxy_file_path ){
104098         sqlite3VdbeSetNumCols(v, 1);
104099         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, 
104100                               "lock_proxy_file", SQLITE_STATIC);
104101         sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
104102         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
104103       }
104104     }else{
104105       Pager *pPager = sqlite3BtreePager(pDb->pBt);
104106       sqlite3_file *pFile = sqlite3PagerFile(pPager);
104107       int res;
104108       if( zRight[0] ){
104109         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
104110                                      zRight);
104111       } else {
104112         res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE, 
104113                                      NULL);
104114       }
104115       if( res!=SQLITE_OK ){
104116         sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
104117         goto pragma_out;
104118       }
104119     }
104120     break;
104121   }
104122 #endif /* SQLITE_ENABLE_LOCKING_STYLE */      
104123     
104124   /*
104125   **   PRAGMA [database.]synchronous
104126   **   PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
104127   **
104128   ** Return or set the local value of the synchronous flag.  Changing
104129   ** the local value does not make changes to the disk file and the
104130   ** default value will be restored the next time the database is
104131   ** opened.
104132   */
104133   case PragTyp_SYNCHRONOUS: {
104134     if( !zRight ){
104135       returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
104136     }else{
104137       if( !db->autoCommit ){
104138         sqlite3ErrorMsg(pParse, 
104139             "Safety level may not be changed inside a transaction");
104140       }else{
104141         pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
104142         setAllPagerFlags(db);
104143       }
104144     }
104145     break;
104146   }
104147 #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
104148
104149 #ifndef SQLITE_OMIT_FLAG_PRAGMAS
104150   case PragTyp_FLAG: {
104151     if( zRight==0 ){
104152       returnSingleInt(pParse, pPragma->zName, (db->flags & pPragma->iArg)!=0 );
104153     }else{
104154       int mask = pPragma->iArg;    /* Mask of bits to set or clear. */
104155       if( db->autoCommit==0 ){
104156         /* Foreign key support may not be enabled or disabled while not
104157         ** in auto-commit mode.  */
104158         mask &= ~(SQLITE_ForeignKeys);
104159       }
104160 #if SQLITE_USER_AUTHENTICATION
104161       if( db->auth.authLevel==UAUTH_User ){
104162         /* Do not allow non-admin users to modify the schema arbitrarily */
104163         mask &= ~(SQLITE_WriteSchema);
104164       }
104165 #endif
104166
104167       if( sqlite3GetBoolean(zRight, 0) ){
104168         db->flags |= mask;
104169       }else{
104170         db->flags &= ~mask;
104171         if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
104172       }
104173
104174       /* Many of the flag-pragmas modify the code generated by the SQL 
104175       ** compiler (eg. count_changes). So add an opcode to expire all
104176       ** compiled SQL statements after modifying a pragma value.
104177       */
104178       sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
104179       setAllPagerFlags(db);
104180     }
104181     break;
104182   }
104183 #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
104184
104185 #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
104186   /*
104187   **   PRAGMA table_info(<table>)
104188   **
104189   ** Return a single row for each column of the named table. The columns of
104190   ** the returned data set are:
104191   **
104192   ** cid:        Column id (numbered from left to right, starting at 0)
104193   ** name:       Column name
104194   ** type:       Column declaration type.
104195   ** notnull:    True if 'NOT NULL' is part of column declaration
104196   ** dflt_value: The default value for the column, if any.
104197   */
104198   case PragTyp_TABLE_INFO: if( zRight ){
104199     Table *pTab;
104200     pTab = sqlite3FindTable(db, zRight, zDb);
104201     if( pTab ){
104202       int i, k;
104203       int nHidden = 0;
104204       Column *pCol;
104205       Index *pPk = sqlite3PrimaryKeyIndex(pTab);
104206       sqlite3VdbeSetNumCols(v, 6);
104207       pParse->nMem = 6;
104208       sqlite3CodeVerifySchema(pParse, iDb);
104209       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
104210       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
104211       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
104212       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
104213       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
104214       sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
104215       sqlite3ViewGetColumnNames(pParse, pTab);
104216       for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
104217         if( IsHiddenColumn(pCol) ){
104218           nHidden++;
104219           continue;
104220         }
104221         sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
104222         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
104223         sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
104224            pCol->zType ? pCol->zType : "", 0);
104225         sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
104226         if( pCol->zDflt ){
104227           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
104228         }else{
104229           sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
104230         }
104231         if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
104232           k = 0;
104233         }else if( pPk==0 ){
104234           k = 1;
104235         }else{
104236           for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){}
104237         }
104238         sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
104239         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
104240       }
104241     }
104242   }
104243   break;
104244
104245   case PragTyp_STATS: {
104246     Index *pIdx;
104247     HashElem *i;
104248     v = sqlite3GetVdbe(pParse);
104249     sqlite3VdbeSetNumCols(v, 4);
104250     pParse->nMem = 4;
104251     sqlite3CodeVerifySchema(pParse, iDb);
104252     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
104253     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "index", SQLITE_STATIC);
104254     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "width", SQLITE_STATIC);
104255     sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "height", SQLITE_STATIC);
104256     for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
104257       Table *pTab = sqliteHashData(i);
104258       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, pTab->zName, 0);
104259       sqlite3VdbeAddOp2(v, OP_Null, 0, 2);
104260       sqlite3VdbeAddOp2(v, OP_Integer,
104261                            (int)sqlite3LogEstToInt(pTab->szTabRow), 3);
104262       sqlite3VdbeAddOp2(v, OP_Integer, 
104263           (int)sqlite3LogEstToInt(pTab->nRowLogEst), 4);
104264       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
104265       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
104266         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
104267         sqlite3VdbeAddOp2(v, OP_Integer,
104268                              (int)sqlite3LogEstToInt(pIdx->szIdxRow), 3);
104269         sqlite3VdbeAddOp2(v, OP_Integer, 
104270             (int)sqlite3LogEstToInt(pIdx->aiRowLogEst[0]), 4);
104271         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
104272       }
104273     }
104274   }
104275   break;
104276
104277   case PragTyp_INDEX_INFO: if( zRight ){
104278     Index *pIdx;
104279     Table *pTab;
104280     pIdx = sqlite3FindIndex(db, zRight, zDb);
104281     if( pIdx ){
104282       int i;
104283       int mx;
104284       if( pPragma->iArg ){
104285         /* PRAGMA index_xinfo (newer version with more rows and columns) */
104286         mx = pIdx->nColumn;
104287         pParse->nMem = 6;
104288       }else{
104289         /* PRAGMA index_info (legacy version) */
104290         mx = pIdx->nKeyCol;
104291         pParse->nMem = 3;
104292       }
104293       pTab = pIdx->pTable;
104294       sqlite3VdbeSetNumCols(v, pParse->nMem);
104295       sqlite3CodeVerifySchema(pParse, iDb);
104296       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
104297       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
104298       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
104299       if( pPragma->iArg ){
104300         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "desc", SQLITE_STATIC);
104301         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "coll", SQLITE_STATIC);
104302         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "key", SQLITE_STATIC);
104303       }
104304       for(i=0; i<mx; i++){
104305         i16 cnum = pIdx->aiColumn[i];
104306         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
104307         sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
104308         if( cnum<0 ){
104309           sqlite3VdbeAddOp2(v, OP_Null, 0, 3);
104310         }else{
104311           sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
104312         }
104313         if( pPragma->iArg ){
104314           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->aSortOrder[i], 4);
104315           sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, pIdx->azColl[i], 0);
104316           sqlite3VdbeAddOp2(v, OP_Integer, i<pIdx->nKeyCol, 6);
104317         }
104318         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, pParse->nMem);
104319       }
104320     }
104321   }
104322   break;
104323
104324   case PragTyp_INDEX_LIST: if( zRight ){
104325     Index *pIdx;
104326     Table *pTab;
104327     int i;
104328     pTab = sqlite3FindTable(db, zRight, zDb);
104329     if( pTab ){
104330       v = sqlite3GetVdbe(pParse);
104331       sqlite3VdbeSetNumCols(v, 5);
104332       pParse->nMem = 5;
104333       sqlite3CodeVerifySchema(pParse, iDb);
104334       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
104335       sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
104336       sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
104337       sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "origin", SQLITE_STATIC);
104338       sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "partial", SQLITE_STATIC);
104339       for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
104340         const char *azOrigin[] = { "c", "u", "pk" };
104341         sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
104342         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
104343         sqlite3VdbeAddOp2(v, OP_Integer, IsUniqueIndex(pIdx), 3);
104344         sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0, azOrigin[pIdx->idxType], 0);
104345         sqlite3VdbeAddOp2(v, OP_Integer, pIdx->pPartIdxWhere!=0, 5);
104346         sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 5);
104347       }
104348     }
104349   }
104350   break;
104351
104352   case PragTyp_DATABASE_LIST: {
104353     int i;
104354     sqlite3VdbeSetNumCols(v, 3);
104355     pParse->nMem = 3;
104356     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
104357     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
104358     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
104359     for(i=0; i<db->nDb; i++){
104360       if( db->aDb[i].pBt==0 ) continue;
104361       assert( db->aDb[i].zName!=0 );
104362       sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
104363       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
104364       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
104365            sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
104366       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
104367     }
104368   }
104369   break;
104370
104371   case PragTyp_COLLATION_LIST: {
104372     int i = 0;
104373     HashElem *p;
104374     sqlite3VdbeSetNumCols(v, 2);
104375     pParse->nMem = 2;
104376     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
104377     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
104378     for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
104379       CollSeq *pColl = (CollSeq *)sqliteHashData(p);
104380       sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
104381       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
104382       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
104383     }
104384   }
104385   break;
104386 #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
104387
104388 #ifndef SQLITE_OMIT_FOREIGN_KEY
104389   case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
104390     FKey *pFK;
104391     Table *pTab;
104392     pTab = sqlite3FindTable(db, zRight, zDb);
104393     if( pTab ){
104394       v = sqlite3GetVdbe(pParse);
104395       pFK = pTab->pFKey;
104396       if( pFK ){
104397         int i = 0; 
104398         sqlite3VdbeSetNumCols(v, 8);
104399         pParse->nMem = 8;
104400         sqlite3CodeVerifySchema(pParse, iDb);
104401         sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
104402         sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
104403         sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
104404         sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
104405         sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
104406         sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
104407         sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
104408         sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
104409         while(pFK){
104410           int j;
104411           for(j=0; j<pFK->nCol; j++){
104412             char *zCol = pFK->aCol[j].zCol;
104413             char *zOnDelete = (char *)actionName(pFK->aAction[0]);
104414             char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
104415             sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
104416             sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
104417             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
104418             sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
104419                               pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
104420             sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
104421             sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
104422             sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
104423             sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
104424             sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
104425           }
104426           ++i;
104427           pFK = pFK->pNextFrom;
104428         }
104429       }
104430     }
104431   }
104432   break;
104433 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
104434
104435 #ifndef SQLITE_OMIT_FOREIGN_KEY
104436 #ifndef SQLITE_OMIT_TRIGGER
104437   case PragTyp_FOREIGN_KEY_CHECK: {
104438     FKey *pFK;             /* A foreign key constraint */
104439     Table *pTab;           /* Child table contain "REFERENCES" keyword */
104440     Table *pParent;        /* Parent table that child points to */
104441     Index *pIdx;           /* Index in the parent table */
104442     int i;                 /* Loop counter:  Foreign key number for pTab */
104443     int j;                 /* Loop counter:  Field of the foreign key */
104444     HashElem *k;           /* Loop counter:  Next table in schema */
104445     int x;                 /* result variable */
104446     int regResult;         /* 3 registers to hold a result row */
104447     int regKey;            /* Register to hold key for checking the FK */
104448     int regRow;            /* Registers to hold a row from pTab */
104449     int addrTop;           /* Top of a loop checking foreign keys */
104450     int addrOk;            /* Jump here if the key is OK */
104451     int *aiCols;           /* child to parent column mapping */
104452
104453     regResult = pParse->nMem+1;
104454     pParse->nMem += 4;
104455     regKey = ++pParse->nMem;
104456     regRow = ++pParse->nMem;
104457     v = sqlite3GetVdbe(pParse);
104458     sqlite3VdbeSetNumCols(v, 4);
104459     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
104460     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
104461     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
104462     sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
104463     sqlite3CodeVerifySchema(pParse, iDb);
104464     k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
104465     while( k ){
104466       if( zRight ){
104467         pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
104468         k = 0;
104469       }else{
104470         pTab = (Table*)sqliteHashData(k);
104471         k = sqliteHashNext(k);
104472       }
104473       if( pTab==0 || pTab->pFKey==0 ) continue;
104474       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
104475       if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
104476       sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
104477       sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
104478                         P4_TRANSIENT);
104479       for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
104480         pParent = sqlite3FindTable(db, pFK->zTo, zDb);
104481         if( pParent==0 ) continue;
104482         pIdx = 0;
104483         sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
104484         x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
104485         if( x==0 ){
104486           if( pIdx==0 ){
104487             sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
104488           }else{
104489             sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
104490             sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
104491           }
104492         }else{
104493           k = 0;
104494           break;
104495         }
104496       }
104497       assert( pParse->nErr>0 || pFK==0 );
104498       if( pFK ) break;
104499       if( pParse->nTab<i ) pParse->nTab = i;
104500       addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
104501       for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
104502         pParent = sqlite3FindTable(db, pFK->zTo, zDb);
104503         pIdx = 0;
104504         aiCols = 0;
104505         if( pParent ){
104506           x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
104507           assert( x==0 );
104508         }
104509         addrOk = sqlite3VdbeMakeLabel(v);
104510         if( pParent && pIdx==0 ){
104511           int iKey = pFK->aCol[0].iFrom;
104512           assert( iKey>=0 && iKey<pTab->nCol );
104513           if( iKey!=pTab->iPKey ){
104514             sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
104515             sqlite3ColumnDefault(v, pTab, iKey, regRow);
104516             sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
104517             sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow, 
104518                sqlite3VdbeCurrentAddr(v)+3); VdbeCoverage(v);
104519           }else{
104520             sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
104521           }
104522           sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow); VdbeCoverage(v);
104523           sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
104524           sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
104525         }else{
104526           for(j=0; j<pFK->nCol; j++){
104527             sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
104528                             aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
104529             sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
104530           }
104531           if( pParent ){
104532             sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
104533                               sqlite3IndexAffinityStr(v,pIdx), pFK->nCol);
104534             sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
104535             VdbeCoverage(v);
104536           }
104537         }
104538         sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
104539         sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0, 
104540                           pFK->zTo, P4_TRANSIENT);
104541         sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
104542         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
104543         sqlite3VdbeResolveLabel(v, addrOk);
104544         sqlite3DbFree(db, aiCols);
104545       }
104546       sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
104547       sqlite3VdbeJumpHere(v, addrTop);
104548     }
104549   }
104550   break;
104551 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
104552 #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
104553
104554 #ifndef NDEBUG
104555   case PragTyp_PARSER_TRACE: {
104556     if( zRight ){
104557       if( sqlite3GetBoolean(zRight, 0) ){
104558         sqlite3ParserTrace(stderr, "parser: ");
104559       }else{
104560         sqlite3ParserTrace(0, 0);
104561       }
104562     }
104563   }
104564   break;
104565 #endif
104566
104567   /* Reinstall the LIKE and GLOB functions.  The variant of LIKE
104568   ** used will be case sensitive or not depending on the RHS.
104569   */
104570   case PragTyp_CASE_SENSITIVE_LIKE: {
104571     if( zRight ){
104572       sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
104573     }
104574   }
104575   break;
104576
104577 #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
104578 # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
104579 #endif
104580
104581 #ifndef SQLITE_OMIT_INTEGRITY_CHECK
104582   /* Pragma "quick_check" is reduced version of 
104583   ** integrity_check designed to detect most database corruption
104584   ** without most of the overhead of a full integrity-check.
104585   */
104586   case PragTyp_INTEGRITY_CHECK: {
104587     int i, j, addr, mxErr;
104588
104589     /* Code that appears at the end of the integrity check.  If no error
104590     ** messages have been generated, output OK.  Otherwise output the
104591     ** error message
104592     */
104593     static const int iLn = VDBE_OFFSET_LINENO(2);
104594     static const VdbeOpList endCode[] = {
104595       { OP_IfNeg,       1, 0,        0},    /* 0 */
104596       { OP_String8,     0, 3,        0},    /* 1 */
104597       { OP_ResultRow,   3, 1,        0},
104598     };
104599
104600     int isQuick = (sqlite3Tolower(zLeft[0])=='q');
104601
104602     /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
104603     ** then iDb is set to the index of the database identified by <db>.
104604     ** In this case, the integrity of database iDb only is verified by
104605     ** the VDBE created below.
104606     **
104607     ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
104608     ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
104609     ** to -1 here, to indicate that the VDBE should verify the integrity
104610     ** of all attached databases.  */
104611     assert( iDb>=0 );
104612     assert( iDb==0 || pId2->z );
104613     if( pId2->z==0 ) iDb = -1;
104614
104615     /* Initialize the VDBE program */
104616     pParse->nMem = 6;
104617     sqlite3VdbeSetNumCols(v, 1);
104618     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
104619
104620     /* Set the maximum error count */
104621     mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
104622     if( zRight ){
104623       sqlite3GetInt32(zRight, &mxErr);
104624       if( mxErr<=0 ){
104625         mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
104626       }
104627     }
104628     sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1);  /* reg[1] holds errors left */
104629
104630     /* Do an integrity check on each database file */
104631     for(i=0; i<db->nDb; i++){
104632       HashElem *x;
104633       Hash *pTbls;
104634       int cnt = 0;
104635
104636       if( OMIT_TEMPDB && i==1 ) continue;
104637       if( iDb>=0 && i!=iDb ) continue;
104638
104639       sqlite3CodeVerifySchema(pParse, i);
104640       addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
104641       VdbeCoverage(v);
104642       sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
104643       sqlite3VdbeJumpHere(v, addr);
104644
104645       /* Do an integrity check of the B-Tree
104646       **
104647       ** Begin by filling registers 2, 3, ... with the root pages numbers
104648       ** for all tables and indices in the database.
104649       */
104650       assert( sqlite3SchemaMutexHeld(db, i, 0) );
104651       pTbls = &db->aDb[i].pSchema->tblHash;
104652       for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
104653         Table *pTab = sqliteHashData(x);
104654         Index *pIdx;
104655         if( HasRowid(pTab) ){
104656           sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
104657           VdbeComment((v, "%s", pTab->zName));
104658           cnt++;
104659         }
104660         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
104661           sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
104662           VdbeComment((v, "%s", pIdx->zName));
104663           cnt++;
104664         }
104665       }
104666
104667       /* Make sure sufficient number of registers have been allocated */
104668       pParse->nMem = MAX( pParse->nMem, cnt+8 );
104669
104670       /* Do the b-tree integrity checks */
104671       sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
104672       sqlite3VdbeChangeP5(v, (u8)i);
104673       addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
104674       sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
104675          sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
104676          P4_DYNAMIC);
104677       sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
104678       sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
104679       sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
104680       sqlite3VdbeJumpHere(v, addr);
104681
104682       /* Make sure all the indices are constructed correctly.
104683       */
104684       for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
104685         Table *pTab = sqliteHashData(x);
104686         Index *pIdx, *pPk;
104687         Index *pPrior = 0;
104688         int loopTop;
104689         int iDataCur, iIdxCur;
104690         int r1 = -1;
104691
104692         if( pTab->pIndex==0 ) continue;
104693         pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
104694         addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1);  /* Stop if out of errors */
104695         VdbeCoverage(v);
104696         sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
104697         sqlite3VdbeJumpHere(v, addr);
104698         sqlite3ExprCacheClear(pParse);
104699         sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead,
104700                                    1, 0, &iDataCur, &iIdxCur);
104701         sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
104702         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
104703           sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
104704         }
104705         pParse->nMem = MAX(pParse->nMem, 8+j);
104706         sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
104707         loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
104708         /* Verify that all NOT NULL columns really are NOT NULL */
104709         for(j=0; j<pTab->nCol; j++){
104710           char *zErr;
104711           int jmp2, jmp3;
104712           if( j==pTab->iPKey ) continue;
104713           if( pTab->aCol[j].notNull==0 ) continue;
104714           sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
104715           sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
104716           jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
104717           sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
104718           zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
104719                               pTab->aCol[j].zName);
104720           sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
104721           sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
104722           jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
104723           sqlite3VdbeAddOp0(v, OP_Halt);
104724           sqlite3VdbeJumpHere(v, jmp2);
104725           sqlite3VdbeJumpHere(v, jmp3);
104726         }
104727         /* Validate index entries for the current row */
104728         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
104729           int jmp2, jmp3, jmp4, jmp5;
104730           int ckUniq = sqlite3VdbeMakeLabel(v);
104731           if( pPk==pIdx ) continue;
104732           r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
104733                                        pPrior, r1);
104734           pPrior = pIdx;
104735           sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1);  /* increment entry count */
104736           /* Verify that an index entry exists for the current table row */
104737           jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
104738                                       pIdx->nColumn); VdbeCoverage(v);
104739           sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
104740           sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, "row ", P4_STATIC);
104741           sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
104742           sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0, 
104743                             " missing from index ", P4_STATIC);
104744           sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
104745           jmp5 = sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
104746                                    pIdx->zName, P4_TRANSIENT);
104747           sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
104748           sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
104749           jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
104750           sqlite3VdbeAddOp0(v, OP_Halt);
104751           sqlite3VdbeJumpHere(v, jmp2);
104752           /* For UNIQUE indexes, verify that only one entry exists with the
104753           ** current key.  The entry is unique if (1) any column is NULL
104754           ** or (2) the next entry has a different key */
104755           if( IsUniqueIndex(pIdx) ){
104756             int uniqOk = sqlite3VdbeMakeLabel(v);
104757             int jmp6;
104758             int kk;
104759             for(kk=0; kk<pIdx->nKeyCol; kk++){
104760               int iCol = pIdx->aiColumn[kk];
104761               assert( iCol>=0 && iCol<pTab->nCol );
104762               if( pTab->aCol[iCol].notNull ) continue;
104763               sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
104764               VdbeCoverage(v);
104765             }
104766             jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
104767             sqlite3VdbeAddOp2(v, OP_Goto, 0, uniqOk);
104768             sqlite3VdbeJumpHere(v, jmp6);
104769             sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
104770                                  pIdx->nKeyCol); VdbeCoverage(v);
104771             sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
104772             sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
104773                               "non-unique entry in index ", P4_STATIC);
104774             sqlite3VdbeAddOp2(v, OP_Goto, 0, jmp5);
104775             sqlite3VdbeResolveLabel(v, uniqOk);
104776           }
104777           sqlite3VdbeJumpHere(v, jmp4);
104778           sqlite3ResolvePartIdxLabel(pParse, jmp3);
104779         }
104780         sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
104781         sqlite3VdbeJumpHere(v, loopTop-1);
104782 #ifndef SQLITE_OMIT_BTREECOUNT
104783         sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, 
104784                      "wrong # of entries in index ", P4_STATIC);
104785         for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
104786           if( pPk==pIdx ) continue;
104787           addr = sqlite3VdbeCurrentAddr(v);
104788           sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
104789           sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
104790           sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
104791           sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
104792           sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
104793           sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
104794           sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT);
104795           sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
104796           sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
104797         }
104798 #endif /* SQLITE_OMIT_BTREECOUNT */
104799       } 
104800     }
104801     addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
104802     sqlite3VdbeChangeP3(v, addr, -mxErr);
104803     sqlite3VdbeJumpHere(v, addr);
104804     sqlite3VdbeChangeP4(v, addr+1, "ok", P4_STATIC);
104805   }
104806   break;
104807 #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
104808
104809 #ifndef SQLITE_OMIT_UTF16
104810   /*
104811   **   PRAGMA encoding
104812   **   PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
104813   **
104814   ** In its first form, this pragma returns the encoding of the main
104815   ** database. If the database is not initialized, it is initialized now.
104816   **
104817   ** The second form of this pragma is a no-op if the main database file
104818   ** has not already been initialized. In this case it sets the default
104819   ** encoding that will be used for the main database file if a new file
104820   ** is created. If an existing main database file is opened, then the
104821   ** default text encoding for the existing database is used.
104822   ** 
104823   ** In all cases new databases created using the ATTACH command are
104824   ** created to use the same default text encoding as the main database. If
104825   ** the main database has not been initialized and/or created when ATTACH
104826   ** is executed, this is done before the ATTACH operation.
104827   **
104828   ** In the second form this pragma sets the text encoding to be used in
104829   ** new database files created using this database handle. It is only
104830   ** useful if invoked immediately after the main database i
104831   */
104832   case PragTyp_ENCODING: {
104833     static const struct EncName {
104834       char *zName;
104835       u8 enc;
104836     } encnames[] = {
104837       { "UTF8",     SQLITE_UTF8        },
104838       { "UTF-8",    SQLITE_UTF8        },  /* Must be element [1] */
104839       { "UTF-16le", SQLITE_UTF16LE     },  /* Must be element [2] */
104840       { "UTF-16be", SQLITE_UTF16BE     },  /* Must be element [3] */
104841       { "UTF16le",  SQLITE_UTF16LE     },
104842       { "UTF16be",  SQLITE_UTF16BE     },
104843       { "UTF-16",   0                  }, /* SQLITE_UTF16NATIVE */
104844       { "UTF16",    0                  }, /* SQLITE_UTF16NATIVE */
104845       { 0, 0 }
104846     };
104847     const struct EncName *pEnc;
104848     if( !zRight ){    /* "PRAGMA encoding" */
104849       if( sqlite3ReadSchema(pParse) ) goto pragma_out;
104850       sqlite3VdbeSetNumCols(v, 1);
104851       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
104852       sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
104853       assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
104854       assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
104855       assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
104856       sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
104857       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
104858     }else{                        /* "PRAGMA encoding = XXX" */
104859       /* Only change the value of sqlite.enc if the database handle is not
104860       ** initialized. If the main database exists, the new sqlite.enc value
104861       ** will be overwritten when the schema is next loaded. If it does not
104862       ** already exists, it will be created to use the new encoding value.
104863       */
104864       if( 
104865         !(DbHasProperty(db, 0, DB_SchemaLoaded)) || 
104866         DbHasProperty(db, 0, DB_Empty) 
104867       ){
104868         for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
104869           if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
104870             SCHEMA_ENC(db) = ENC(db) =
104871                 pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
104872             break;
104873           }
104874         }
104875         if( !pEnc->zName ){
104876           sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
104877         }
104878       }
104879     }
104880   }
104881   break;
104882 #endif /* SQLITE_OMIT_UTF16 */
104883
104884 #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
104885   /*
104886   **   PRAGMA [database.]schema_version
104887   **   PRAGMA [database.]schema_version = <integer>
104888   **
104889   **   PRAGMA [database.]user_version
104890   **   PRAGMA [database.]user_version = <integer>
104891   **
104892   **   PRAGMA [database.]freelist_count = <integer>
104893   **
104894   **   PRAGMA [database.]application_id
104895   **   PRAGMA [database.]application_id = <integer>
104896   **
104897   ** The pragma's schema_version and user_version are used to set or get
104898   ** the value of the schema-version and user-version, respectively. Both
104899   ** the schema-version and the user-version are 32-bit signed integers
104900   ** stored in the database header.
104901   **
104902   ** The schema-cookie is usually only manipulated internally by SQLite. It
104903   ** is incremented by SQLite whenever the database schema is modified (by
104904   ** creating or dropping a table or index). The schema version is used by
104905   ** SQLite each time a query is executed to ensure that the internal cache
104906   ** of the schema used when compiling the SQL query matches the schema of
104907   ** the database against which the compiled query is actually executed.
104908   ** Subverting this mechanism by using "PRAGMA schema_version" to modify
104909   ** the schema-version is potentially dangerous and may lead to program
104910   ** crashes or database corruption. Use with caution!
104911   **
104912   ** The user-version is not used internally by SQLite. It may be used by
104913   ** applications for any purpose.
104914   */
104915   case PragTyp_HEADER_VALUE: {
104916     int iCookie = pPragma->iArg;  /* Which cookie to read or write */
104917     sqlite3VdbeUsesBtree(v, iDb);
104918     if( zRight && (pPragma->mPragFlag & PragFlag_ReadOnly)==0 ){
104919       /* Write the specified cookie value */
104920       static const VdbeOpList setCookie[] = {
104921         { OP_Transaction,    0,  1,  0},    /* 0 */
104922         { OP_Integer,        0,  1,  0},    /* 1 */
104923         { OP_SetCookie,      0,  0,  1},    /* 2 */
104924       };
104925       int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
104926       sqlite3VdbeChangeP1(v, addr, iDb);
104927       sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
104928       sqlite3VdbeChangeP1(v, addr+2, iDb);
104929       sqlite3VdbeChangeP2(v, addr+2, iCookie);
104930     }else{
104931       /* Read the specified cookie value */
104932       static const VdbeOpList readCookie[] = {
104933         { OP_Transaction,     0,  0,  0},    /* 0 */
104934         { OP_ReadCookie,      0,  1,  0},    /* 1 */
104935         { OP_ResultRow,       1,  1,  0}
104936       };
104937       int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie, 0);
104938       sqlite3VdbeChangeP1(v, addr, iDb);
104939       sqlite3VdbeChangeP1(v, addr+1, iDb);
104940       sqlite3VdbeChangeP3(v, addr+1, iCookie);
104941       sqlite3VdbeSetNumCols(v, 1);
104942       sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
104943     }
104944   }
104945   break;
104946 #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
104947
104948 #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
104949   /*
104950   **   PRAGMA compile_options
104951   **
104952   ** Return the names of all compile-time options used in this build,
104953   ** one option per row.
104954   */
104955   case PragTyp_COMPILE_OPTIONS: {
104956     int i = 0;
104957     const char *zOpt;
104958     sqlite3VdbeSetNumCols(v, 1);
104959     pParse->nMem = 1;
104960     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
104961     while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
104962       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
104963       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
104964     }
104965   }
104966   break;
104967 #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
104968
104969 #ifndef SQLITE_OMIT_WAL
104970   /*
104971   **   PRAGMA [database.]wal_checkpoint = passive|full|restart|truncate
104972   **
104973   ** Checkpoint the database.
104974   */
104975   case PragTyp_WAL_CHECKPOINT: {
104976     int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
104977     int eMode = SQLITE_CHECKPOINT_PASSIVE;
104978     if( zRight ){
104979       if( sqlite3StrICmp(zRight, "full")==0 ){
104980         eMode = SQLITE_CHECKPOINT_FULL;
104981       }else if( sqlite3StrICmp(zRight, "restart")==0 ){
104982         eMode = SQLITE_CHECKPOINT_RESTART;
104983       }else if( sqlite3StrICmp(zRight, "truncate")==0 ){
104984         eMode = SQLITE_CHECKPOINT_TRUNCATE;
104985       }
104986     }
104987     sqlite3VdbeSetNumCols(v, 3);
104988     pParse->nMem = 3;
104989     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
104990     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
104991     sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
104992
104993     sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
104994     sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
104995   }
104996   break;
104997
104998   /*
104999   **   PRAGMA wal_autocheckpoint
105000   **   PRAGMA wal_autocheckpoint = N
105001   **
105002   ** Configure a database connection to automatically checkpoint a database
105003   ** after accumulating N frames in the log. Or query for the current value
105004   ** of N.
105005   */
105006   case PragTyp_WAL_AUTOCHECKPOINT: {
105007     if( zRight ){
105008       sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
105009     }
105010     returnSingleInt(pParse, "wal_autocheckpoint", 
105011        db->xWalCallback==sqlite3WalDefaultHook ? 
105012            SQLITE_PTR_TO_INT(db->pWalArg) : 0);
105013   }
105014   break;
105015 #endif
105016
105017   /*
105018   **  PRAGMA shrink_memory
105019   **
105020   ** IMPLEMENTATION-OF: R-23445-46109 This pragma causes the database
105021   ** connection on which it is invoked to free up as much memory as it
105022   ** can, by calling sqlite3_db_release_memory().
105023   */
105024   case PragTyp_SHRINK_MEMORY: {
105025     sqlite3_db_release_memory(db);
105026     break;
105027   }
105028
105029   /*
105030   **   PRAGMA busy_timeout
105031   **   PRAGMA busy_timeout = N
105032   **
105033   ** Call sqlite3_busy_timeout(db, N).  Return the current timeout value
105034   ** if one is set.  If no busy handler or a different busy handler is set
105035   ** then 0 is returned.  Setting the busy_timeout to 0 or negative
105036   ** disables the timeout.
105037   */
105038   /*case PragTyp_BUSY_TIMEOUT*/ default: {
105039     assert( pPragma->ePragTyp==PragTyp_BUSY_TIMEOUT );
105040     if( zRight ){
105041       sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
105042     }
105043     returnSingleInt(pParse, "timeout",  db->busyTimeout);
105044     break;
105045   }
105046
105047   /*
105048   **   PRAGMA soft_heap_limit
105049   **   PRAGMA soft_heap_limit = N
105050   **
105051   ** IMPLEMENTATION-OF: R-26343-45930 This pragma invokes the
105052   ** sqlite3_soft_heap_limit64() interface with the argument N, if N is
105053   ** specified and is a non-negative integer.
105054   ** IMPLEMENTATION-OF: R-64451-07163 The soft_heap_limit pragma always
105055   ** returns the same integer that would be returned by the
105056   ** sqlite3_soft_heap_limit64(-1) C-language function.
105057   */
105058   case PragTyp_SOFT_HEAP_LIMIT: {
105059     sqlite3_int64 N;
105060     if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
105061       sqlite3_soft_heap_limit64(N);
105062     }
105063     returnSingleInt(pParse, "soft_heap_limit",  sqlite3_soft_heap_limit64(-1));
105064     break;
105065   }
105066
105067   /*
105068   **   PRAGMA threads
105069   **   PRAGMA threads = N
105070   **
105071   ** Configure the maximum number of worker threads.  Return the new
105072   ** maximum, which might be less than requested.
105073   */
105074   case PragTyp_THREADS: {
105075     sqlite3_int64 N;
105076     if( zRight
105077      && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
105078      && N>=0
105079     ){
105080       sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
105081     }
105082     returnSingleInt(pParse, "threads",
105083                     sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
105084     break;
105085   }
105086
105087 #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
105088   /*
105089   ** Report the current state of file logs for all databases
105090   */
105091   case PragTyp_LOCK_STATUS: {
105092     static const char *const azLockName[] = {
105093       "unlocked", "shared", "reserved", "pending", "exclusive"
105094     };
105095     int i;
105096     sqlite3VdbeSetNumCols(v, 2);
105097     pParse->nMem = 2;
105098     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
105099     sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
105100     for(i=0; i<db->nDb; i++){
105101       Btree *pBt;
105102       const char *zState = "unknown";
105103       int j;
105104       if( db->aDb[i].zName==0 ) continue;
105105       sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
105106       pBt = db->aDb[i].pBt;
105107       if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
105108         zState = "closed";
105109       }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0, 
105110                                      SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
105111          zState = azLockName[j];
105112       }
105113       sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
105114       sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
105115     }
105116     break;
105117   }
105118 #endif
105119
105120 #ifdef SQLITE_HAS_CODEC
105121   case PragTyp_KEY: {
105122     if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
105123     break;
105124   }
105125   case PragTyp_REKEY: {
105126     if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
105127     break;
105128   }
105129   case PragTyp_HEXKEY: {
105130     if( zRight ){
105131       u8 iByte;
105132       int i;
105133       char zKey[40];
105134       for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
105135         iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
105136         if( (i&1)!=0 ) zKey[i/2] = iByte;
105137       }
105138       if( (zLeft[3] & 0xf)==0xb ){
105139         sqlite3_key_v2(db, zDb, zKey, i/2);
105140       }else{
105141         sqlite3_rekey_v2(db, zDb, zKey, i/2);
105142       }
105143     }
105144     break;
105145   }
105146 #endif
105147 #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
105148   case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
105149 #ifdef SQLITE_HAS_CODEC
105150     if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
105151       sqlite3_activate_see(&zRight[4]);
105152     }
105153 #endif
105154 #ifdef SQLITE_ENABLE_CEROD
105155     if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
105156       sqlite3_activate_cerod(&zRight[6]);
105157     }
105158 #endif
105159   }
105160   break;
105161 #endif
105162
105163   } /* End of the PRAGMA switch */
105164
105165 pragma_out:
105166   sqlite3DbFree(db, zLeft);
105167   sqlite3DbFree(db, zRight);
105168 }
105169
105170 #endif /* SQLITE_OMIT_PRAGMA */
105171
105172 /************** End of pragma.c **********************************************/
105173 /************** Begin file prepare.c *****************************************/
105174 /*
105175 ** 2005 May 25
105176 **
105177 ** The author disclaims copyright to this source code.  In place of
105178 ** a legal notice, here is a blessing:
105179 **
105180 **    May you do good and not evil.
105181 **    May you find forgiveness for yourself and forgive others.
105182 **    May you share freely, never taking more than you give.
105183 **
105184 *************************************************************************
105185 ** This file contains the implementation of the sqlite3_prepare()
105186 ** interface, and routines that contribute to loading the database schema
105187 ** from disk.
105188 */
105189
105190 /*
105191 ** Fill the InitData structure with an error message that indicates
105192 ** that the database is corrupt.
105193 */
105194 static void corruptSchema(
105195   InitData *pData,     /* Initialization context */
105196   const char *zObj,    /* Object being parsed at the point of error */
105197   const char *zExtra   /* Error information */
105198 ){
105199   sqlite3 *db = pData->db;
105200   if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
105201     if( zObj==0 ) zObj = "?";
105202     sqlite3SetString(pData->pzErrMsg, db,
105203       "malformed database schema (%s)", zObj);
105204     if( zExtra ){
105205       *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg, 
105206                                  "%s - %s", *pData->pzErrMsg, zExtra);
105207     }
105208   }
105209   pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
105210 }
105211
105212 /*
105213 ** This is the callback routine for the code that initializes the
105214 ** database.  See sqlite3Init() below for additional information.
105215 ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
105216 **
105217 ** Each callback contains the following information:
105218 **
105219 **     argv[0] = name of thing being created
105220 **     argv[1] = root page number for table or index. 0 for trigger or view.
105221 **     argv[2] = SQL text for the CREATE statement.
105222 **
105223 */
105224 SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
105225   InitData *pData = (InitData*)pInit;
105226   sqlite3 *db = pData->db;
105227   int iDb = pData->iDb;
105228
105229   assert( argc==3 );
105230   UNUSED_PARAMETER2(NotUsed, argc);
105231   assert( sqlite3_mutex_held(db->mutex) );
105232   DbClearProperty(db, iDb, DB_Empty);
105233   if( db->mallocFailed ){
105234     corruptSchema(pData, argv[0], 0);
105235     return 1;
105236   }
105237
105238   assert( iDb>=0 && iDb<db->nDb );
105239   if( argv==0 ) return 0;   /* Might happen if EMPTY_RESULT_CALLBACKS are on */
105240   if( argv[1]==0 ){
105241     corruptSchema(pData, argv[0], 0);
105242   }else if( argv[2] && argv[2][0] ){
105243     /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
105244     ** But because db->init.busy is set to 1, no VDBE code is generated
105245     ** or executed.  All the parser does is build the internal data
105246     ** structures that describe the table, index, or view.
105247     */
105248     int rc;
105249     sqlite3_stmt *pStmt;
105250     TESTONLY(int rcp);            /* Return code from sqlite3_prepare() */
105251
105252     assert( db->init.busy );
105253     db->init.iDb = iDb;
105254     db->init.newTnum = sqlite3Atoi(argv[1]);
105255     db->init.orphanTrigger = 0;
105256     TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
105257     rc = db->errCode;
105258     assert( (rc&0xFF)==(rcp&0xFF) );
105259     db->init.iDb = 0;
105260     if( SQLITE_OK!=rc ){
105261       if( db->init.orphanTrigger ){
105262         assert( iDb==1 );
105263       }else{
105264         pData->rc = rc;
105265         if( rc==SQLITE_NOMEM ){
105266           db->mallocFailed = 1;
105267         }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
105268           corruptSchema(pData, argv[0], sqlite3_errmsg(db));
105269         }
105270       }
105271     }
105272     sqlite3_finalize(pStmt);
105273   }else if( argv[0]==0 ){
105274     corruptSchema(pData, 0, 0);
105275   }else{
105276     /* If the SQL column is blank it means this is an index that
105277     ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
105278     ** constraint for a CREATE TABLE.  The index should have already
105279     ** been created when we processed the CREATE TABLE.  All we have
105280     ** to do here is record the root page number for that index.
105281     */
105282     Index *pIndex;
105283     pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
105284     if( pIndex==0 ){
105285       /* This can occur if there exists an index on a TEMP table which
105286       ** has the same name as another index on a permanent index.  Since
105287       ** the permanent table is hidden by the TEMP table, we can also
105288       ** safely ignore the index on the permanent table.
105289       */
105290       /* Do Nothing */;
105291     }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
105292       corruptSchema(pData, argv[0], "invalid rootpage");
105293     }
105294   }
105295   return 0;
105296 }
105297
105298 /*
105299 ** Attempt to read the database schema and initialize internal
105300 ** data structures for a single database file.  The index of the
105301 ** database file is given by iDb.  iDb==0 is used for the main
105302 ** database.  iDb==1 should never be used.  iDb>=2 is used for
105303 ** auxiliary databases.  Return one of the SQLITE_ error codes to
105304 ** indicate success or failure.
105305 */
105306 static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
105307   int rc;
105308   int i;
105309 #ifndef SQLITE_OMIT_DEPRECATED
105310   int size;
105311 #endif
105312   Table *pTab;
105313   Db *pDb;
105314   char const *azArg[4];
105315   int meta[5];
105316   InitData initData;
105317   char const *zMasterSchema;
105318   char const *zMasterName;
105319   int openedTransaction = 0;
105320
105321   /*
105322   ** The master database table has a structure like this
105323   */
105324   static const char master_schema[] = 
105325      "CREATE TABLE sqlite_master(\n"
105326      "  type text,\n"
105327      "  name text,\n"
105328      "  tbl_name text,\n"
105329      "  rootpage integer,\n"
105330      "  sql text\n"
105331      ")"
105332   ;
105333 #ifndef SQLITE_OMIT_TEMPDB
105334   static const char temp_master_schema[] = 
105335      "CREATE TEMP TABLE sqlite_temp_master(\n"
105336      "  type text,\n"
105337      "  name text,\n"
105338      "  tbl_name text,\n"
105339      "  rootpage integer,\n"
105340      "  sql text\n"
105341      ")"
105342   ;
105343 #else
105344   #define temp_master_schema 0
105345 #endif
105346
105347   assert( iDb>=0 && iDb<db->nDb );
105348   assert( db->aDb[iDb].pSchema );
105349   assert( sqlite3_mutex_held(db->mutex) );
105350   assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
105351
105352   /* zMasterSchema and zInitScript are set to point at the master schema
105353   ** and initialisation script appropriate for the database being
105354   ** initialized. zMasterName is the name of the master table.
105355   */
105356   if( !OMIT_TEMPDB && iDb==1 ){
105357     zMasterSchema = temp_master_schema;
105358   }else{
105359     zMasterSchema = master_schema;
105360   }
105361   zMasterName = SCHEMA_TABLE(iDb);
105362
105363   /* Construct the schema tables.  */
105364   azArg[0] = zMasterName;
105365   azArg[1] = "1";
105366   azArg[2] = zMasterSchema;
105367   azArg[3] = 0;
105368   initData.db = db;
105369   initData.iDb = iDb;
105370   initData.rc = SQLITE_OK;
105371   initData.pzErrMsg = pzErrMsg;
105372   sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
105373   if( initData.rc ){
105374     rc = initData.rc;
105375     goto error_out;
105376   }
105377   pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
105378   if( ALWAYS(pTab) ){
105379     pTab->tabFlags |= TF_Readonly;
105380   }
105381
105382   /* Create a cursor to hold the database open
105383   */
105384   pDb = &db->aDb[iDb];
105385   if( pDb->pBt==0 ){
105386     if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
105387       DbSetProperty(db, 1, DB_SchemaLoaded);
105388     }
105389     return SQLITE_OK;
105390   }
105391
105392   /* If there is not already a read-only (or read-write) transaction opened
105393   ** on the b-tree database, open one now. If a transaction is opened, it 
105394   ** will be closed before this function returns.  */
105395   sqlite3BtreeEnter(pDb->pBt);
105396   if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
105397     rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
105398     if( rc!=SQLITE_OK ){
105399       sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
105400       goto initone_error_out;
105401     }
105402     openedTransaction = 1;
105403   }
105404
105405   /* Get the database meta information.
105406   **
105407   ** Meta values are as follows:
105408   **    meta[0]   Schema cookie.  Changes with each schema change.
105409   **    meta[1]   File format of schema layer.
105410   **    meta[2]   Size of the page cache.
105411   **    meta[3]   Largest rootpage (auto/incr_vacuum mode)
105412   **    meta[4]   Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
105413   **    meta[5]   User version
105414   **    meta[6]   Incremental vacuum mode
105415   **    meta[7]   unused
105416   **    meta[8]   unused
105417   **    meta[9]   unused
105418   **
105419   ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
105420   ** the possible values of meta[4].
105421   */
105422   for(i=0; i<ArraySize(meta); i++){
105423     sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
105424   }
105425   pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
105426
105427   /* If opening a non-empty database, check the text encoding. For the
105428   ** main database, set sqlite3.enc to the encoding of the main database.
105429   ** For an attached db, it is an error if the encoding is not the same
105430   ** as sqlite3.enc.
105431   */
105432   if( meta[BTREE_TEXT_ENCODING-1] ){  /* text encoding */
105433     if( iDb==0 ){
105434 #ifndef SQLITE_OMIT_UTF16
105435       u8 encoding;
105436       /* If opening the main database, set ENC(db). */
105437       encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
105438       if( encoding==0 ) encoding = SQLITE_UTF8;
105439       ENC(db) = encoding;
105440 #else
105441       ENC(db) = SQLITE_UTF8;
105442 #endif
105443     }else{
105444       /* If opening an attached database, the encoding much match ENC(db) */
105445       if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
105446         sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
105447             " text encoding as main database");
105448         rc = SQLITE_ERROR;
105449         goto initone_error_out;
105450       }
105451     }
105452   }else{
105453     DbSetProperty(db, iDb, DB_Empty);
105454   }
105455   pDb->pSchema->enc = ENC(db);
105456
105457   if( pDb->pSchema->cache_size==0 ){
105458 #ifndef SQLITE_OMIT_DEPRECATED
105459     size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
105460     if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
105461     pDb->pSchema->cache_size = size;
105462 #else
105463     pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
105464 #endif
105465     sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
105466   }
105467
105468   /*
105469   ** file_format==1    Version 3.0.0.
105470   ** file_format==2    Version 3.1.3.  // ALTER TABLE ADD COLUMN
105471   ** file_format==3    Version 3.1.4.  // ditto but with non-NULL defaults
105472   ** file_format==4    Version 3.3.0.  // DESC indices.  Boolean constants
105473   */
105474   pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
105475   if( pDb->pSchema->file_format==0 ){
105476     pDb->pSchema->file_format = 1;
105477   }
105478   if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
105479     sqlite3SetString(pzErrMsg, db, "unsupported file format");
105480     rc = SQLITE_ERROR;
105481     goto initone_error_out;
105482   }
105483
105484   /* Ticket #2804:  When we open a database in the newer file format,
105485   ** clear the legacy_file_format pragma flag so that a VACUUM will
105486   ** not downgrade the database and thus invalidate any descending
105487   ** indices that the user might have created.
105488   */
105489   if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
105490     db->flags &= ~SQLITE_LegacyFileFmt;
105491   }
105492
105493   /* Read the schema information out of the schema tables
105494   */
105495   assert( db->init.busy );
105496   {
105497     char *zSql;
105498     zSql = sqlite3MPrintf(db, 
105499         "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
105500         db->aDb[iDb].zName, zMasterName);
105501 #ifndef SQLITE_OMIT_AUTHORIZATION
105502     {
105503       sqlite3_xauth xAuth;
105504       xAuth = db->xAuth;
105505       db->xAuth = 0;
105506 #endif
105507       rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
105508 #ifndef SQLITE_OMIT_AUTHORIZATION
105509       db->xAuth = xAuth;
105510     }
105511 #endif
105512     if( rc==SQLITE_OK ) rc = initData.rc;
105513     sqlite3DbFree(db, zSql);
105514 #ifndef SQLITE_OMIT_ANALYZE
105515     if( rc==SQLITE_OK ){
105516       sqlite3AnalysisLoad(db, iDb);
105517     }
105518 #endif
105519   }
105520   if( db->mallocFailed ){
105521     rc = SQLITE_NOMEM;
105522     sqlite3ResetAllSchemasOfConnection(db);
105523   }
105524   if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
105525     /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
105526     ** the schema loaded, even if errors occurred. In this situation the 
105527     ** current sqlite3_prepare() operation will fail, but the following one
105528     ** will attempt to compile the supplied statement against whatever subset
105529     ** of the schema was loaded before the error occurred. The primary
105530     ** purpose of this is to allow access to the sqlite_master table
105531     ** even when its contents have been corrupted.
105532     */
105533     DbSetProperty(db, iDb, DB_SchemaLoaded);
105534     rc = SQLITE_OK;
105535   }
105536
105537   /* Jump here for an error that occurs after successfully allocating
105538   ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
105539   ** before that point, jump to error_out.
105540   */
105541 initone_error_out:
105542   if( openedTransaction ){
105543     sqlite3BtreeCommit(pDb->pBt);
105544   }
105545   sqlite3BtreeLeave(pDb->pBt);
105546
105547 error_out:
105548   if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
105549     db->mallocFailed = 1;
105550   }
105551   return rc;
105552 }
105553
105554 /*
105555 ** Initialize all database files - the main database file, the file
105556 ** used to store temporary tables, and any additional database files
105557 ** created using ATTACH statements.  Return a success code.  If an
105558 ** error occurs, write an error message into *pzErrMsg.
105559 **
105560 ** After a database is initialized, the DB_SchemaLoaded bit is set
105561 ** bit is set in the flags field of the Db structure. If the database
105562 ** file was of zero-length, then the DB_Empty flag is also set.
105563 */
105564 SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
105565   int i, rc;
105566   int commit_internal = !(db->flags&SQLITE_InternChanges);
105567   
105568   assert( sqlite3_mutex_held(db->mutex) );
105569   assert( sqlite3BtreeHoldsMutex(db->aDb[0].pBt) );
105570   assert( db->init.busy==0 );
105571   rc = SQLITE_OK;
105572   db->init.busy = 1;
105573   ENC(db) = SCHEMA_ENC(db);
105574   for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
105575     if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
105576     rc = sqlite3InitOne(db, i, pzErrMsg);
105577     if( rc ){
105578       sqlite3ResetOneSchema(db, i);
105579     }
105580   }
105581
105582   /* Once all the other databases have been initialized, load the schema
105583   ** for the TEMP database. This is loaded last, as the TEMP database
105584   ** schema may contain references to objects in other databases.
105585   */
105586 #ifndef SQLITE_OMIT_TEMPDB
105587   assert( db->nDb>1 );
105588   if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
105589     rc = sqlite3InitOne(db, 1, pzErrMsg);
105590     if( rc ){
105591       sqlite3ResetOneSchema(db, 1);
105592     }
105593   }
105594 #endif
105595
105596   db->init.busy = 0;
105597   if( rc==SQLITE_OK && commit_internal ){
105598     sqlite3CommitInternalChanges(db);
105599   }
105600
105601   return rc; 
105602 }
105603
105604 /*
105605 ** This routine is a no-op if the database schema is already initialized.
105606 ** Otherwise, the schema is loaded. An error code is returned.
105607 */
105608 SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
105609   int rc = SQLITE_OK;
105610   sqlite3 *db = pParse->db;
105611   assert( sqlite3_mutex_held(db->mutex) );
105612   if( !db->init.busy ){
105613     rc = sqlite3Init(db, &pParse->zErrMsg);
105614   }
105615   if( rc!=SQLITE_OK ){
105616     pParse->rc = rc;
105617     pParse->nErr++;
105618   }
105619   return rc;
105620 }
105621
105622
105623 /*
105624 ** Check schema cookies in all databases.  If any cookie is out
105625 ** of date set pParse->rc to SQLITE_SCHEMA.  If all schema cookies
105626 ** make no changes to pParse->rc.
105627 */
105628 static void schemaIsValid(Parse *pParse){
105629   sqlite3 *db = pParse->db;
105630   int iDb;
105631   int rc;
105632   int cookie;
105633
105634   assert( pParse->checkSchema );
105635   assert( sqlite3_mutex_held(db->mutex) );
105636   for(iDb=0; iDb<db->nDb; iDb++){
105637     int openedTransaction = 0;         /* True if a transaction is opened */
105638     Btree *pBt = db->aDb[iDb].pBt;     /* Btree database to read cookie from */
105639     if( pBt==0 ) continue;
105640
105641     /* If there is not already a read-only (or read-write) transaction opened
105642     ** on the b-tree database, open one now. If a transaction is opened, it 
105643     ** will be closed immediately after reading the meta-value. */
105644     if( !sqlite3BtreeIsInReadTrans(pBt) ){
105645       rc = sqlite3BtreeBeginTrans(pBt, 0);
105646       if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
105647         db->mallocFailed = 1;
105648       }
105649       if( rc!=SQLITE_OK ) return;
105650       openedTransaction = 1;
105651     }
105652
105653     /* Read the schema cookie from the database. If it does not match the 
105654     ** value stored as part of the in-memory schema representation,
105655     ** set Parse.rc to SQLITE_SCHEMA. */
105656     sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
105657     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
105658     if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
105659       sqlite3ResetOneSchema(db, iDb);
105660       pParse->rc = SQLITE_SCHEMA;
105661     }
105662
105663     /* Close the transaction, if one was opened. */
105664     if( openedTransaction ){
105665       sqlite3BtreeCommit(pBt);
105666     }
105667   }
105668 }
105669
105670 /*
105671 ** Convert a schema pointer into the iDb index that indicates
105672 ** which database file in db->aDb[] the schema refers to.
105673 **
105674 ** If the same database is attached more than once, the first
105675 ** attached database is returned.
105676 */
105677 SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
105678   int i = -1000000;
105679
105680   /* If pSchema is NULL, then return -1000000. This happens when code in 
105681   ** expr.c is trying to resolve a reference to a transient table (i.e. one
105682   ** created by a sub-select). In this case the return value of this 
105683   ** function should never be used.
105684   **
105685   ** We return -1000000 instead of the more usual -1 simply because using
105686   ** -1000000 as the incorrect index into db->aDb[] is much 
105687   ** more likely to cause a segfault than -1 (of course there are assert()
105688   ** statements too, but it never hurts to play the odds).
105689   */
105690   assert( sqlite3_mutex_held(db->mutex) );
105691   if( pSchema ){
105692     for(i=0; ALWAYS(i<db->nDb); i++){
105693       if( db->aDb[i].pSchema==pSchema ){
105694         break;
105695       }
105696     }
105697     assert( i>=0 && i<db->nDb );
105698   }
105699   return i;
105700 }
105701
105702 /*
105703 ** Free all memory allocations in the pParse object
105704 */
105705 SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
105706   if( pParse ){
105707     sqlite3 *db = pParse->db;
105708     sqlite3DbFree(db, pParse->aLabel);
105709     sqlite3ExprListDelete(db, pParse->pConstExpr);
105710   }
105711 }
105712
105713 /*
105714 ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
105715 */
105716 static int sqlite3Prepare(
105717   sqlite3 *db,              /* Database handle. */
105718   const char *zSql,         /* UTF-8 encoded SQL statement. */
105719   int nBytes,               /* Length of zSql in bytes. */
105720   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
105721   Vdbe *pReprepare,         /* VM being reprepared */
105722   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
105723   const char **pzTail       /* OUT: End of parsed string */
105724 ){
105725   Parse *pParse;            /* Parsing context */
105726   char *zErrMsg = 0;        /* Error message */
105727   int rc = SQLITE_OK;       /* Result code */
105728   int i;                    /* Loop counter */
105729
105730   /* Allocate the parsing context */
105731   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
105732   if( pParse==0 ){
105733     rc = SQLITE_NOMEM;
105734     goto end_prepare;
105735   }
105736   pParse->pReprepare = pReprepare;
105737   assert( ppStmt && *ppStmt==0 );
105738   assert( !db->mallocFailed );
105739   assert( sqlite3_mutex_held(db->mutex) );
105740
105741   /* Check to verify that it is possible to get a read lock on all
105742   ** database schemas.  The inability to get a read lock indicates that
105743   ** some other database connection is holding a write-lock, which in
105744   ** turn means that the other connection has made uncommitted changes
105745   ** to the schema.
105746   **
105747   ** Were we to proceed and prepare the statement against the uncommitted
105748   ** schema changes and if those schema changes are subsequently rolled
105749   ** back and different changes are made in their place, then when this
105750   ** prepared statement goes to run the schema cookie would fail to detect
105751   ** the schema change.  Disaster would follow.
105752   **
105753   ** This thread is currently holding mutexes on all Btrees (because
105754   ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
105755   ** is not possible for another thread to start a new schema change
105756   ** while this routine is running.  Hence, we do not need to hold 
105757   ** locks on the schema, we just need to make sure nobody else is 
105758   ** holding them.
105759   **
105760   ** Note that setting READ_UNCOMMITTED overrides most lock detection,
105761   ** but it does *not* override schema lock detection, so this all still
105762   ** works even if READ_UNCOMMITTED is set.
105763   */
105764   for(i=0; i<db->nDb; i++) {
105765     Btree *pBt = db->aDb[i].pBt;
105766     if( pBt ){
105767       assert( sqlite3BtreeHoldsMutex(pBt) );
105768       rc = sqlite3BtreeSchemaLocked(pBt);
105769       if( rc ){
105770         const char *zDb = db->aDb[i].zName;
105771         sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
105772         testcase( db->flags & SQLITE_ReadUncommitted );
105773         goto end_prepare;
105774       }
105775     }
105776   }
105777
105778   sqlite3VtabUnlockList(db);
105779
105780   pParse->db = db;
105781   pParse->nQueryLoop = 0;  /* Logarithmic, so 0 really means 1 */
105782   if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
105783     char *zSqlCopy;
105784     int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
105785     testcase( nBytes==mxLen );
105786     testcase( nBytes==mxLen+1 );
105787     if( nBytes>mxLen ){
105788       sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
105789       rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
105790       goto end_prepare;
105791     }
105792     zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
105793     if( zSqlCopy ){
105794       sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
105795       sqlite3DbFree(db, zSqlCopy);
105796       pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
105797     }else{
105798       pParse->zTail = &zSql[nBytes];
105799     }
105800   }else{
105801     sqlite3RunParser(pParse, zSql, &zErrMsg);
105802   }
105803   assert( 0==pParse->nQueryLoop );
105804
105805   if( db->mallocFailed ){
105806     pParse->rc = SQLITE_NOMEM;
105807   }
105808   if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
105809   if( pParse->checkSchema ){
105810     schemaIsValid(pParse);
105811   }
105812   if( db->mallocFailed ){
105813     pParse->rc = SQLITE_NOMEM;
105814   }
105815   if( pzTail ){
105816     *pzTail = pParse->zTail;
105817   }
105818   rc = pParse->rc;
105819
105820 #ifndef SQLITE_OMIT_EXPLAIN
105821   if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
105822     static const char * const azColName[] = {
105823        "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
105824        "selectid", "order", "from", "detail"
105825     };
105826     int iFirst, mx;
105827     if( pParse->explain==2 ){
105828       sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
105829       iFirst = 8;
105830       mx = 12;
105831     }else{
105832       sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
105833       iFirst = 0;
105834       mx = 8;
105835     }
105836     for(i=iFirst; i<mx; i++){
105837       sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
105838                             azColName[i], SQLITE_STATIC);
105839     }
105840   }
105841 #endif
105842
105843   if( db->init.busy==0 ){
105844     Vdbe *pVdbe = pParse->pVdbe;
105845     sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
105846   }
105847   if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
105848     sqlite3VdbeFinalize(pParse->pVdbe);
105849     assert(!(*ppStmt));
105850   }else{
105851     *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
105852   }
105853
105854   if( zErrMsg ){
105855     sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
105856     sqlite3DbFree(db, zErrMsg);
105857   }else{
105858     sqlite3Error(db, rc);
105859   }
105860
105861   /* Delete any TriggerPrg structures allocated while parsing this statement. */
105862   while( pParse->pTriggerPrg ){
105863     TriggerPrg *pT = pParse->pTriggerPrg;
105864     pParse->pTriggerPrg = pT->pNext;
105865     sqlite3DbFree(db, pT);
105866   }
105867
105868 end_prepare:
105869
105870   sqlite3ParserReset(pParse);
105871   sqlite3StackFree(db, pParse);
105872   rc = sqlite3ApiExit(db, rc);
105873   assert( (rc&db->errMask)==rc );
105874   return rc;
105875 }
105876 static int sqlite3LockAndPrepare(
105877   sqlite3 *db,              /* Database handle. */
105878   const char *zSql,         /* UTF-8 encoded SQL statement. */
105879   int nBytes,               /* Length of zSql in bytes. */
105880   int saveSqlFlag,          /* True to copy SQL text into the sqlite3_stmt */
105881   Vdbe *pOld,               /* VM being reprepared */
105882   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
105883   const char **pzTail       /* OUT: End of parsed string */
105884 ){
105885   int rc;
105886
105887 #ifdef SQLITE_ENABLE_API_ARMOR
105888   if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
105889 #endif
105890   *ppStmt = 0;
105891   if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
105892     return SQLITE_MISUSE_BKPT;
105893   }
105894   sqlite3_mutex_enter(db->mutex);
105895   sqlite3BtreeEnterAll(db);
105896   rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
105897   if( rc==SQLITE_SCHEMA ){
105898     sqlite3_finalize(*ppStmt);
105899     rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
105900   }
105901   sqlite3BtreeLeaveAll(db);
105902   sqlite3_mutex_leave(db->mutex);
105903   assert( rc==SQLITE_OK || *ppStmt==0 );
105904   return rc;
105905 }
105906
105907 /*
105908 ** Rerun the compilation of a statement after a schema change.
105909 **
105910 ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
105911 ** if the statement cannot be recompiled because another connection has
105912 ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
105913 ** occurs, return SQLITE_SCHEMA.
105914 */
105915 SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
105916   int rc;
105917   sqlite3_stmt *pNew;
105918   const char *zSql;
105919   sqlite3 *db;
105920
105921   assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
105922   zSql = sqlite3_sql((sqlite3_stmt *)p);
105923   assert( zSql!=0 );  /* Reprepare only called for prepare_v2() statements */
105924   db = sqlite3VdbeDb(p);
105925   assert( sqlite3_mutex_held(db->mutex) );
105926   rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
105927   if( rc ){
105928     if( rc==SQLITE_NOMEM ){
105929       db->mallocFailed = 1;
105930     }
105931     assert( pNew==0 );
105932     return rc;
105933   }else{
105934     assert( pNew!=0 );
105935   }
105936   sqlite3VdbeSwap((Vdbe*)pNew, p);
105937   sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
105938   sqlite3VdbeResetStepResult((Vdbe*)pNew);
105939   sqlite3VdbeFinalize((Vdbe*)pNew);
105940   return SQLITE_OK;
105941 }
105942
105943
105944 /*
105945 ** Two versions of the official API.  Legacy and new use.  In the legacy
105946 ** version, the original SQL text is not saved in the prepared statement
105947 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
105948 ** sqlite3_step().  In the new version, the original SQL text is retained
105949 ** and the statement is automatically recompiled if an schema change
105950 ** occurs.
105951 */
105952 SQLITE_API int SQLITE_STDCALL sqlite3_prepare(
105953   sqlite3 *db,              /* Database handle. */
105954   const char *zSql,         /* UTF-8 encoded SQL statement. */
105955   int nBytes,               /* Length of zSql in bytes. */
105956   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
105957   const char **pzTail       /* OUT: End of parsed string */
105958 ){
105959   int rc;
105960   rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
105961   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
105962   return rc;
105963 }
105964 SQLITE_API int SQLITE_STDCALL sqlite3_prepare_v2(
105965   sqlite3 *db,              /* Database handle. */
105966   const char *zSql,         /* UTF-8 encoded SQL statement. */
105967   int nBytes,               /* Length of zSql in bytes. */
105968   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
105969   const char **pzTail       /* OUT: End of parsed string */
105970 ){
105971   int rc;
105972   rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
105973   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
105974   return rc;
105975 }
105976
105977
105978 #ifndef SQLITE_OMIT_UTF16
105979 /*
105980 ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
105981 */
105982 static int sqlite3Prepare16(
105983   sqlite3 *db,              /* Database handle. */ 
105984   const void *zSql,         /* UTF-16 encoded SQL statement. */
105985   int nBytes,               /* Length of zSql in bytes. */
105986   int saveSqlFlag,          /* True to save SQL text into the sqlite3_stmt */
105987   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
105988   const void **pzTail       /* OUT: End of parsed string */
105989 ){
105990   /* This function currently works by first transforming the UTF-16
105991   ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
105992   ** tricky bit is figuring out the pointer to return in *pzTail.
105993   */
105994   char *zSql8;
105995   const char *zTail8 = 0;
105996   int rc = SQLITE_OK;
105997
105998 #ifdef SQLITE_ENABLE_API_ARMOR
105999   if( ppStmt==0 ) return SQLITE_MISUSE_BKPT;
106000 #endif
106001   *ppStmt = 0;
106002   if( !sqlite3SafetyCheckOk(db)||zSql==0 ){
106003     return SQLITE_MISUSE_BKPT;
106004   }
106005   if( nBytes>=0 ){
106006     int sz;
106007     const char *z = (const char*)zSql;
106008     for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
106009     nBytes = sz;
106010   }
106011   sqlite3_mutex_enter(db->mutex);
106012   zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
106013   if( zSql8 ){
106014     rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
106015   }
106016
106017   if( zTail8 && pzTail ){
106018     /* If sqlite3_prepare returns a tail pointer, we calculate the
106019     ** equivalent pointer into the UTF-16 string by counting the unicode
106020     ** characters between zSql8 and zTail8, and then returning a pointer
106021     ** the same number of characters into the UTF-16 string.
106022     */
106023     int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
106024     *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
106025   }
106026   sqlite3DbFree(db, zSql8); 
106027   rc = sqlite3ApiExit(db, rc);
106028   sqlite3_mutex_leave(db->mutex);
106029   return rc;
106030 }
106031
106032 /*
106033 ** Two versions of the official API.  Legacy and new use.  In the legacy
106034 ** version, the original SQL text is not saved in the prepared statement
106035 ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
106036 ** sqlite3_step().  In the new version, the original SQL text is retained
106037 ** and the statement is automatically recompiled if an schema change
106038 ** occurs.
106039 */
106040 SQLITE_API int SQLITE_STDCALL sqlite3_prepare16(
106041   sqlite3 *db,              /* Database handle. */ 
106042   const void *zSql,         /* UTF-16 encoded SQL statement. */
106043   int nBytes,               /* Length of zSql in bytes. */
106044   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
106045   const void **pzTail       /* OUT: End of parsed string */
106046 ){
106047   int rc;
106048   rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
106049   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
106050   return rc;
106051 }
106052 SQLITE_API int SQLITE_STDCALL sqlite3_prepare16_v2(
106053   sqlite3 *db,              /* Database handle. */ 
106054   const void *zSql,         /* UTF-16 encoded SQL statement. */
106055   int nBytes,               /* Length of zSql in bytes. */
106056   sqlite3_stmt **ppStmt,    /* OUT: A pointer to the prepared statement */
106057   const void **pzTail       /* OUT: End of parsed string */
106058 ){
106059   int rc;
106060   rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
106061   assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 );  /* VERIFY: F13021 */
106062   return rc;
106063 }
106064
106065 #endif /* SQLITE_OMIT_UTF16 */
106066
106067 /************** End of prepare.c *********************************************/
106068 /************** Begin file select.c ******************************************/
106069 /*
106070 ** 2001 September 15
106071 **
106072 ** The author disclaims copyright to this source code.  In place of
106073 ** a legal notice, here is a blessing:
106074 **
106075 **    May you do good and not evil.
106076 **    May you find forgiveness for yourself and forgive others.
106077 **    May you share freely, never taking more than you give.
106078 **
106079 *************************************************************************
106080 ** This file contains C code routines that are called by the parser
106081 ** to handle SELECT statements in SQLite.
106082 */
106083
106084 /*
106085 ** Trace output macros
106086 */
106087 #if SELECTTRACE_ENABLED
106088 /***/ int sqlite3SelectTrace = 0;
106089 # define SELECTTRACE(K,P,S,X)  \
106090   if(sqlite3SelectTrace&(K))   \
106091     sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",(S)->zSelName,(S)),\
106092     sqlite3DebugPrintf X
106093 #else
106094 # define SELECTTRACE(K,P,S,X)
106095 #endif
106096
106097
106098 /*
106099 ** An instance of the following object is used to record information about
106100 ** how to process the DISTINCT keyword, to simplify passing that information
106101 ** into the selectInnerLoop() routine.
106102 */
106103 typedef struct DistinctCtx DistinctCtx;
106104 struct DistinctCtx {
106105   u8 isTnct;      /* True if the DISTINCT keyword is present */
106106   u8 eTnctType;   /* One of the WHERE_DISTINCT_* operators */
106107   int tabTnct;    /* Ephemeral table used for DISTINCT processing */
106108   int addrTnct;   /* Address of OP_OpenEphemeral opcode for tabTnct */
106109 };
106110
106111 /*
106112 ** An instance of the following object is used to record information about
106113 ** the ORDER BY (or GROUP BY) clause of query is being coded.
106114 */
106115 typedef struct SortCtx SortCtx;
106116 struct SortCtx {
106117   ExprList *pOrderBy;   /* The ORDER BY (or GROUP BY clause) */
106118   int nOBSat;           /* Number of ORDER BY terms satisfied by indices */
106119   int iECursor;         /* Cursor number for the sorter */
106120   int regReturn;        /* Register holding block-output return address */
106121   int labelBkOut;       /* Start label for the block-output subroutine */
106122   int addrSortIndex;    /* Address of the OP_SorterOpen or OP_OpenEphemeral */
106123   u8 sortFlags;         /* Zero or more SORTFLAG_* bits */
106124 };
106125 #define SORTFLAG_UseSorter  0x01   /* Use SorterOpen instead of OpenEphemeral */
106126
106127 /*
106128 ** Delete all the content of a Select structure.  Deallocate the structure
106129 ** itself only if bFree is true.
106130 */
106131 static void clearSelect(sqlite3 *db, Select *p, int bFree){
106132   while( p ){
106133     Select *pPrior = p->pPrior;
106134     sqlite3ExprListDelete(db, p->pEList);
106135     sqlite3SrcListDelete(db, p->pSrc);
106136     sqlite3ExprDelete(db, p->pWhere);
106137     sqlite3ExprListDelete(db, p->pGroupBy);
106138     sqlite3ExprDelete(db, p->pHaving);
106139     sqlite3ExprListDelete(db, p->pOrderBy);
106140     sqlite3ExprDelete(db, p->pLimit);
106141     sqlite3ExprDelete(db, p->pOffset);
106142     sqlite3WithDelete(db, p->pWith);
106143     if( bFree ) sqlite3DbFree(db, p);
106144     p = pPrior;
106145     bFree = 1;
106146   }
106147 }
106148
106149 /*
106150 ** Initialize a SelectDest structure.
106151 */
106152 SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
106153   pDest->eDest = (u8)eDest;
106154   pDest->iSDParm = iParm;
106155   pDest->affSdst = 0;
106156   pDest->iSdst = 0;
106157   pDest->nSdst = 0;
106158 }
106159
106160
106161 /*
106162 ** Allocate a new Select structure and return a pointer to that
106163 ** structure.
106164 */
106165 SQLITE_PRIVATE Select *sqlite3SelectNew(
106166   Parse *pParse,        /* Parsing context */
106167   ExprList *pEList,     /* which columns to include in the result */
106168   SrcList *pSrc,        /* the FROM clause -- which tables to scan */
106169   Expr *pWhere,         /* the WHERE clause */
106170   ExprList *pGroupBy,   /* the GROUP BY clause */
106171   Expr *pHaving,        /* the HAVING clause */
106172   ExprList *pOrderBy,   /* the ORDER BY clause */
106173   u16 selFlags,         /* Flag parameters, such as SF_Distinct */
106174   Expr *pLimit,         /* LIMIT value.  NULL means not used */
106175   Expr *pOffset         /* OFFSET value.  NULL means no offset */
106176 ){
106177   Select *pNew;
106178   Select standin;
106179   sqlite3 *db = pParse->db;
106180   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
106181   assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
106182   if( pNew==0 ){
106183     assert( db->mallocFailed );
106184     pNew = &standin;
106185     memset(pNew, 0, sizeof(*pNew));
106186   }
106187   if( pEList==0 ){
106188     pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
106189   }
106190   pNew->pEList = pEList;
106191   if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
106192   pNew->pSrc = pSrc;
106193   pNew->pWhere = pWhere;
106194   pNew->pGroupBy = pGroupBy;
106195   pNew->pHaving = pHaving;
106196   pNew->pOrderBy = pOrderBy;
106197   pNew->selFlags = selFlags;
106198   pNew->op = TK_SELECT;
106199   pNew->pLimit = pLimit;
106200   pNew->pOffset = pOffset;
106201   assert( pOffset==0 || pLimit!=0 );
106202   pNew->addrOpenEphm[0] = -1;
106203   pNew->addrOpenEphm[1] = -1;
106204   if( db->mallocFailed ) {
106205     clearSelect(db, pNew, pNew!=&standin);
106206     pNew = 0;
106207   }else{
106208     assert( pNew->pSrc!=0 || pParse->nErr>0 );
106209   }
106210   assert( pNew!=&standin );
106211   return pNew;
106212 }
106213
106214 #if SELECTTRACE_ENABLED
106215 /*
106216 ** Set the name of a Select object
106217 */
106218 SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
106219   if( p && zName ){
106220     sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
106221   }
106222 }
106223 #endif
106224
106225
106226 /*
106227 ** Delete the given Select structure and all of its substructures.
106228 */
106229 SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
106230   clearSelect(db, p, 1);
106231 }
106232
106233 /*
106234 ** Return a pointer to the right-most SELECT statement in a compound.
106235 */
106236 static Select *findRightmost(Select *p){
106237   while( p->pNext ) p = p->pNext;
106238   return p;
106239 }
106240
106241 /*
106242 ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
106243 ** type of join.  Return an integer constant that expresses that type
106244 ** in terms of the following bit values:
106245 **
106246 **     JT_INNER
106247 **     JT_CROSS
106248 **     JT_OUTER
106249 **     JT_NATURAL
106250 **     JT_LEFT
106251 **     JT_RIGHT
106252 **
106253 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
106254 **
106255 ** If an illegal or unsupported join type is seen, then still return
106256 ** a join type, but put an error in the pParse structure.
106257 */
106258 SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
106259   int jointype = 0;
106260   Token *apAll[3];
106261   Token *p;
106262                              /*   0123456789 123456789 123456789 123 */
106263   static const char zKeyText[] = "naturaleftouterightfullinnercross";
106264   static const struct {
106265     u8 i;        /* Beginning of keyword text in zKeyText[] */
106266     u8 nChar;    /* Length of the keyword in characters */
106267     u8 code;     /* Join type mask */
106268   } aKeyword[] = {
106269     /* natural */ { 0,  7, JT_NATURAL                },
106270     /* left    */ { 6,  4, JT_LEFT|JT_OUTER          },
106271     /* outer   */ { 10, 5, JT_OUTER                  },
106272     /* right   */ { 14, 5, JT_RIGHT|JT_OUTER         },
106273     /* full    */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
106274     /* inner   */ { 23, 5, JT_INNER                  },
106275     /* cross   */ { 28, 5, JT_INNER|JT_CROSS         },
106276   };
106277   int i, j;
106278   apAll[0] = pA;
106279   apAll[1] = pB;
106280   apAll[2] = pC;
106281   for(i=0; i<3 && apAll[i]; i++){
106282     p = apAll[i];
106283     for(j=0; j<ArraySize(aKeyword); j++){
106284       if( p->n==aKeyword[j].nChar 
106285           && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
106286         jointype |= aKeyword[j].code;
106287         break;
106288       }
106289     }
106290     testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
106291     if( j>=ArraySize(aKeyword) ){
106292       jointype |= JT_ERROR;
106293       break;
106294     }
106295   }
106296   if(
106297      (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
106298      (jointype & JT_ERROR)!=0
106299   ){
106300     const char *zSp = " ";
106301     assert( pB!=0 );
106302     if( pC==0 ){ zSp++; }
106303     sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
106304        "%T %T%s%T", pA, pB, zSp, pC);
106305     jointype = JT_INNER;
106306   }else if( (jointype & JT_OUTER)!=0 
106307          && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
106308     sqlite3ErrorMsg(pParse, 
106309       "RIGHT and FULL OUTER JOINs are not currently supported");
106310     jointype = JT_INNER;
106311   }
106312   return jointype;
106313 }
106314
106315 /*
106316 ** Return the index of a column in a table.  Return -1 if the column
106317 ** is not contained in the table.
106318 */
106319 static int columnIndex(Table *pTab, const char *zCol){
106320   int i;
106321   for(i=0; i<pTab->nCol; i++){
106322     if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
106323   }
106324   return -1;
106325 }
106326
106327 /*
106328 ** Search the first N tables in pSrc, from left to right, looking for a
106329 ** table that has a column named zCol.  
106330 **
106331 ** When found, set *piTab and *piCol to the table index and column index
106332 ** of the matching column and return TRUE.
106333 **
106334 ** If not found, return FALSE.
106335 */
106336 static int tableAndColumnIndex(
106337   SrcList *pSrc,       /* Array of tables to search */
106338   int N,               /* Number of tables in pSrc->a[] to search */
106339   const char *zCol,    /* Name of the column we are looking for */
106340   int *piTab,          /* Write index of pSrc->a[] here */
106341   int *piCol           /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
106342 ){
106343   int i;               /* For looping over tables in pSrc */
106344   int iCol;            /* Index of column matching zCol */
106345
106346   assert( (piTab==0)==(piCol==0) );  /* Both or neither are NULL */
106347   for(i=0; i<N; i++){
106348     iCol = columnIndex(pSrc->a[i].pTab, zCol);
106349     if( iCol>=0 ){
106350       if( piTab ){
106351         *piTab = i;
106352         *piCol = iCol;
106353       }
106354       return 1;
106355     }
106356   }
106357   return 0;
106358 }
106359
106360 /*
106361 ** This function is used to add terms implied by JOIN syntax to the
106362 ** WHERE clause expression of a SELECT statement. The new term, which
106363 ** is ANDed with the existing WHERE clause, is of the form:
106364 **
106365 **    (tab1.col1 = tab2.col2)
106366 **
106367 ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the 
106368 ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
106369 ** column iColRight of tab2.
106370 */
106371 static void addWhereTerm(
106372   Parse *pParse,                  /* Parsing context */
106373   SrcList *pSrc,                  /* List of tables in FROM clause */
106374   int iLeft,                      /* Index of first table to join in pSrc */
106375   int iColLeft,                   /* Index of column in first table */
106376   int iRight,                     /* Index of second table in pSrc */
106377   int iColRight,                  /* Index of column in second table */
106378   int isOuterJoin,                /* True if this is an OUTER join */
106379   Expr **ppWhere                  /* IN/OUT: The WHERE clause to add to */
106380 ){
106381   sqlite3 *db = pParse->db;
106382   Expr *pE1;
106383   Expr *pE2;
106384   Expr *pEq;
106385
106386   assert( iLeft<iRight );
106387   assert( pSrc->nSrc>iRight );
106388   assert( pSrc->a[iLeft].pTab );
106389   assert( pSrc->a[iRight].pTab );
106390
106391   pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
106392   pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
106393
106394   pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
106395   if( pEq && isOuterJoin ){
106396     ExprSetProperty(pEq, EP_FromJoin);
106397     assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
106398     ExprSetVVAProperty(pEq, EP_NoReduce);
106399     pEq->iRightJoinTable = (i16)pE2->iTable;
106400   }
106401   *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
106402 }
106403
106404 /*
106405 ** Set the EP_FromJoin property on all terms of the given expression.
106406 ** And set the Expr.iRightJoinTable to iTable for every term in the
106407 ** expression.
106408 **
106409 ** The EP_FromJoin property is used on terms of an expression to tell
106410 ** the LEFT OUTER JOIN processing logic that this term is part of the
106411 ** join restriction specified in the ON or USING clause and not a part
106412 ** of the more general WHERE clause.  These terms are moved over to the
106413 ** WHERE clause during join processing but we need to remember that they
106414 ** originated in the ON or USING clause.
106415 **
106416 ** The Expr.iRightJoinTable tells the WHERE clause processing that the
106417 ** expression depends on table iRightJoinTable even if that table is not
106418 ** explicitly mentioned in the expression.  That information is needed
106419 ** for cases like this:
106420 **
106421 **    SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
106422 **
106423 ** The where clause needs to defer the handling of the t1.x=5
106424 ** term until after the t2 loop of the join.  In that way, a
106425 ** NULL t2 row will be inserted whenever t1.x!=5.  If we do not
106426 ** defer the handling of t1.x=5, it will be processed immediately
106427 ** after the t1 loop and rows with t1.x!=5 will never appear in
106428 ** the output, which is incorrect.
106429 */
106430 static void setJoinExpr(Expr *p, int iTable){
106431   while( p ){
106432     ExprSetProperty(p, EP_FromJoin);
106433     assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
106434     ExprSetVVAProperty(p, EP_NoReduce);
106435     p->iRightJoinTable = (i16)iTable;
106436     setJoinExpr(p->pLeft, iTable);
106437     p = p->pRight;
106438   } 
106439 }
106440
106441 /*
106442 ** This routine processes the join information for a SELECT statement.
106443 ** ON and USING clauses are converted into extra terms of the WHERE clause.
106444 ** NATURAL joins also create extra WHERE clause terms.
106445 **
106446 ** The terms of a FROM clause are contained in the Select.pSrc structure.
106447 ** The left most table is the first entry in Select.pSrc.  The right-most
106448 ** table is the last entry.  The join operator is held in the entry to
106449 ** the left.  Thus entry 0 contains the join operator for the join between
106450 ** entries 0 and 1.  Any ON or USING clauses associated with the join are
106451 ** also attached to the left entry.
106452 **
106453 ** This routine returns the number of errors encountered.
106454 */
106455 static int sqliteProcessJoin(Parse *pParse, Select *p){
106456   SrcList *pSrc;                  /* All tables in the FROM clause */
106457   int i, j;                       /* Loop counters */
106458   struct SrcList_item *pLeft;     /* Left table being joined */
106459   struct SrcList_item *pRight;    /* Right table being joined */
106460
106461   pSrc = p->pSrc;
106462   pLeft = &pSrc->a[0];
106463   pRight = &pLeft[1];
106464   for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
106465     Table *pLeftTab = pLeft->pTab;
106466     Table *pRightTab = pRight->pTab;
106467     int isOuter;
106468
106469     if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
106470     isOuter = (pRight->jointype & JT_OUTER)!=0;
106471
106472     /* When the NATURAL keyword is present, add WHERE clause terms for
106473     ** every column that the two tables have in common.
106474     */
106475     if( pRight->jointype & JT_NATURAL ){
106476       if( pRight->pOn || pRight->pUsing ){
106477         sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
106478            "an ON or USING clause", 0);
106479         return 1;
106480       }
106481       for(j=0; j<pRightTab->nCol; j++){
106482         char *zName;   /* Name of column in the right table */
106483         int iLeft;     /* Matching left table */
106484         int iLeftCol;  /* Matching column in the left table */
106485
106486         zName = pRightTab->aCol[j].zName;
106487         if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
106488           addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
106489                        isOuter, &p->pWhere);
106490         }
106491       }
106492     }
106493
106494     /* Disallow both ON and USING clauses in the same join
106495     */
106496     if( pRight->pOn && pRight->pUsing ){
106497       sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
106498         "clauses in the same join");
106499       return 1;
106500     }
106501
106502     /* Add the ON clause to the end of the WHERE clause, connected by
106503     ** an AND operator.
106504     */
106505     if( pRight->pOn ){
106506       if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
106507       p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
106508       pRight->pOn = 0;
106509     }
106510
106511     /* Create extra terms on the WHERE clause for each column named
106512     ** in the USING clause.  Example: If the two tables to be joined are 
106513     ** A and B and the USING clause names X, Y, and Z, then add this
106514     ** to the WHERE clause:    A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
106515     ** Report an error if any column mentioned in the USING clause is
106516     ** not contained in both tables to be joined.
106517     */
106518     if( pRight->pUsing ){
106519       IdList *pList = pRight->pUsing;
106520       for(j=0; j<pList->nId; j++){
106521         char *zName;     /* Name of the term in the USING clause */
106522         int iLeft;       /* Table on the left with matching column name */
106523         int iLeftCol;    /* Column number of matching column on the left */
106524         int iRightCol;   /* Column number of matching column on the right */
106525
106526         zName = pList->a[j].zName;
106527         iRightCol = columnIndex(pRightTab, zName);
106528         if( iRightCol<0
106529          || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
106530         ){
106531           sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
106532             "not present in both tables", zName);
106533           return 1;
106534         }
106535         addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
106536                      isOuter, &p->pWhere);
106537       }
106538     }
106539   }
106540   return 0;
106541 }
106542
106543 /* Forward reference */
106544 static KeyInfo *keyInfoFromExprList(
106545   Parse *pParse,       /* Parsing context */
106546   ExprList *pList,     /* Form the KeyInfo object from this ExprList */
106547   int iStart,          /* Begin with this column of pList */
106548   int nExtra           /* Add this many extra columns to the end */
106549 );
106550
106551 /*
106552 ** Generate code that will push the record in registers regData
106553 ** through regData+nData-1 onto the sorter.
106554 */
106555 static void pushOntoSorter(
106556   Parse *pParse,         /* Parser context */
106557   SortCtx *pSort,        /* Information about the ORDER BY clause */
106558   Select *pSelect,       /* The whole SELECT statement */
106559   int regData,           /* First register holding data to be sorted */
106560   int nData,             /* Number of elements in the data array */
106561   int nPrefixReg         /* No. of reg prior to regData available for use */
106562 ){
106563   Vdbe *v = pParse->pVdbe;                         /* Stmt under construction */
106564   int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
106565   int nExpr = pSort->pOrderBy->nExpr;              /* No. of ORDER BY terms */
106566   int nBase = nExpr + bSeq + nData;                /* Fields in sorter record */
106567   int regBase;                                     /* Regs for sorter record */
106568   int regRecord = ++pParse->nMem;                  /* Assembled sorter record */
106569   int nOBSat = pSort->nOBSat;                      /* ORDER BY terms to skip */
106570   int op;                            /* Opcode to add sorter record to sorter */
106571
106572   assert( bSeq==0 || bSeq==1 );
106573   if( nPrefixReg ){
106574     assert( nPrefixReg==nExpr+bSeq );
106575     regBase = regData - nExpr - bSeq;
106576   }else{
106577     regBase = pParse->nMem + 1;
106578     pParse->nMem += nBase;
106579   }
106580   sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, SQLITE_ECEL_DUP);
106581   if( bSeq ){
106582     sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
106583   }
106584   if( nPrefixReg==0 ){
106585     sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
106586   }
106587
106588   sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
106589   if( nOBSat>0 ){
106590     int regPrevKey;   /* The first nOBSat columns of the previous row */
106591     int addrFirst;    /* Address of the OP_IfNot opcode */
106592     int addrJmp;      /* Address of the OP_Jump opcode */
106593     VdbeOp *pOp;      /* Opcode that opens the sorter */
106594     int nKey;         /* Number of sorting key columns, including OP_Sequence */
106595     KeyInfo *pKI;     /* Original KeyInfo on the sorter table */
106596
106597     regPrevKey = pParse->nMem+1;
106598     pParse->nMem += pSort->nOBSat;
106599     nKey = nExpr - pSort->nOBSat + bSeq;
106600     if( bSeq ){
106601       addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr); 
106602     }else{
106603       addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
106604     }
106605     VdbeCoverage(v);
106606     sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
106607     pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
106608     if( pParse->db->mallocFailed ) return;
106609     pOp->p2 = nKey + nData;
106610     pKI = pOp->p4.pKeyInfo;
106611     memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
106612     sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
106613     testcase( pKI->nXField>2 );
106614     pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat,
106615                                            pKI->nXField-1);
106616     addrJmp = sqlite3VdbeCurrentAddr(v);
106617     sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
106618     pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
106619     pSort->regReturn = ++pParse->nMem;
106620     sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
106621     sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
106622     sqlite3VdbeJumpHere(v, addrFirst);
106623     sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
106624     sqlite3VdbeJumpHere(v, addrJmp);
106625   }
106626   if( pSort->sortFlags & SORTFLAG_UseSorter ){
106627     op = OP_SorterInsert;
106628   }else{
106629     op = OP_IdxInsert;
106630   }
106631   sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
106632   if( pSelect->iLimit ){
106633     int addr;
106634     int iLimit;
106635     if( pSelect->iOffset ){
106636       iLimit = pSelect->iOffset+1;
106637     }else{
106638       iLimit = pSelect->iLimit;
106639     }
106640     addr = sqlite3VdbeAddOp3(v, OP_IfNotZero, iLimit, 0, -1); VdbeCoverage(v);
106641     sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
106642     sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
106643     sqlite3VdbeJumpHere(v, addr);
106644   }
106645 }
106646
106647 /*
106648 ** Add code to implement the OFFSET
106649 */
106650 static void codeOffset(
106651   Vdbe *v,          /* Generate code into this VM */
106652   int iOffset,      /* Register holding the offset counter */
106653   int iContinue     /* Jump here to skip the current record */
106654 ){
106655   if( iOffset>0 ){
106656     int addr;
106657     addr = sqlite3VdbeAddOp3(v, OP_IfNeg, iOffset, 0, -1); VdbeCoverage(v);
106658     sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
106659     VdbeComment((v, "skip OFFSET records"));
106660     sqlite3VdbeJumpHere(v, addr);
106661   }
106662 }
106663
106664 /*
106665 ** Add code that will check to make sure the N registers starting at iMem
106666 ** form a distinct entry.  iTab is a sorting index that holds previously
106667 ** seen combinations of the N values.  A new entry is made in iTab
106668 ** if the current N values are new.
106669 **
106670 ** A jump to addrRepeat is made and the N+1 values are popped from the
106671 ** stack if the top N elements are not distinct.
106672 */
106673 static void codeDistinct(
106674   Parse *pParse,     /* Parsing and code generating context */
106675   int iTab,          /* A sorting index used to test for distinctness */
106676   int addrRepeat,    /* Jump to here if not distinct */
106677   int N,             /* Number of elements */
106678   int iMem           /* First element */
106679 ){
106680   Vdbe *v;
106681   int r1;
106682
106683   v = pParse->pVdbe;
106684   r1 = sqlite3GetTempReg(pParse);
106685   sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
106686   sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
106687   sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
106688   sqlite3ReleaseTempReg(pParse, r1);
106689 }
106690
106691 #ifndef SQLITE_OMIT_SUBQUERY
106692 /*
106693 ** Generate an error message when a SELECT is used within a subexpression
106694 ** (example:  "a IN (SELECT * FROM table)") but it has more than 1 result
106695 ** column.  We do this in a subroutine because the error used to occur
106696 ** in multiple places.  (The error only occurs in one place now, but we
106697 ** retain the subroutine to minimize code disruption.)
106698 */
106699 static int checkForMultiColumnSelectError(
106700   Parse *pParse,       /* Parse context. */
106701   SelectDest *pDest,   /* Destination of SELECT results */
106702   int nExpr            /* Number of result columns returned by SELECT */
106703 ){
106704   int eDest = pDest->eDest;
106705   if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
106706     sqlite3ErrorMsg(pParse, "only a single result allowed for "
106707        "a SELECT that is part of an expression");
106708     return 1;
106709   }else{
106710     return 0;
106711   }
106712 }
106713 #endif
106714
106715 /*
106716 ** This routine generates the code for the inside of the inner loop
106717 ** of a SELECT.
106718 **
106719 ** If srcTab is negative, then the pEList expressions
106720 ** are evaluated in order to get the data for this row.  If srcTab is
106721 ** zero or more, then data is pulled from srcTab and pEList is used only 
106722 ** to get number columns and the datatype for each column.
106723 */
106724 static void selectInnerLoop(
106725   Parse *pParse,          /* The parser context */
106726   Select *p,              /* The complete select statement being coded */
106727   ExprList *pEList,       /* List of values being extracted */
106728   int srcTab,             /* Pull data from this table */
106729   SortCtx *pSort,         /* If not NULL, info on how to process ORDER BY */
106730   DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
106731   SelectDest *pDest,      /* How to dispose of the results */
106732   int iContinue,          /* Jump here to continue with next row */
106733   int iBreak              /* Jump here to break out of the inner loop */
106734 ){
106735   Vdbe *v = pParse->pVdbe;
106736   int i;
106737   int hasDistinct;        /* True if the DISTINCT keyword is present */
106738   int regResult;              /* Start of memory holding result set */
106739   int eDest = pDest->eDest;   /* How to dispose of results */
106740   int iParm = pDest->iSDParm; /* First argument to disposal method */
106741   int nResultCol;             /* Number of result columns */
106742   int nPrefixReg = 0;         /* Number of extra registers before regResult */
106743
106744   assert( v );
106745   assert( pEList!=0 );
106746   hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
106747   if( pSort && pSort->pOrderBy==0 ) pSort = 0;
106748   if( pSort==0 && !hasDistinct ){
106749     assert( iContinue!=0 );
106750     codeOffset(v, p->iOffset, iContinue);
106751   }
106752
106753   /* Pull the requested columns.
106754   */
106755   nResultCol = pEList->nExpr;
106756
106757   if( pDest->iSdst==0 ){
106758     if( pSort ){
106759       nPrefixReg = pSort->pOrderBy->nExpr;
106760       if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
106761       pParse->nMem += nPrefixReg;
106762     }
106763     pDest->iSdst = pParse->nMem+1;
106764     pParse->nMem += nResultCol;
106765   }else if( pDest->iSdst+nResultCol > pParse->nMem ){
106766     /* This is an error condition that can result, for example, when a SELECT
106767     ** on the right-hand side of an INSERT contains more result columns than
106768     ** there are columns in the table on the left.  The error will be caught
106769     ** and reported later.  But we need to make sure enough memory is allocated
106770     ** to avoid other spurious errors in the meantime. */
106771     pParse->nMem += nResultCol;
106772   }
106773   pDest->nSdst = nResultCol;
106774   regResult = pDest->iSdst;
106775   if( srcTab>=0 ){
106776     for(i=0; i<nResultCol; i++){
106777       sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
106778       VdbeComment((v, "%s", pEList->a[i].zName));
106779     }
106780   }else if( eDest!=SRT_Exists ){
106781     /* If the destination is an EXISTS(...) expression, the actual
106782     ** values returned by the SELECT are not required.
106783     */
106784     sqlite3ExprCodeExprList(pParse, pEList, regResult,
106785                   (eDest==SRT_Output||eDest==SRT_Coroutine)?SQLITE_ECEL_DUP:0);
106786   }
106787
106788   /* If the DISTINCT keyword was present on the SELECT statement
106789   ** and this row has been seen before, then do not make this row
106790   ** part of the result.
106791   */
106792   if( hasDistinct ){
106793     switch( pDistinct->eTnctType ){
106794       case WHERE_DISTINCT_ORDERED: {
106795         VdbeOp *pOp;            /* No longer required OpenEphemeral instr. */
106796         int iJump;              /* Jump destination */
106797         int regPrev;            /* Previous row content */
106798
106799         /* Allocate space for the previous row */
106800         regPrev = pParse->nMem+1;
106801         pParse->nMem += nResultCol;
106802
106803         /* Change the OP_OpenEphemeral coded earlier to an OP_Null
106804         ** sets the MEM_Cleared bit on the first register of the
106805         ** previous value.  This will cause the OP_Ne below to always
106806         ** fail on the first iteration of the loop even if the first
106807         ** row is all NULLs.
106808         */
106809         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
106810         pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
106811         pOp->opcode = OP_Null;
106812         pOp->p1 = 1;
106813         pOp->p2 = regPrev;
106814
106815         iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
106816         for(i=0; i<nResultCol; i++){
106817           CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
106818           if( i<nResultCol-1 ){
106819             sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
106820             VdbeCoverage(v);
106821           }else{
106822             sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
106823             VdbeCoverage(v);
106824            }
106825           sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
106826           sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
106827         }
106828         assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
106829         sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
106830         break;
106831       }
106832
106833       case WHERE_DISTINCT_UNIQUE: {
106834         sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
106835         break;
106836       }
106837
106838       default: {
106839         assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
106840         codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, regResult);
106841         break;
106842       }
106843     }
106844     if( pSort==0 ){
106845       codeOffset(v, p->iOffset, iContinue);
106846     }
106847   }
106848
106849   switch( eDest ){
106850     /* In this mode, write each query result to the key of the temporary
106851     ** table iParm.
106852     */
106853 #ifndef SQLITE_OMIT_COMPOUND_SELECT
106854     case SRT_Union: {
106855       int r1;
106856       r1 = sqlite3GetTempReg(pParse);
106857       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
106858       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
106859       sqlite3ReleaseTempReg(pParse, r1);
106860       break;
106861     }
106862
106863     /* Construct a record from the query result, but instead of
106864     ** saving that record, use it as a key to delete elements from
106865     ** the temporary table iParm.
106866     */
106867     case SRT_Except: {
106868       sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
106869       break;
106870     }
106871 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
106872
106873     /* Store the result as data using a unique key.
106874     */
106875     case SRT_Fifo:
106876     case SRT_DistFifo:
106877     case SRT_Table:
106878     case SRT_EphemTab: {
106879       int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
106880       testcase( eDest==SRT_Table );
106881       testcase( eDest==SRT_EphemTab );
106882       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
106883 #ifndef SQLITE_OMIT_CTE
106884       if( eDest==SRT_DistFifo ){
106885         /* If the destination is DistFifo, then cursor (iParm+1) is open
106886         ** on an ephemeral index. If the current row is already present
106887         ** in the index, do not write it to the output. If not, add the
106888         ** current row to the index and proceed with writing it to the
106889         ** output table as well.  */
106890         int addr = sqlite3VdbeCurrentAddr(v) + 4;
106891         sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); VdbeCoverage(v);
106892         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
106893         assert( pSort==0 );
106894       }
106895 #endif
106896       if( pSort ){
106897         pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, 1, nPrefixReg);
106898       }else{
106899         int r2 = sqlite3GetTempReg(pParse);
106900         sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
106901         sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
106902         sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
106903         sqlite3ReleaseTempReg(pParse, r2);
106904       }
106905       sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
106906       break;
106907     }
106908
106909 #ifndef SQLITE_OMIT_SUBQUERY
106910     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
106911     ** then there should be a single item on the stack.  Write this
106912     ** item into the set table with bogus data.
106913     */
106914     case SRT_Set: {
106915       assert( nResultCol==1 );
106916       pDest->affSdst =
106917                   sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
106918       if( pSort ){
106919         /* At first glance you would think we could optimize out the
106920         ** ORDER BY in this case since the order of entries in the set
106921         ** does not matter.  But there might be a LIMIT clause, in which
106922         ** case the order does matter */
106923         pushOntoSorter(pParse, pSort, p, regResult, 1, nPrefixReg);
106924       }else{
106925         int r1 = sqlite3GetTempReg(pParse);
106926         sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
106927         sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
106928         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
106929         sqlite3ReleaseTempReg(pParse, r1);
106930       }
106931       break;
106932     }
106933
106934     /* If any row exist in the result set, record that fact and abort.
106935     */
106936     case SRT_Exists: {
106937       sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
106938       /* The LIMIT clause will terminate the loop for us */
106939       break;
106940     }
106941
106942     /* If this is a scalar select that is part of an expression, then
106943     ** store the results in the appropriate memory cell and break out
106944     ** of the scan loop.
106945     */
106946     case SRT_Mem: {
106947       assert( nResultCol==1 );
106948       if( pSort ){
106949         pushOntoSorter(pParse, pSort, p, regResult, 1, nPrefixReg);
106950       }else{
106951         assert( regResult==iParm );
106952         /* The LIMIT clause will jump out of the loop for us */
106953       }
106954       break;
106955     }
106956 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
106957
106958     case SRT_Coroutine:       /* Send data to a co-routine */
106959     case SRT_Output: {        /* Return the results */
106960       testcase( eDest==SRT_Coroutine );
106961       testcase( eDest==SRT_Output );
106962       if( pSort ){
106963         pushOntoSorter(pParse, pSort, p, regResult, nResultCol, nPrefixReg);
106964       }else if( eDest==SRT_Coroutine ){
106965         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
106966       }else{
106967         sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
106968         sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
106969       }
106970       break;
106971     }
106972
106973 #ifndef SQLITE_OMIT_CTE
106974     /* Write the results into a priority queue that is order according to
106975     ** pDest->pOrderBy (in pSO).  pDest->iSDParm (in iParm) is the cursor for an
106976     ** index with pSO->nExpr+2 columns.  Build a key using pSO for the first
106977     ** pSO->nExpr columns, then make sure all keys are unique by adding a
106978     ** final OP_Sequence column.  The last column is the record as a blob.
106979     */
106980     case SRT_DistQueue:
106981     case SRT_Queue: {
106982       int nKey;
106983       int r1, r2, r3;
106984       int addrTest = 0;
106985       ExprList *pSO;
106986       pSO = pDest->pOrderBy;
106987       assert( pSO );
106988       nKey = pSO->nExpr;
106989       r1 = sqlite3GetTempReg(pParse);
106990       r2 = sqlite3GetTempRange(pParse, nKey+2);
106991       r3 = r2+nKey+1;
106992       if( eDest==SRT_DistQueue ){
106993         /* If the destination is DistQueue, then cursor (iParm+1) is open
106994         ** on a second ephemeral index that holds all values every previously
106995         ** added to the queue. */
106996         addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0, 
106997                                         regResult, nResultCol);
106998         VdbeCoverage(v);
106999       }
107000       sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
107001       if( eDest==SRT_DistQueue ){
107002         sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
107003         sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
107004       }
107005       for(i=0; i<nKey; i++){
107006         sqlite3VdbeAddOp2(v, OP_SCopy,
107007                           regResult + pSO->a[i].u.x.iOrderByCol - 1,
107008                           r2+i);
107009       }
107010       sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
107011       sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
107012       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
107013       if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
107014       sqlite3ReleaseTempReg(pParse, r1);
107015       sqlite3ReleaseTempRange(pParse, r2, nKey+2);
107016       break;
107017     }
107018 #endif /* SQLITE_OMIT_CTE */
107019
107020
107021
107022 #if !defined(SQLITE_OMIT_TRIGGER)
107023     /* Discard the results.  This is used for SELECT statements inside
107024     ** the body of a TRIGGER.  The purpose of such selects is to call
107025     ** user-defined functions that have side effects.  We do not care
107026     ** about the actual results of the select.
107027     */
107028     default: {
107029       assert( eDest==SRT_Discard );
107030       break;
107031     }
107032 #endif
107033   }
107034
107035   /* Jump to the end of the loop if the LIMIT is reached.  Except, if
107036   ** there is a sorter, in which case the sorter has already limited
107037   ** the output for us.
107038   */
107039   if( pSort==0 && p->iLimit ){
107040     sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
107041   }
107042 }
107043
107044 /*
107045 ** Allocate a KeyInfo object sufficient for an index of N key columns and
107046 ** X extra columns.
107047 */
107048 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
107049   KeyInfo *p = sqlite3DbMallocZero(0, 
107050                    sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1));
107051   if( p ){
107052     p->aSortOrder = (u8*)&p->aColl[N+X];
107053     p->nField = (u16)N;
107054     p->nXField = (u16)X;
107055     p->enc = ENC(db);
107056     p->db = db;
107057     p->nRef = 1;
107058   }else{
107059     db->mallocFailed = 1;
107060   }
107061   return p;
107062 }
107063
107064 /*
107065 ** Deallocate a KeyInfo object
107066 */
107067 SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
107068   if( p ){
107069     assert( p->nRef>0 );
107070     p->nRef--;
107071     if( p->nRef==0 ) sqlite3DbFree(0, p);
107072   }
107073 }
107074
107075 /*
107076 ** Make a new pointer to a KeyInfo object
107077 */
107078 SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
107079   if( p ){
107080     assert( p->nRef>0 );
107081     p->nRef++;
107082   }
107083   return p;
107084 }
107085
107086 #ifdef SQLITE_DEBUG
107087 /*
107088 ** Return TRUE if a KeyInfo object can be change.  The KeyInfo object
107089 ** can only be changed if this is just a single reference to the object.
107090 **
107091 ** This routine is used only inside of assert() statements.
107092 */
107093 SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
107094 #endif /* SQLITE_DEBUG */
107095
107096 /*
107097 ** Given an expression list, generate a KeyInfo structure that records
107098 ** the collating sequence for each expression in that expression list.
107099 **
107100 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
107101 ** KeyInfo structure is appropriate for initializing a virtual index to
107102 ** implement that clause.  If the ExprList is the result set of a SELECT
107103 ** then the KeyInfo structure is appropriate for initializing a virtual
107104 ** index to implement a DISTINCT test.
107105 **
107106 ** Space to hold the KeyInfo structure is obtained from malloc.  The calling
107107 ** function is responsible for seeing that this structure is eventually
107108 ** freed.
107109 */
107110 static KeyInfo *keyInfoFromExprList(
107111   Parse *pParse,       /* Parsing context */
107112   ExprList *pList,     /* Form the KeyInfo object from this ExprList */
107113   int iStart,          /* Begin with this column of pList */
107114   int nExtra           /* Add this many extra columns to the end */
107115 ){
107116   int nExpr;
107117   KeyInfo *pInfo;
107118   struct ExprList_item *pItem;
107119   sqlite3 *db = pParse->db;
107120   int i;
107121
107122   nExpr = pList->nExpr;
107123   pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
107124   if( pInfo ){
107125     assert( sqlite3KeyInfoIsWriteable(pInfo) );
107126     for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
107127       CollSeq *pColl;
107128       pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
107129       if( !pColl ) pColl = db->pDfltColl;
107130       pInfo->aColl[i-iStart] = pColl;
107131       pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
107132     }
107133   }
107134   return pInfo;
107135 }
107136
107137 #ifndef SQLITE_OMIT_COMPOUND_SELECT
107138 /*
107139 ** Name of the connection operator, used for error messages.
107140 */
107141 static const char *selectOpName(int id){
107142   char *z;
107143   switch( id ){
107144     case TK_ALL:       z = "UNION ALL";   break;
107145     case TK_INTERSECT: z = "INTERSECT";   break;
107146     case TK_EXCEPT:    z = "EXCEPT";      break;
107147     default:           z = "UNION";       break;
107148   }
107149   return z;
107150 }
107151 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
107152
107153 #ifndef SQLITE_OMIT_EXPLAIN
107154 /*
107155 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
107156 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
107157 ** where the caption is of the form:
107158 **
107159 **   "USE TEMP B-TREE FOR xxx"
107160 **
107161 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
107162 ** is determined by the zUsage argument.
107163 */
107164 static void explainTempTable(Parse *pParse, const char *zUsage){
107165   if( pParse->explain==2 ){
107166     Vdbe *v = pParse->pVdbe;
107167     char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
107168     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
107169   }
107170 }
107171
107172 /*
107173 ** Assign expression b to lvalue a. A second, no-op, version of this macro
107174 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
107175 ** in sqlite3Select() to assign values to structure member variables that
107176 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
107177 ** code with #ifndef directives.
107178 */
107179 # define explainSetInteger(a, b) a = b
107180
107181 #else
107182 /* No-op versions of the explainXXX() functions and macros. */
107183 # define explainTempTable(y,z)
107184 # define explainSetInteger(y,z)
107185 #endif
107186
107187 #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
107188 /*
107189 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
107190 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
107191 ** where the caption is of one of the two forms:
107192 **
107193 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
107194 **   "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
107195 **
107196 ** where iSub1 and iSub2 are the integers passed as the corresponding
107197 ** function parameters, and op is the text representation of the parameter
107198 ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
107199 ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is 
107200 ** false, or the second form if it is true.
107201 */
107202 static void explainComposite(
107203   Parse *pParse,                  /* Parse context */
107204   int op,                         /* One of TK_UNION, TK_EXCEPT etc. */
107205   int iSub1,                      /* Subquery id 1 */
107206   int iSub2,                      /* Subquery id 2 */
107207   int bUseTmp                     /* True if a temp table was used */
107208 ){
107209   assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
107210   if( pParse->explain==2 ){
107211     Vdbe *v = pParse->pVdbe;
107212     char *zMsg = sqlite3MPrintf(
107213         pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
107214         bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
107215     );
107216     sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
107217   }
107218 }
107219 #else
107220 /* No-op versions of the explainXXX() functions and macros. */
107221 # define explainComposite(v,w,x,y,z)
107222 #endif
107223
107224 /*
107225 ** If the inner loop was generated using a non-null pOrderBy argument,
107226 ** then the results were placed in a sorter.  After the loop is terminated
107227 ** we need to run the sorter and output the results.  The following
107228 ** routine generates the code needed to do that.
107229 */
107230 static void generateSortTail(
107231   Parse *pParse,    /* Parsing context */
107232   Select *p,        /* The SELECT statement */
107233   SortCtx *pSort,   /* Information on the ORDER BY clause */
107234   int nColumn,      /* Number of columns of data */
107235   SelectDest *pDest /* Write the sorted results here */
107236 ){
107237   Vdbe *v = pParse->pVdbe;                     /* The prepared statement */
107238   int addrBreak = sqlite3VdbeMakeLabel(v);     /* Jump here to exit loop */
107239   int addrContinue = sqlite3VdbeMakeLabel(v);  /* Jump here for next cycle */
107240   int addr;
107241   int addrOnce = 0;
107242   int iTab;
107243   ExprList *pOrderBy = pSort->pOrderBy;
107244   int eDest = pDest->eDest;
107245   int iParm = pDest->iSDParm;
107246   int regRow;
107247   int regRowid;
107248   int nKey;
107249   int iSortTab;                   /* Sorter cursor to read from */
107250   int nSortData;                  /* Trailing values to read from sorter */
107251   int i;
107252   int bSeq;                       /* True if sorter record includes seq. no. */
107253 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
107254   struct ExprList_item *aOutEx = p->pEList->a;
107255 #endif
107256
107257   if( pSort->labelBkOut ){
107258     sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
107259     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBreak);
107260     sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
107261   }
107262   iTab = pSort->iECursor;
107263   if( eDest==SRT_Output || eDest==SRT_Coroutine ){
107264     regRowid = 0;
107265     regRow = pDest->iSdst;
107266     nSortData = nColumn;
107267   }else{
107268     regRowid = sqlite3GetTempReg(pParse);
107269     regRow = sqlite3GetTempReg(pParse);
107270     nSortData = 1;
107271   }
107272   nKey = pOrderBy->nExpr - pSort->nOBSat;
107273   if( pSort->sortFlags & SORTFLAG_UseSorter ){
107274     int regSortOut = ++pParse->nMem;
107275     iSortTab = pParse->nTab++;
107276     if( pSort->labelBkOut ){
107277       addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
107278     }
107279     sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
107280     if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
107281     addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
107282     VdbeCoverage(v);
107283     codeOffset(v, p->iOffset, addrContinue);
107284     sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
107285     bSeq = 0;
107286   }else{
107287     addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
107288     codeOffset(v, p->iOffset, addrContinue);
107289     iSortTab = iTab;
107290     bSeq = 1;
107291   }
107292   for(i=0; i<nSortData; i++){
107293     sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i);
107294     VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
107295   }
107296   switch( eDest ){
107297     case SRT_Table:
107298     case SRT_EphemTab: {
107299       testcase( eDest==SRT_Table );
107300       testcase( eDest==SRT_EphemTab );
107301       sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
107302       sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
107303       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
107304       break;
107305     }
107306 #ifndef SQLITE_OMIT_SUBQUERY
107307     case SRT_Set: {
107308       assert( nColumn==1 );
107309       sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
107310                         &pDest->affSdst, 1);
107311       sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
107312       sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
107313       break;
107314     }
107315     case SRT_Mem: {
107316       assert( nColumn==1 );
107317       sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
107318       /* The LIMIT clause will terminate the loop for us */
107319       break;
107320     }
107321 #endif
107322     default: {
107323       assert( eDest==SRT_Output || eDest==SRT_Coroutine ); 
107324       testcase( eDest==SRT_Output );
107325       testcase( eDest==SRT_Coroutine );
107326       if( eDest==SRT_Output ){
107327         sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
107328         sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
107329       }else{
107330         sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
107331       }
107332       break;
107333     }
107334   }
107335   if( regRowid ){
107336     sqlite3ReleaseTempReg(pParse, regRow);
107337     sqlite3ReleaseTempReg(pParse, regRowid);
107338   }
107339   /* The bottom of the loop
107340   */
107341   sqlite3VdbeResolveLabel(v, addrContinue);
107342   if( pSort->sortFlags & SORTFLAG_UseSorter ){
107343     sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
107344   }else{
107345     sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
107346   }
107347   if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
107348   sqlite3VdbeResolveLabel(v, addrBreak);
107349 }
107350
107351 /*
107352 ** Return a pointer to a string containing the 'declaration type' of the
107353 ** expression pExpr. The string may be treated as static by the caller.
107354 **
107355 ** Also try to estimate the size of the returned value and return that
107356 ** result in *pEstWidth.
107357 **
107358 ** The declaration type is the exact datatype definition extracted from the
107359 ** original CREATE TABLE statement if the expression is a column. The
107360 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
107361 ** is considered a column can be complex in the presence of subqueries. The
107362 ** result-set expression in all of the following SELECT statements is 
107363 ** considered a column by this function.
107364 **
107365 **   SELECT col FROM tbl;
107366 **   SELECT (SELECT col FROM tbl;
107367 **   SELECT (SELECT col FROM tbl);
107368 **   SELECT abc FROM (SELECT col AS abc FROM tbl);
107369 ** 
107370 ** The declaration type for any expression other than a column is NULL.
107371 **
107372 ** This routine has either 3 or 6 parameters depending on whether or not
107373 ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
107374 */
107375 #ifdef SQLITE_ENABLE_COLUMN_METADATA
107376 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
107377 static const char *columnTypeImpl(
107378   NameContext *pNC, 
107379   Expr *pExpr,
107380   const char **pzOrigDb,
107381   const char **pzOrigTab,
107382   const char **pzOrigCol,
107383   u8 *pEstWidth
107384 ){
107385   char const *zOrigDb = 0;
107386   char const *zOrigTab = 0;
107387   char const *zOrigCol = 0;
107388 #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
107389 # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
107390 static const char *columnTypeImpl(
107391   NameContext *pNC, 
107392   Expr *pExpr,
107393   u8 *pEstWidth
107394 ){
107395 #endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */
107396   char const *zType = 0;
107397   int j;
107398   u8 estWidth = 1;
107399
107400   if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
107401   switch( pExpr->op ){
107402     case TK_AGG_COLUMN:
107403     case TK_COLUMN: {
107404       /* The expression is a column. Locate the table the column is being
107405       ** extracted from in NameContext.pSrcList. This table may be real
107406       ** database table or a subquery.
107407       */
107408       Table *pTab = 0;            /* Table structure column is extracted from */
107409       Select *pS = 0;             /* Select the column is extracted from */
107410       int iCol = pExpr->iColumn;  /* Index of column in pTab */
107411       testcase( pExpr->op==TK_AGG_COLUMN );
107412       testcase( pExpr->op==TK_COLUMN );
107413       while( pNC && !pTab ){
107414         SrcList *pTabList = pNC->pSrcList;
107415         for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
107416         if( j<pTabList->nSrc ){
107417           pTab = pTabList->a[j].pTab;
107418           pS = pTabList->a[j].pSelect;
107419         }else{
107420           pNC = pNC->pNext;
107421         }
107422       }
107423
107424       if( pTab==0 ){
107425         /* At one time, code such as "SELECT new.x" within a trigger would
107426         ** cause this condition to run.  Since then, we have restructured how
107427         ** trigger code is generated and so this condition is no longer 
107428         ** possible. However, it can still be true for statements like
107429         ** the following:
107430         **
107431         **   CREATE TABLE t1(col INTEGER);
107432         **   SELECT (SELECT t1.col) FROM FROM t1;
107433         **
107434         ** when columnType() is called on the expression "t1.col" in the 
107435         ** sub-select. In this case, set the column type to NULL, even
107436         ** though it should really be "INTEGER".
107437         **
107438         ** This is not a problem, as the column type of "t1.col" is never
107439         ** used. When columnType() is called on the expression 
107440         ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
107441         ** branch below.  */
107442         break;
107443       }
107444
107445       assert( pTab && pExpr->pTab==pTab );
107446       if( pS ){
107447         /* The "table" is actually a sub-select or a view in the FROM clause
107448         ** of the SELECT statement. Return the declaration type and origin
107449         ** data for the result-set column of the sub-select.
107450         */
107451         if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
107452           /* If iCol is less than zero, then the expression requests the
107453           ** rowid of the sub-select or view. This expression is legal (see 
107454           ** test case misc2.2.2) - it always evaluates to NULL.
107455           */
107456           NameContext sNC;
107457           Expr *p = pS->pEList->a[iCol].pExpr;
107458           sNC.pSrcList = pS->pSrc;
107459           sNC.pNext = pNC;
107460           sNC.pParse = pNC->pParse;
107461           zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth); 
107462         }
107463       }else if( pTab->pSchema ){
107464         /* A real table */
107465         assert( !pS );
107466         if( iCol<0 ) iCol = pTab->iPKey;
107467         assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
107468 #ifdef SQLITE_ENABLE_COLUMN_METADATA
107469         if( iCol<0 ){
107470           zType = "INTEGER";
107471           zOrigCol = "rowid";
107472         }else{
107473           zType = pTab->aCol[iCol].zType;
107474           zOrigCol = pTab->aCol[iCol].zName;
107475           estWidth = pTab->aCol[iCol].szEst;
107476         }
107477         zOrigTab = pTab->zName;
107478         if( pNC->pParse ){
107479           int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
107480           zOrigDb = pNC->pParse->db->aDb[iDb].zName;
107481         }
107482 #else
107483         if( iCol<0 ){
107484           zType = "INTEGER";
107485         }else{
107486           zType = pTab->aCol[iCol].zType;
107487           estWidth = pTab->aCol[iCol].szEst;
107488         }
107489 #endif
107490       }
107491       break;
107492     }
107493 #ifndef SQLITE_OMIT_SUBQUERY
107494     case TK_SELECT: {
107495       /* The expression is a sub-select. Return the declaration type and
107496       ** origin info for the single column in the result set of the SELECT
107497       ** statement.
107498       */
107499       NameContext sNC;
107500       Select *pS = pExpr->x.pSelect;
107501       Expr *p = pS->pEList->a[0].pExpr;
107502       assert( ExprHasProperty(pExpr, EP_xIsSelect) );
107503       sNC.pSrcList = pS->pSrc;
107504       sNC.pNext = pNC;
107505       sNC.pParse = pNC->pParse;
107506       zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth); 
107507       break;
107508     }
107509 #endif
107510   }
107511
107512 #ifdef SQLITE_ENABLE_COLUMN_METADATA  
107513   if( pzOrigDb ){
107514     assert( pzOrigTab && pzOrigCol );
107515     *pzOrigDb = zOrigDb;
107516     *pzOrigTab = zOrigTab;
107517     *pzOrigCol = zOrigCol;
107518   }
107519 #endif
107520   if( pEstWidth ) *pEstWidth = estWidth;
107521   return zType;
107522 }
107523
107524 /*
107525 ** Generate code that will tell the VDBE the declaration types of columns
107526 ** in the result set.
107527 */
107528 static void generateColumnTypes(
107529   Parse *pParse,      /* Parser context */
107530   SrcList *pTabList,  /* List of tables */
107531   ExprList *pEList    /* Expressions defining the result set */
107532 ){
107533 #ifndef SQLITE_OMIT_DECLTYPE
107534   Vdbe *v = pParse->pVdbe;
107535   int i;
107536   NameContext sNC;
107537   sNC.pSrcList = pTabList;
107538   sNC.pParse = pParse;
107539   for(i=0; i<pEList->nExpr; i++){
107540     Expr *p = pEList->a[i].pExpr;
107541     const char *zType;
107542 #ifdef SQLITE_ENABLE_COLUMN_METADATA
107543     const char *zOrigDb = 0;
107544     const char *zOrigTab = 0;
107545     const char *zOrigCol = 0;
107546     zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
107547
107548     /* The vdbe must make its own copy of the column-type and other 
107549     ** column specific strings, in case the schema is reset before this
107550     ** virtual machine is deleted.
107551     */
107552     sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
107553     sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
107554     sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
107555 #else
107556     zType = columnType(&sNC, p, 0, 0, 0, 0);
107557 #endif
107558     sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
107559   }
107560 #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
107561 }
107562
107563 /*
107564 ** Generate code that will tell the VDBE the names of columns
107565 ** in the result set.  This information is used to provide the
107566 ** azCol[] values in the callback.
107567 */
107568 static void generateColumnNames(
107569   Parse *pParse,      /* Parser context */
107570   SrcList *pTabList,  /* List of tables */
107571   ExprList *pEList    /* Expressions defining the result set */
107572 ){
107573   Vdbe *v = pParse->pVdbe;
107574   int i, j;
107575   sqlite3 *db = pParse->db;
107576   int fullNames, shortNames;
107577
107578 #ifndef SQLITE_OMIT_EXPLAIN
107579   /* If this is an EXPLAIN, skip this step */
107580   if( pParse->explain ){
107581     return;
107582   }
107583 #endif
107584
107585   if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
107586   pParse->colNamesSet = 1;
107587   fullNames = (db->flags & SQLITE_FullColNames)!=0;
107588   shortNames = (db->flags & SQLITE_ShortColNames)!=0;
107589   sqlite3VdbeSetNumCols(v, pEList->nExpr);
107590   for(i=0; i<pEList->nExpr; i++){
107591     Expr *p;
107592     p = pEList->a[i].pExpr;
107593     if( NEVER(p==0) ) continue;
107594     if( pEList->a[i].zName ){
107595       char *zName = pEList->a[i].zName;
107596       sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
107597     }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
107598       Table *pTab;
107599       char *zCol;
107600       int iCol = p->iColumn;
107601       for(j=0; ALWAYS(j<pTabList->nSrc); j++){
107602         if( pTabList->a[j].iCursor==p->iTable ) break;
107603       }
107604       assert( j<pTabList->nSrc );
107605       pTab = pTabList->a[j].pTab;
107606       if( iCol<0 ) iCol = pTab->iPKey;
107607       assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
107608       if( iCol<0 ){
107609         zCol = "rowid";
107610       }else{
107611         zCol = pTab->aCol[iCol].zName;
107612       }
107613       if( !shortNames && !fullNames ){
107614         sqlite3VdbeSetColName(v, i, COLNAME_NAME, 
107615             sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
107616       }else if( fullNames ){
107617         char *zName = 0;
107618         zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
107619         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
107620       }else{
107621         sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
107622       }
107623     }else{
107624       const char *z = pEList->a[i].zSpan;
107625       z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
107626       sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
107627     }
107628   }
107629   generateColumnTypes(pParse, pTabList, pEList);
107630 }
107631
107632 /*
107633 ** Given an expression list (which is really the list of expressions
107634 ** that form the result set of a SELECT statement) compute appropriate
107635 ** column names for a table that would hold the expression list.
107636 **
107637 ** All column names will be unique.
107638 **
107639 ** Only the column names are computed.  Column.zType, Column.zColl,
107640 ** and other fields of Column are zeroed.
107641 **
107642 ** Return SQLITE_OK on success.  If a memory allocation error occurs,
107643 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
107644 */
107645 static int selectColumnsFromExprList(
107646   Parse *pParse,          /* Parsing context */
107647   ExprList *pEList,       /* Expr list from which to derive column names */
107648   i16 *pnCol,             /* Write the number of columns here */
107649   Column **paCol          /* Write the new column list here */
107650 ){
107651   sqlite3 *db = pParse->db;   /* Database connection */
107652   int i, j;                   /* Loop counters */
107653   int cnt;                    /* Index added to make the name unique */
107654   Column *aCol, *pCol;        /* For looping over result columns */
107655   int nCol;                   /* Number of columns in the result set */
107656   Expr *p;                    /* Expression for a single result column */
107657   char *zName;                /* Column name */
107658   int nName;                  /* Size of name in zName[] */
107659
107660   if( pEList ){
107661     nCol = pEList->nExpr;
107662     aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
107663     testcase( aCol==0 );
107664   }else{
107665     nCol = 0;
107666     aCol = 0;
107667   }
107668   *pnCol = nCol;
107669   *paCol = aCol;
107670
107671   for(i=0, pCol=aCol; i<nCol; i++, pCol++){
107672     /* Get an appropriate name for the column
107673     */
107674     p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
107675     if( (zName = pEList->a[i].zName)!=0 ){
107676       /* If the column contains an "AS <name>" phrase, use <name> as the name */
107677       zName = sqlite3DbStrDup(db, zName);
107678     }else{
107679       Expr *pColExpr = p;  /* The expression that is the result column name */
107680       Table *pTab;         /* Table associated with this expression */
107681       while( pColExpr->op==TK_DOT ){
107682         pColExpr = pColExpr->pRight;
107683         assert( pColExpr!=0 );
107684       }
107685       if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
107686         /* For columns use the column name name */
107687         int iCol = pColExpr->iColumn;
107688         pTab = pColExpr->pTab;
107689         if( iCol<0 ) iCol = pTab->iPKey;
107690         zName = sqlite3MPrintf(db, "%s",
107691                  iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
107692       }else if( pColExpr->op==TK_ID ){
107693         assert( !ExprHasProperty(pColExpr, EP_IntValue) );
107694         zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
107695       }else{
107696         /* Use the original text of the column expression as its name */
107697         zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
107698       }
107699     }
107700     if( db->mallocFailed ){
107701       sqlite3DbFree(db, zName);
107702       break;
107703     }
107704
107705     /* Make sure the column name is unique.  If the name is not unique,
107706     ** append an integer to the name so that it becomes unique.
107707     */
107708     nName = sqlite3Strlen30(zName);
107709     for(j=cnt=0; j<i; j++){
107710       if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
107711         char *zNewName;
107712         int k;
107713         for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
107714         if( k>=0 && zName[k]==':' ) nName = k;
107715         zName[nName] = 0;
107716         zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
107717         sqlite3DbFree(db, zName);
107718         zName = zNewName;
107719         j = -1;
107720         if( zName==0 ) break;
107721       }
107722     }
107723     pCol->zName = zName;
107724   }
107725   if( db->mallocFailed ){
107726     for(j=0; j<i; j++){
107727       sqlite3DbFree(db, aCol[j].zName);
107728     }
107729     sqlite3DbFree(db, aCol);
107730     *paCol = 0;
107731     *pnCol = 0;
107732     return SQLITE_NOMEM;
107733   }
107734   return SQLITE_OK;
107735 }
107736
107737 /*
107738 ** Add type and collation information to a column list based on
107739 ** a SELECT statement.
107740 ** 
107741 ** The column list presumably came from selectColumnNamesFromExprList().
107742 ** The column list has only names, not types or collations.  This
107743 ** routine goes through and adds the types and collations.
107744 **
107745 ** This routine requires that all identifiers in the SELECT
107746 ** statement be resolved.
107747 */
107748 static void selectAddColumnTypeAndCollation(
107749   Parse *pParse,        /* Parsing contexts */
107750   Table *pTab,          /* Add column type information to this table */
107751   Select *pSelect       /* SELECT used to determine types and collations */
107752 ){
107753   sqlite3 *db = pParse->db;
107754   NameContext sNC;
107755   Column *pCol;
107756   CollSeq *pColl;
107757   int i;
107758   Expr *p;
107759   struct ExprList_item *a;
107760   u64 szAll = 0;
107761
107762   assert( pSelect!=0 );
107763   assert( (pSelect->selFlags & SF_Resolved)!=0 );
107764   assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
107765   if( db->mallocFailed ) return;
107766   memset(&sNC, 0, sizeof(sNC));
107767   sNC.pSrcList = pSelect->pSrc;
107768   a = pSelect->pEList->a;
107769   for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
107770     p = a[i].pExpr;
107771     pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst));
107772     szAll += pCol->szEst;
107773     pCol->affinity = sqlite3ExprAffinity(p);
107774     if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
107775     pColl = sqlite3ExprCollSeq(pParse, p);
107776     if( pColl ){
107777       pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
107778     }
107779   }
107780   pTab->szTabRow = sqlite3LogEst(szAll*4);
107781 }
107782
107783 /*
107784 ** Given a SELECT statement, generate a Table structure that describes
107785 ** the result set of that SELECT.
107786 */
107787 SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
107788   Table *pTab;
107789   sqlite3 *db = pParse->db;
107790   int savedFlags;
107791
107792   savedFlags = db->flags;
107793   db->flags &= ~SQLITE_FullColNames;
107794   db->flags |= SQLITE_ShortColNames;
107795   sqlite3SelectPrep(pParse, pSelect, 0);
107796   if( pParse->nErr ) return 0;
107797   while( pSelect->pPrior ) pSelect = pSelect->pPrior;
107798   db->flags = savedFlags;
107799   pTab = sqlite3DbMallocZero(db, sizeof(Table) );
107800   if( pTab==0 ){
107801     return 0;
107802   }
107803   /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
107804   ** is disabled */
107805   assert( db->lookaside.bEnabled==0 );
107806   pTab->nRef = 1;
107807   pTab->zName = 0;
107808   pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
107809   selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
107810   selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
107811   pTab->iPKey = -1;
107812   if( db->mallocFailed ){
107813     sqlite3DeleteTable(db, pTab);
107814     return 0;
107815   }
107816   return pTab;
107817 }
107818
107819 /*
107820 ** Get a VDBE for the given parser context.  Create a new one if necessary.
107821 ** If an error occurs, return NULL and leave a message in pParse.
107822 */
107823 SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
107824   Vdbe *v = pParse->pVdbe;
107825   if( v==0 ){
107826     v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
107827     if( v ) sqlite3VdbeAddOp0(v, OP_Init);
107828     if( pParse->pToplevel==0
107829      && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
107830     ){
107831       pParse->okConstFactor = 1;
107832     }
107833
107834   }
107835   return v;
107836 }
107837
107838
107839 /*
107840 ** Compute the iLimit and iOffset fields of the SELECT based on the
107841 ** pLimit and pOffset expressions.  pLimit and pOffset hold the expressions
107842 ** that appear in the original SQL statement after the LIMIT and OFFSET
107843 ** keywords.  Or NULL if those keywords are omitted. iLimit and iOffset 
107844 ** are the integer memory register numbers for counters used to compute 
107845 ** the limit and offset.  If there is no limit and/or offset, then 
107846 ** iLimit and iOffset are negative.
107847 **
107848 ** This routine changes the values of iLimit and iOffset only if
107849 ** a limit or offset is defined by pLimit and pOffset.  iLimit and
107850 ** iOffset should have been preset to appropriate default values (zero)
107851 ** prior to calling this routine.
107852 **
107853 ** The iOffset register (if it exists) is initialized to the value
107854 ** of the OFFSET.  The iLimit register is initialized to LIMIT.  Register
107855 ** iOffset+1 is initialized to LIMIT+OFFSET.
107856 **
107857 ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
107858 ** redefined.  The UNION ALL operator uses this property to force
107859 ** the reuse of the same limit and offset registers across multiple
107860 ** SELECT statements.
107861 */
107862 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
107863   Vdbe *v = 0;
107864   int iLimit = 0;
107865   int iOffset;
107866   int addr1, n;
107867   if( p->iLimit ) return;
107868
107869   /* 
107870   ** "LIMIT -1" always shows all rows.  There is some
107871   ** controversy about what the correct behavior should be.
107872   ** The current implementation interprets "LIMIT 0" to mean
107873   ** no rows.
107874   */
107875   sqlite3ExprCacheClear(pParse);
107876   assert( p->pOffset==0 || p->pLimit!=0 );
107877   if( p->pLimit ){
107878     p->iLimit = iLimit = ++pParse->nMem;
107879     v = sqlite3GetVdbe(pParse);
107880     assert( v!=0 );
107881     if( sqlite3ExprIsInteger(p->pLimit, &n) ){
107882       sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
107883       VdbeComment((v, "LIMIT counter"));
107884       if( n==0 ){
107885         sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
107886       }else if( n>=0 && p->nSelectRow>(u64)n ){
107887         p->nSelectRow = n;
107888       }
107889     }else{
107890       sqlite3ExprCode(pParse, p->pLimit, iLimit);
107891       sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
107892       VdbeComment((v, "LIMIT counter"));
107893       sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
107894     }
107895     if( p->pOffset ){
107896       p->iOffset = iOffset = ++pParse->nMem;
107897       pParse->nMem++;   /* Allocate an extra register for limit+offset */
107898       sqlite3ExprCode(pParse, p->pOffset, iOffset);
107899       sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
107900       VdbeComment((v, "OFFSET counter"));
107901       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); VdbeCoverage(v);
107902       sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
107903       sqlite3VdbeJumpHere(v, addr1);
107904       sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
107905       VdbeComment((v, "LIMIT+OFFSET"));
107906       addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); VdbeCoverage(v);
107907       sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
107908       sqlite3VdbeJumpHere(v, addr1);
107909     }
107910   }
107911 }
107912
107913 #ifndef SQLITE_OMIT_COMPOUND_SELECT
107914 /*
107915 ** Return the appropriate collating sequence for the iCol-th column of
107916 ** the result set for the compound-select statement "p".  Return NULL if
107917 ** the column has no default collating sequence.
107918 **
107919 ** The collating sequence for the compound select is taken from the
107920 ** left-most term of the select that has a collating sequence.
107921 */
107922 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
107923   CollSeq *pRet;
107924   if( p->pPrior ){
107925     pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
107926   }else{
107927     pRet = 0;
107928   }
107929   assert( iCol>=0 );
107930   if( pRet==0 && iCol<p->pEList->nExpr ){
107931     pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
107932   }
107933   return pRet;
107934 }
107935
107936 /*
107937 ** The select statement passed as the second parameter is a compound SELECT
107938 ** with an ORDER BY clause. This function allocates and returns a KeyInfo
107939 ** structure suitable for implementing the ORDER BY.
107940 **
107941 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
107942 ** function is responsible for ensuring that this structure is eventually
107943 ** freed.
107944 */
107945 static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
107946   ExprList *pOrderBy = p->pOrderBy;
107947   int nOrderBy = p->pOrderBy->nExpr;
107948   sqlite3 *db = pParse->db;
107949   KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
107950   if( pRet ){
107951     int i;
107952     for(i=0; i<nOrderBy; i++){
107953       struct ExprList_item *pItem = &pOrderBy->a[i];
107954       Expr *pTerm = pItem->pExpr;
107955       CollSeq *pColl;
107956
107957       if( pTerm->flags & EP_Collate ){
107958         pColl = sqlite3ExprCollSeq(pParse, pTerm);
107959       }else{
107960         pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
107961         if( pColl==0 ) pColl = db->pDfltColl;
107962         pOrderBy->a[i].pExpr =
107963           sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
107964       }
107965       assert( sqlite3KeyInfoIsWriteable(pRet) );
107966       pRet->aColl[i] = pColl;
107967       pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
107968     }
107969   }
107970
107971   return pRet;
107972 }
107973
107974 #ifndef SQLITE_OMIT_CTE
107975 /*
107976 ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
107977 ** query of the form:
107978 **
107979 **   <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
107980 **                         \___________/             \_______________/
107981 **                           p->pPrior                      p
107982 **
107983 **
107984 ** There is exactly one reference to the recursive-table in the FROM clause
107985 ** of recursive-query, marked with the SrcList->a[].isRecursive flag.
107986 **
107987 ** The setup-query runs once to generate an initial set of rows that go
107988 ** into a Queue table.  Rows are extracted from the Queue table one by
107989 ** one.  Each row extracted from Queue is output to pDest.  Then the single
107990 ** extracted row (now in the iCurrent table) becomes the content of the
107991 ** recursive-table for a recursive-query run.  The output of the recursive-query
107992 ** is added back into the Queue table.  Then another row is extracted from Queue
107993 ** and the iteration continues until the Queue table is empty.
107994 **
107995 ** If the compound query operator is UNION then no duplicate rows are ever
107996 ** inserted into the Queue table.  The iDistinct table keeps a copy of all rows
107997 ** that have ever been inserted into Queue and causes duplicates to be
107998 ** discarded.  If the operator is UNION ALL, then duplicates are allowed.
107999 ** 
108000 ** If the query has an ORDER BY, then entries in the Queue table are kept in
108001 ** ORDER BY order and the first entry is extracted for each cycle.  Without
108002 ** an ORDER BY, the Queue table is just a FIFO.
108003 **
108004 ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
108005 ** have been output to pDest.  A LIMIT of zero means to output no rows and a
108006 ** negative LIMIT means to output all rows.  If there is also an OFFSET clause
108007 ** with a positive value, then the first OFFSET outputs are discarded rather
108008 ** than being sent to pDest.  The LIMIT count does not begin until after OFFSET
108009 ** rows have been skipped.
108010 */
108011 static void generateWithRecursiveQuery(
108012   Parse *pParse,        /* Parsing context */
108013   Select *p,            /* The recursive SELECT to be coded */
108014   SelectDest *pDest     /* What to do with query results */
108015 ){
108016   SrcList *pSrc = p->pSrc;      /* The FROM clause of the recursive query */
108017   int nCol = p->pEList->nExpr;  /* Number of columns in the recursive table */
108018   Vdbe *v = pParse->pVdbe;      /* The prepared statement under construction */
108019   Select *pSetup = p->pPrior;   /* The setup query */
108020   int addrTop;                  /* Top of the loop */
108021   int addrCont, addrBreak;      /* CONTINUE and BREAK addresses */
108022   int iCurrent = 0;             /* The Current table */
108023   int regCurrent;               /* Register holding Current table */
108024   int iQueue;                   /* The Queue table */
108025   int iDistinct = 0;            /* To ensure unique results if UNION */
108026   int eDest = SRT_Fifo;         /* How to write to Queue */
108027   SelectDest destQueue;         /* SelectDest targetting the Queue table */
108028   int i;                        /* Loop counter */
108029   int rc;                       /* Result code */
108030   ExprList *pOrderBy;           /* The ORDER BY clause */
108031   Expr *pLimit, *pOffset;       /* Saved LIMIT and OFFSET */
108032   int regLimit, regOffset;      /* Registers used by LIMIT and OFFSET */
108033
108034   /* Obtain authorization to do a recursive query */
108035   if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
108036
108037   /* Process the LIMIT and OFFSET clauses, if they exist */
108038   addrBreak = sqlite3VdbeMakeLabel(v);
108039   computeLimitRegisters(pParse, p, addrBreak);
108040   pLimit = p->pLimit;
108041   pOffset = p->pOffset;
108042   regLimit = p->iLimit;
108043   regOffset = p->iOffset;
108044   p->pLimit = p->pOffset = 0;
108045   p->iLimit = p->iOffset = 0;
108046   pOrderBy = p->pOrderBy;
108047
108048   /* Locate the cursor number of the Current table */
108049   for(i=0; ALWAYS(i<pSrc->nSrc); i++){
108050     if( pSrc->a[i].isRecursive ){
108051       iCurrent = pSrc->a[i].iCursor;
108052       break;
108053     }
108054   }
108055
108056   /* Allocate cursors numbers for Queue and Distinct.  The cursor number for
108057   ** the Distinct table must be exactly one greater than Queue in order
108058   ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
108059   iQueue = pParse->nTab++;
108060   if( p->op==TK_UNION ){
108061     eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
108062     iDistinct = pParse->nTab++;
108063   }else{
108064     eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
108065   }
108066   sqlite3SelectDestInit(&destQueue, eDest, iQueue);
108067
108068   /* Allocate cursors for Current, Queue, and Distinct. */
108069   regCurrent = ++pParse->nMem;
108070   sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
108071   if( pOrderBy ){
108072     KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
108073     sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
108074                       (char*)pKeyInfo, P4_KEYINFO);
108075     destQueue.pOrderBy = pOrderBy;
108076   }else{
108077     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
108078   }
108079   VdbeComment((v, "Queue table"));
108080   if( iDistinct ){
108081     p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
108082     p->selFlags |= SF_UsesEphemeral;
108083   }
108084
108085   /* Detach the ORDER BY clause from the compound SELECT */
108086   p->pOrderBy = 0;
108087
108088   /* Store the results of the setup-query in Queue. */
108089   pSetup->pNext = 0;
108090   rc = sqlite3Select(pParse, pSetup, &destQueue);
108091   pSetup->pNext = p;
108092   if( rc ) goto end_of_recursive_query;
108093
108094   /* Find the next row in the Queue and output that row */
108095   addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
108096
108097   /* Transfer the next row in Queue over to Current */
108098   sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
108099   if( pOrderBy ){
108100     sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
108101   }else{
108102     sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
108103   }
108104   sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
108105
108106   /* Output the single row in Current */
108107   addrCont = sqlite3VdbeMakeLabel(v);
108108   codeOffset(v, regOffset, addrCont);
108109   selectInnerLoop(pParse, p, p->pEList, iCurrent,
108110       0, 0, pDest, addrCont, addrBreak);
108111   if( regLimit ){
108112     sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
108113     VdbeCoverage(v);
108114   }
108115   sqlite3VdbeResolveLabel(v, addrCont);
108116
108117   /* Execute the recursive SELECT taking the single row in Current as
108118   ** the value for the recursive-table. Store the results in the Queue.
108119   */
108120   p->pPrior = 0;
108121   sqlite3Select(pParse, p, &destQueue);
108122   assert( p->pPrior==0 );
108123   p->pPrior = pSetup;
108124
108125   /* Keep running the loop until the Queue is empty */
108126   sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
108127   sqlite3VdbeResolveLabel(v, addrBreak);
108128
108129 end_of_recursive_query:
108130   sqlite3ExprListDelete(pParse->db, p->pOrderBy);
108131   p->pOrderBy = pOrderBy;
108132   p->pLimit = pLimit;
108133   p->pOffset = pOffset;
108134   return;
108135 }
108136 #endif /* SQLITE_OMIT_CTE */
108137
108138 /* Forward references */
108139 static int multiSelectOrderBy(
108140   Parse *pParse,        /* Parsing context */
108141   Select *p,            /* The right-most of SELECTs to be coded */
108142   SelectDest *pDest     /* What to do with query results */
108143 );
108144
108145 /*
108146 ** Error message for when two or more terms of a compound select have different
108147 ** size result sets.
108148 */
108149 static void selectWrongNumTermsError(Parse *pParse, Select *p){
108150   if( p->selFlags & SF_Values ){
108151     sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
108152   }else{
108153     sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
108154       " do not have the same number of result columns", selectOpName(p->op));
108155   }
108156 }
108157
108158 /*
108159 ** Handle the special case of a compound-select that originates from a
108160 ** VALUES clause.  By handling this as a special case, we avoid deep
108161 ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
108162 ** on a VALUES clause.
108163 **
108164 ** Because the Select object originates from a VALUES clause:
108165 **   (1) It has no LIMIT or OFFSET
108166 **   (2) All terms are UNION ALL
108167 **   (3) There is no ORDER BY clause
108168 */
108169 static int multiSelectValues(
108170   Parse *pParse,        /* Parsing context */
108171   Select *p,            /* The right-most of SELECTs to be coded */
108172   SelectDest *pDest     /* What to do with query results */
108173 ){
108174   Select *pPrior;
108175   int nExpr = p->pEList->nExpr;
108176   int nRow = 1;
108177   int rc = 0;
108178   assert( p->pNext==0 );
108179   assert( p->selFlags & SF_AllValues );
108180   do{
108181     assert( p->selFlags & SF_Values );
108182     assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
108183     assert( p->pLimit==0 );
108184     assert( p->pOffset==0 );
108185     if( p->pEList->nExpr!=nExpr ){
108186       selectWrongNumTermsError(pParse, p);
108187       return 1;
108188     }
108189     if( p->pPrior==0 ) break;
108190     assert( p->pPrior->pNext==p );
108191     p = p->pPrior;
108192     nRow++;
108193   }while(1);
108194   while( p ){
108195     pPrior = p->pPrior;
108196     p->pPrior = 0;
108197     rc = sqlite3Select(pParse, p, pDest);
108198     p->pPrior = pPrior;
108199     if( rc ) break;
108200     p->nSelectRow = nRow;
108201     p = p->pNext;
108202   }
108203   return rc;
108204 }
108205
108206 /*
108207 ** This routine is called to process a compound query form from
108208 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
108209 ** INTERSECT
108210 **
108211 ** "p" points to the right-most of the two queries.  the query on the
108212 ** left is p->pPrior.  The left query could also be a compound query
108213 ** in which case this routine will be called recursively. 
108214 **
108215 ** The results of the total query are to be written into a destination
108216 ** of type eDest with parameter iParm.
108217 **
108218 ** Example 1:  Consider a three-way compound SQL statement.
108219 **
108220 **     SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
108221 **
108222 ** This statement is parsed up as follows:
108223 **
108224 **     SELECT c FROM t3
108225 **      |
108226 **      `----->  SELECT b FROM t2
108227 **                |
108228 **                `------>  SELECT a FROM t1
108229 **
108230 ** The arrows in the diagram above represent the Select.pPrior pointer.
108231 ** So if this routine is called with p equal to the t3 query, then
108232 ** pPrior will be the t2 query.  p->op will be TK_UNION in this case.
108233 **
108234 ** Notice that because of the way SQLite parses compound SELECTs, the
108235 ** individual selects always group from left to right.
108236 */
108237 static int multiSelect(
108238   Parse *pParse,        /* Parsing context */
108239   Select *p,            /* The right-most of SELECTs to be coded */
108240   SelectDest *pDest     /* What to do with query results */
108241 ){
108242   int rc = SQLITE_OK;   /* Success code from a subroutine */
108243   Select *pPrior;       /* Another SELECT immediately to our left */
108244   Vdbe *v;              /* Generate code to this VDBE */
108245   SelectDest dest;      /* Alternative data destination */
108246   Select *pDelete = 0;  /* Chain of simple selects to delete */
108247   sqlite3 *db;          /* Database connection */
108248 #ifndef SQLITE_OMIT_EXPLAIN
108249   int iSub1 = 0;        /* EQP id of left-hand query */
108250   int iSub2 = 0;        /* EQP id of right-hand query */
108251 #endif
108252
108253   /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs.  Only
108254   ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
108255   */
108256   assert( p && p->pPrior );  /* Calling function guarantees this much */
108257   assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
108258   db = pParse->db;
108259   pPrior = p->pPrior;
108260   dest = *pDest;
108261   if( pPrior->pOrderBy ){
108262     sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
108263       selectOpName(p->op));
108264     rc = 1;
108265     goto multi_select_end;
108266   }
108267   if( pPrior->pLimit ){
108268     sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
108269       selectOpName(p->op));
108270     rc = 1;
108271     goto multi_select_end;
108272   }
108273
108274   v = sqlite3GetVdbe(pParse);
108275   assert( v!=0 );  /* The VDBE already created by calling function */
108276
108277   /* Create the destination temporary table if necessary
108278   */
108279   if( dest.eDest==SRT_EphemTab ){
108280     assert( p->pEList );
108281     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
108282     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
108283     dest.eDest = SRT_Table;
108284   }
108285
108286   /* Special handling for a compound-select that originates as a VALUES clause.
108287   */
108288   if( p->selFlags & SF_AllValues ){
108289     rc = multiSelectValues(pParse, p, &dest);
108290     goto multi_select_end;
108291   }
108292
108293   /* Make sure all SELECTs in the statement have the same number of elements
108294   ** in their result sets.
108295   */
108296   assert( p->pEList && pPrior->pEList );
108297   if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
108298     selectWrongNumTermsError(pParse, p);
108299     rc = 1;
108300     goto multi_select_end;
108301   }
108302
108303 #ifndef SQLITE_OMIT_CTE
108304   if( p->selFlags & SF_Recursive ){
108305     generateWithRecursiveQuery(pParse, p, &dest);
108306   }else
108307 #endif
108308
108309   /* Compound SELECTs that have an ORDER BY clause are handled separately.
108310   */
108311   if( p->pOrderBy ){
108312     return multiSelectOrderBy(pParse, p, pDest);
108313   }else
108314
108315   /* Generate code for the left and right SELECT statements.
108316   */
108317   switch( p->op ){
108318     case TK_ALL: {
108319       int addr = 0;
108320       int nLimit;
108321       assert( !pPrior->pLimit );
108322       pPrior->iLimit = p->iLimit;
108323       pPrior->iOffset = p->iOffset;
108324       pPrior->pLimit = p->pLimit;
108325       pPrior->pOffset = p->pOffset;
108326       explainSetInteger(iSub1, pParse->iNextSelectId);
108327       rc = sqlite3Select(pParse, pPrior, &dest);
108328       p->pLimit = 0;
108329       p->pOffset = 0;
108330       if( rc ){
108331         goto multi_select_end;
108332       }
108333       p->pPrior = 0;
108334       p->iLimit = pPrior->iLimit;
108335       p->iOffset = pPrior->iOffset;
108336       if( p->iLimit ){
108337         addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
108338         VdbeComment((v, "Jump ahead if LIMIT reached"));
108339       }
108340       explainSetInteger(iSub2, pParse->iNextSelectId);
108341       rc = sqlite3Select(pParse, p, &dest);
108342       testcase( rc!=SQLITE_OK );
108343       pDelete = p->pPrior;
108344       p->pPrior = pPrior;
108345       p->nSelectRow += pPrior->nSelectRow;
108346       if( pPrior->pLimit
108347        && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
108348        && nLimit>0 && p->nSelectRow > (u64)nLimit 
108349       ){
108350         p->nSelectRow = nLimit;
108351       }
108352       if( addr ){
108353         sqlite3VdbeJumpHere(v, addr);
108354       }
108355       break;
108356     }
108357     case TK_EXCEPT:
108358     case TK_UNION: {
108359       int unionTab;    /* Cursor number of the temporary table holding result */
108360       u8 op = 0;       /* One of the SRT_ operations to apply to self */
108361       int priorOp;     /* The SRT_ operation to apply to prior selects */
108362       Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
108363       int addr;
108364       SelectDest uniondest;
108365
108366       testcase( p->op==TK_EXCEPT );
108367       testcase( p->op==TK_UNION );
108368       priorOp = SRT_Union;
108369       if( dest.eDest==priorOp ){
108370         /* We can reuse a temporary table generated by a SELECT to our
108371         ** right.
108372         */
108373         assert( p->pLimit==0 );      /* Not allowed on leftward elements */
108374         assert( p->pOffset==0 );     /* Not allowed on leftward elements */
108375         unionTab = dest.iSDParm;
108376       }else{
108377         /* We will need to create our own temporary table to hold the
108378         ** intermediate results.
108379         */
108380         unionTab = pParse->nTab++;
108381         assert( p->pOrderBy==0 );
108382         addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
108383         assert( p->addrOpenEphm[0] == -1 );
108384         p->addrOpenEphm[0] = addr;
108385         findRightmost(p)->selFlags |= SF_UsesEphemeral;
108386         assert( p->pEList );
108387       }
108388
108389       /* Code the SELECT statements to our left
108390       */
108391       assert( !pPrior->pOrderBy );
108392       sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
108393       explainSetInteger(iSub1, pParse->iNextSelectId);
108394       rc = sqlite3Select(pParse, pPrior, &uniondest);
108395       if( rc ){
108396         goto multi_select_end;
108397       }
108398
108399       /* Code the current SELECT statement
108400       */
108401       if( p->op==TK_EXCEPT ){
108402         op = SRT_Except;
108403       }else{
108404         assert( p->op==TK_UNION );
108405         op = SRT_Union;
108406       }
108407       p->pPrior = 0;
108408       pLimit = p->pLimit;
108409       p->pLimit = 0;
108410       pOffset = p->pOffset;
108411       p->pOffset = 0;
108412       uniondest.eDest = op;
108413       explainSetInteger(iSub2, pParse->iNextSelectId);
108414       rc = sqlite3Select(pParse, p, &uniondest);
108415       testcase( rc!=SQLITE_OK );
108416       /* Query flattening in sqlite3Select() might refill p->pOrderBy.
108417       ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
108418       sqlite3ExprListDelete(db, p->pOrderBy);
108419       pDelete = p->pPrior;
108420       p->pPrior = pPrior;
108421       p->pOrderBy = 0;
108422       if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
108423       sqlite3ExprDelete(db, p->pLimit);
108424       p->pLimit = pLimit;
108425       p->pOffset = pOffset;
108426       p->iLimit = 0;
108427       p->iOffset = 0;
108428
108429       /* Convert the data in the temporary table into whatever form
108430       ** it is that we currently need.
108431       */
108432       assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
108433       if( dest.eDest!=priorOp ){
108434         int iCont, iBreak, iStart;
108435         assert( p->pEList );
108436         if( dest.eDest==SRT_Output ){
108437           Select *pFirst = p;
108438           while( pFirst->pPrior ) pFirst = pFirst->pPrior;
108439           generateColumnNames(pParse, 0, pFirst->pEList);
108440         }
108441         iBreak = sqlite3VdbeMakeLabel(v);
108442         iCont = sqlite3VdbeMakeLabel(v);
108443         computeLimitRegisters(pParse, p, iBreak);
108444         sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
108445         iStart = sqlite3VdbeCurrentAddr(v);
108446         selectInnerLoop(pParse, p, p->pEList, unionTab,
108447                         0, 0, &dest, iCont, iBreak);
108448         sqlite3VdbeResolveLabel(v, iCont);
108449         sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
108450         sqlite3VdbeResolveLabel(v, iBreak);
108451         sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
108452       }
108453       break;
108454     }
108455     default: assert( p->op==TK_INTERSECT ); {
108456       int tab1, tab2;
108457       int iCont, iBreak, iStart;
108458       Expr *pLimit, *pOffset;
108459       int addr;
108460       SelectDest intersectdest;
108461       int r1;
108462
108463       /* INTERSECT is different from the others since it requires
108464       ** two temporary tables.  Hence it has its own case.  Begin
108465       ** by allocating the tables we will need.
108466       */
108467       tab1 = pParse->nTab++;
108468       tab2 = pParse->nTab++;
108469       assert( p->pOrderBy==0 );
108470
108471       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
108472       assert( p->addrOpenEphm[0] == -1 );
108473       p->addrOpenEphm[0] = addr;
108474       findRightmost(p)->selFlags |= SF_UsesEphemeral;
108475       assert( p->pEList );
108476
108477       /* Code the SELECTs to our left into temporary table "tab1".
108478       */
108479       sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
108480       explainSetInteger(iSub1, pParse->iNextSelectId);
108481       rc = sqlite3Select(pParse, pPrior, &intersectdest);
108482       if( rc ){
108483         goto multi_select_end;
108484       }
108485
108486       /* Code the current SELECT into temporary table "tab2"
108487       */
108488       addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
108489       assert( p->addrOpenEphm[1] == -1 );
108490       p->addrOpenEphm[1] = addr;
108491       p->pPrior = 0;
108492       pLimit = p->pLimit;
108493       p->pLimit = 0;
108494       pOffset = p->pOffset;
108495       p->pOffset = 0;
108496       intersectdest.iSDParm = tab2;
108497       explainSetInteger(iSub2, pParse->iNextSelectId);
108498       rc = sqlite3Select(pParse, p, &intersectdest);
108499       testcase( rc!=SQLITE_OK );
108500       pDelete = p->pPrior;
108501       p->pPrior = pPrior;
108502       if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
108503       sqlite3ExprDelete(db, p->pLimit);
108504       p->pLimit = pLimit;
108505       p->pOffset = pOffset;
108506
108507       /* Generate code to take the intersection of the two temporary
108508       ** tables.
108509       */
108510       assert( p->pEList );
108511       if( dest.eDest==SRT_Output ){
108512         Select *pFirst = p;
108513         while( pFirst->pPrior ) pFirst = pFirst->pPrior;
108514         generateColumnNames(pParse, 0, pFirst->pEList);
108515       }
108516       iBreak = sqlite3VdbeMakeLabel(v);
108517       iCont = sqlite3VdbeMakeLabel(v);
108518       computeLimitRegisters(pParse, p, iBreak);
108519       sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
108520       r1 = sqlite3GetTempReg(pParse);
108521       iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
108522       sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
108523       sqlite3ReleaseTempReg(pParse, r1);
108524       selectInnerLoop(pParse, p, p->pEList, tab1,
108525                       0, 0, &dest, iCont, iBreak);
108526       sqlite3VdbeResolveLabel(v, iCont);
108527       sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
108528       sqlite3VdbeResolveLabel(v, iBreak);
108529       sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
108530       sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
108531       break;
108532     }
108533   }
108534
108535   explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
108536
108537   /* Compute collating sequences used by 
108538   ** temporary tables needed to implement the compound select.
108539   ** Attach the KeyInfo structure to all temporary tables.
108540   **
108541   ** This section is run by the right-most SELECT statement only.
108542   ** SELECT statements to the left always skip this part.  The right-most
108543   ** SELECT might also skip this part if it has no ORDER BY clause and
108544   ** no temp tables are required.
108545   */
108546   if( p->selFlags & SF_UsesEphemeral ){
108547     int i;                        /* Loop counter */
108548     KeyInfo *pKeyInfo;            /* Collating sequence for the result set */
108549     Select *pLoop;                /* For looping through SELECT statements */
108550     CollSeq **apColl;             /* For looping through pKeyInfo->aColl[] */
108551     int nCol;                     /* Number of columns in result set */
108552
108553     assert( p->pNext==0 );
108554     nCol = p->pEList->nExpr;
108555     pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
108556     if( !pKeyInfo ){
108557       rc = SQLITE_NOMEM;
108558       goto multi_select_end;
108559     }
108560     for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
108561       *apColl = multiSelectCollSeq(pParse, p, i);
108562       if( 0==*apColl ){
108563         *apColl = db->pDfltColl;
108564       }
108565     }
108566
108567     for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
108568       for(i=0; i<2; i++){
108569         int addr = pLoop->addrOpenEphm[i];
108570         if( addr<0 ){
108571           /* If [0] is unused then [1] is also unused.  So we can
108572           ** always safely abort as soon as the first unused slot is found */
108573           assert( pLoop->addrOpenEphm[1]<0 );
108574           break;
108575         }
108576         sqlite3VdbeChangeP2(v, addr, nCol);
108577         sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
108578                             P4_KEYINFO);
108579         pLoop->addrOpenEphm[i] = -1;
108580       }
108581     }
108582     sqlite3KeyInfoUnref(pKeyInfo);
108583   }
108584
108585 multi_select_end:
108586   pDest->iSdst = dest.iSdst;
108587   pDest->nSdst = dest.nSdst;
108588   sqlite3SelectDelete(db, pDelete);
108589   return rc;
108590 }
108591 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
108592
108593 /*
108594 ** Code an output subroutine for a coroutine implementation of a
108595 ** SELECT statment.
108596 **
108597 ** The data to be output is contained in pIn->iSdst.  There are
108598 ** pIn->nSdst columns to be output.  pDest is where the output should
108599 ** be sent.
108600 **
108601 ** regReturn is the number of the register holding the subroutine
108602 ** return address.
108603 **
108604 ** If regPrev>0 then it is the first register in a vector that
108605 ** records the previous output.  mem[regPrev] is a flag that is false
108606 ** if there has been no previous output.  If regPrev>0 then code is
108607 ** generated to suppress duplicates.  pKeyInfo is used for comparing
108608 ** keys.
108609 **
108610 ** If the LIMIT found in p->iLimit is reached, jump immediately to
108611 ** iBreak.
108612 */
108613 static int generateOutputSubroutine(
108614   Parse *pParse,          /* Parsing context */
108615   Select *p,              /* The SELECT statement */
108616   SelectDest *pIn,        /* Coroutine supplying data */
108617   SelectDest *pDest,      /* Where to send the data */
108618   int regReturn,          /* The return address register */
108619   int regPrev,            /* Previous result register.  No uniqueness if 0 */
108620   KeyInfo *pKeyInfo,      /* For comparing with previous entry */
108621   int iBreak              /* Jump here if we hit the LIMIT */
108622 ){
108623   Vdbe *v = pParse->pVdbe;
108624   int iContinue;
108625   int addr;
108626
108627   addr = sqlite3VdbeCurrentAddr(v);
108628   iContinue = sqlite3VdbeMakeLabel(v);
108629
108630   /* Suppress duplicates for UNION, EXCEPT, and INTERSECT 
108631   */
108632   if( regPrev ){
108633     int j1, j2;
108634     j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
108635     j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
108636                               (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
108637     sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2); VdbeCoverage(v);
108638     sqlite3VdbeJumpHere(v, j1);
108639     sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
108640     sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
108641   }
108642   if( pParse->db->mallocFailed ) return 0;
108643
108644   /* Suppress the first OFFSET entries if there is an OFFSET clause
108645   */
108646   codeOffset(v, p->iOffset, iContinue);
108647
108648   switch( pDest->eDest ){
108649     /* Store the result as data using a unique key.
108650     */
108651     case SRT_Table:
108652     case SRT_EphemTab: {
108653       int r1 = sqlite3GetTempReg(pParse);
108654       int r2 = sqlite3GetTempReg(pParse);
108655       testcase( pDest->eDest==SRT_Table );
108656       testcase( pDest->eDest==SRT_EphemTab );
108657       sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
108658       sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
108659       sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
108660       sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
108661       sqlite3ReleaseTempReg(pParse, r2);
108662       sqlite3ReleaseTempReg(pParse, r1);
108663       break;
108664     }
108665
108666 #ifndef SQLITE_OMIT_SUBQUERY
108667     /* If we are creating a set for an "expr IN (SELECT ...)" construct,
108668     ** then there should be a single item on the stack.  Write this
108669     ** item into the set table with bogus data.
108670     */
108671     case SRT_Set: {
108672       int r1;
108673       assert( pIn->nSdst==1 );
108674       pDest->affSdst = 
108675          sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
108676       r1 = sqlite3GetTempReg(pParse);
108677       sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
108678       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
108679       sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
108680       sqlite3ReleaseTempReg(pParse, r1);
108681       break;
108682     }
108683
108684 #if 0  /* Never occurs on an ORDER BY query */
108685     /* If any row exist in the result set, record that fact and abort.
108686     */
108687     case SRT_Exists: {
108688       sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
108689       /* The LIMIT clause will terminate the loop for us */
108690       break;
108691     }
108692 #endif
108693
108694     /* If this is a scalar select that is part of an expression, then
108695     ** store the results in the appropriate memory cell and break out
108696     ** of the scan loop.
108697     */
108698     case SRT_Mem: {
108699       assert( pIn->nSdst==1 );
108700       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
108701       /* The LIMIT clause will jump out of the loop for us */
108702       break;
108703     }
108704 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
108705
108706     /* The results are stored in a sequence of registers
108707     ** starting at pDest->iSdst.  Then the co-routine yields.
108708     */
108709     case SRT_Coroutine: {
108710       if( pDest->iSdst==0 ){
108711         pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
108712         pDest->nSdst = pIn->nSdst;
108713       }
108714       sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
108715       sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
108716       break;
108717     }
108718
108719     /* If none of the above, then the result destination must be
108720     ** SRT_Output.  This routine is never called with any other
108721     ** destination other than the ones handled above or SRT_Output.
108722     **
108723     ** For SRT_Output, results are stored in a sequence of registers.  
108724     ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
108725     ** return the next row of result.
108726     */
108727     default: {
108728       assert( pDest->eDest==SRT_Output );
108729       sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
108730       sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
108731       break;
108732     }
108733   }
108734
108735   /* Jump to the end of the loop if the LIMIT is reached.
108736   */
108737   if( p->iLimit ){
108738     sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
108739   }
108740
108741   /* Generate the subroutine return
108742   */
108743   sqlite3VdbeResolveLabel(v, iContinue);
108744   sqlite3VdbeAddOp1(v, OP_Return, regReturn);
108745
108746   return addr;
108747 }
108748
108749 /*
108750 ** Alternative compound select code generator for cases when there
108751 ** is an ORDER BY clause.
108752 **
108753 ** We assume a query of the following form:
108754 **
108755 **      <selectA>  <operator>  <selectB>  ORDER BY <orderbylist>
108756 **
108757 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT.  The idea
108758 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
108759 ** co-routines.  Then run the co-routines in parallel and merge the results
108760 ** into the output.  In addition to the two coroutines (called selectA and
108761 ** selectB) there are 7 subroutines:
108762 **
108763 **    outA:    Move the output of the selectA coroutine into the output
108764 **             of the compound query.
108765 **
108766 **    outB:    Move the output of the selectB coroutine into the output
108767 **             of the compound query.  (Only generated for UNION and
108768 **             UNION ALL.  EXCEPT and INSERTSECT never output a row that
108769 **             appears only in B.)
108770 **
108771 **    AltB:    Called when there is data from both coroutines and A<B.
108772 **
108773 **    AeqB:    Called when there is data from both coroutines and A==B.
108774 **
108775 **    AgtB:    Called when there is data from both coroutines and A>B.
108776 **
108777 **    EofA:    Called when data is exhausted from selectA.
108778 **
108779 **    EofB:    Called when data is exhausted from selectB.
108780 **
108781 ** The implementation of the latter five subroutines depend on which 
108782 ** <operator> is used:
108783 **
108784 **
108785 **             UNION ALL         UNION            EXCEPT          INTERSECT
108786 **          -------------  -----------------  --------------  -----------------
108787 **   AltB:   outA, nextA      outA, nextA       outA, nextA         nextA
108788 **
108789 **   AeqB:   outA, nextA         nextA             nextA         outA, nextA
108790 **
108791 **   AgtB:   outB, nextB      outB, nextB          nextB            nextB
108792 **
108793 **   EofA:   outB, nextB      outB, nextB          halt             halt
108794 **
108795 **   EofB:   outA, nextA      outA, nextA       outA, nextA         halt
108796 **
108797 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
108798 ** causes an immediate jump to EofA and an EOF on B following nextB causes
108799 ** an immediate jump to EofB.  Within EofA and EofB, and EOF on entry or
108800 ** following nextX causes a jump to the end of the select processing.
108801 **
108802 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
108803 ** within the output subroutine.  The regPrev register set holds the previously
108804 ** output value.  A comparison is made against this value and the output
108805 ** is skipped if the next results would be the same as the previous.
108806 **
108807 ** The implementation plan is to implement the two coroutines and seven
108808 ** subroutines first, then put the control logic at the bottom.  Like this:
108809 **
108810 **          goto Init
108811 **     coA: coroutine for left query (A)
108812 **     coB: coroutine for right query (B)
108813 **    outA: output one row of A
108814 **    outB: output one row of B (UNION and UNION ALL only)
108815 **    EofA: ...
108816 **    EofB: ...
108817 **    AltB: ...
108818 **    AeqB: ...
108819 **    AgtB: ...
108820 **    Init: initialize coroutine registers
108821 **          yield coA
108822 **          if eof(A) goto EofA
108823 **          yield coB
108824 **          if eof(B) goto EofB
108825 **    Cmpr: Compare A, B
108826 **          Jump AltB, AeqB, AgtB
108827 **     End: ...
108828 **
108829 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
108830 ** actually called using Gosub and they do not Return.  EofA and EofB loop
108831 ** until all data is exhausted then jump to the "end" labe.  AltB, AeqB,
108832 ** and AgtB jump to either L2 or to one of EofA or EofB.
108833 */
108834 #ifndef SQLITE_OMIT_COMPOUND_SELECT
108835 static int multiSelectOrderBy(
108836   Parse *pParse,        /* Parsing context */
108837   Select *p,            /* The right-most of SELECTs to be coded */
108838   SelectDest *pDest     /* What to do with query results */
108839 ){
108840   int i, j;             /* Loop counters */
108841   Select *pPrior;       /* Another SELECT immediately to our left */
108842   Vdbe *v;              /* Generate code to this VDBE */
108843   SelectDest destA;     /* Destination for coroutine A */
108844   SelectDest destB;     /* Destination for coroutine B */
108845   int regAddrA;         /* Address register for select-A coroutine */
108846   int regAddrB;         /* Address register for select-B coroutine */
108847   int addrSelectA;      /* Address of the select-A coroutine */
108848   int addrSelectB;      /* Address of the select-B coroutine */
108849   int regOutA;          /* Address register for the output-A subroutine */
108850   int regOutB;          /* Address register for the output-B subroutine */
108851   int addrOutA;         /* Address of the output-A subroutine */
108852   int addrOutB = 0;     /* Address of the output-B subroutine */
108853   int addrEofA;         /* Address of the select-A-exhausted subroutine */
108854   int addrEofA_noB;     /* Alternate addrEofA if B is uninitialized */
108855   int addrEofB;         /* Address of the select-B-exhausted subroutine */
108856   int addrAltB;         /* Address of the A<B subroutine */
108857   int addrAeqB;         /* Address of the A==B subroutine */
108858   int addrAgtB;         /* Address of the A>B subroutine */
108859   int regLimitA;        /* Limit register for select-A */
108860   int regLimitB;        /* Limit register for select-A */
108861   int regPrev;          /* A range of registers to hold previous output */
108862   int savedLimit;       /* Saved value of p->iLimit */
108863   int savedOffset;      /* Saved value of p->iOffset */
108864   int labelCmpr;        /* Label for the start of the merge algorithm */
108865   int labelEnd;         /* Label for the end of the overall SELECT stmt */
108866   int j1;               /* Jump instructions that get retargetted */
108867   int op;               /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
108868   KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
108869   KeyInfo *pKeyMerge;   /* Comparison information for merging rows */
108870   sqlite3 *db;          /* Database connection */
108871   ExprList *pOrderBy;   /* The ORDER BY clause */
108872   int nOrderBy;         /* Number of terms in the ORDER BY clause */
108873   int *aPermute;        /* Mapping from ORDER BY terms to result set columns */
108874 #ifndef SQLITE_OMIT_EXPLAIN
108875   int iSub1;            /* EQP id of left-hand query */
108876   int iSub2;            /* EQP id of right-hand query */
108877 #endif
108878
108879   assert( p->pOrderBy!=0 );
108880   assert( pKeyDup==0 ); /* "Managed" code needs this.  Ticket #3382. */
108881   db = pParse->db;
108882   v = pParse->pVdbe;
108883   assert( v!=0 );       /* Already thrown the error if VDBE alloc failed */
108884   labelEnd = sqlite3VdbeMakeLabel(v);
108885   labelCmpr = sqlite3VdbeMakeLabel(v);
108886
108887
108888   /* Patch up the ORDER BY clause
108889   */
108890   op = p->op;  
108891   pPrior = p->pPrior;
108892   assert( pPrior->pOrderBy==0 );
108893   pOrderBy = p->pOrderBy;
108894   assert( pOrderBy );
108895   nOrderBy = pOrderBy->nExpr;
108896
108897   /* For operators other than UNION ALL we have to make sure that
108898   ** the ORDER BY clause covers every term of the result set.  Add
108899   ** terms to the ORDER BY clause as necessary.
108900   */
108901   if( op!=TK_ALL ){
108902     for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
108903       struct ExprList_item *pItem;
108904       for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
108905         assert( pItem->u.x.iOrderByCol>0 );
108906         if( pItem->u.x.iOrderByCol==i ) break;
108907       }
108908       if( j==nOrderBy ){
108909         Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
108910         if( pNew==0 ) return SQLITE_NOMEM;
108911         pNew->flags |= EP_IntValue;
108912         pNew->u.iValue = i;
108913         pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
108914         if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
108915       }
108916     }
108917   }
108918
108919   /* Compute the comparison permutation and keyinfo that is used with
108920   ** the permutation used to determine if the next
108921   ** row of results comes from selectA or selectB.  Also add explicit
108922   ** collations to the ORDER BY clause terms so that when the subqueries
108923   ** to the right and the left are evaluated, they use the correct
108924   ** collation.
108925   */
108926   aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
108927   if( aPermute ){
108928     struct ExprList_item *pItem;
108929     for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
108930       assert( pItem->u.x.iOrderByCol>0
108931           && pItem->u.x.iOrderByCol<=p->pEList->nExpr );
108932       aPermute[i] = pItem->u.x.iOrderByCol - 1;
108933     }
108934     pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
108935   }else{
108936     pKeyMerge = 0;
108937   }
108938
108939   /* Reattach the ORDER BY clause to the query.
108940   */
108941   p->pOrderBy = pOrderBy;
108942   pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
108943
108944   /* Allocate a range of temporary registers and the KeyInfo needed
108945   ** for the logic that removes duplicate result rows when the
108946   ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
108947   */
108948   if( op==TK_ALL ){
108949     regPrev = 0;
108950   }else{
108951     int nExpr = p->pEList->nExpr;
108952     assert( nOrderBy>=nExpr || db->mallocFailed );
108953     regPrev = pParse->nMem+1;
108954     pParse->nMem += nExpr+1;
108955     sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
108956     pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
108957     if( pKeyDup ){
108958       assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
108959       for(i=0; i<nExpr; i++){
108960         pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
108961         pKeyDup->aSortOrder[i] = 0;
108962       }
108963     }
108964   }
108965  
108966   /* Separate the left and the right query from one another
108967   */
108968   p->pPrior = 0;
108969   pPrior->pNext = 0;
108970   sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
108971   if( pPrior->pPrior==0 ){
108972     sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
108973   }
108974
108975   /* Compute the limit registers */
108976   computeLimitRegisters(pParse, p, labelEnd);
108977   if( p->iLimit && op==TK_ALL ){
108978     regLimitA = ++pParse->nMem;
108979     regLimitB = ++pParse->nMem;
108980     sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
108981                                   regLimitA);
108982     sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
108983   }else{
108984     regLimitA = regLimitB = 0;
108985   }
108986   sqlite3ExprDelete(db, p->pLimit);
108987   p->pLimit = 0;
108988   sqlite3ExprDelete(db, p->pOffset);
108989   p->pOffset = 0;
108990
108991   regAddrA = ++pParse->nMem;
108992   regAddrB = ++pParse->nMem;
108993   regOutA = ++pParse->nMem;
108994   regOutB = ++pParse->nMem;
108995   sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
108996   sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
108997
108998   /* Generate a coroutine to evaluate the SELECT statement to the
108999   ** left of the compound operator - the "A" select.
109000   */
109001   addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
109002   j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
109003   VdbeComment((v, "left SELECT"));
109004   pPrior->iLimit = regLimitA;
109005   explainSetInteger(iSub1, pParse->iNextSelectId);
109006   sqlite3Select(pParse, pPrior, &destA);
109007   sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrA);
109008   sqlite3VdbeJumpHere(v, j1);
109009
109010   /* Generate a coroutine to evaluate the SELECT statement on 
109011   ** the right - the "B" select
109012   */
109013   addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
109014   j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
109015   VdbeComment((v, "right SELECT"));
109016   savedLimit = p->iLimit;
109017   savedOffset = p->iOffset;
109018   p->iLimit = regLimitB;
109019   p->iOffset = 0;  
109020   explainSetInteger(iSub2, pParse->iNextSelectId);
109021   sqlite3Select(pParse, p, &destB);
109022   p->iLimit = savedLimit;
109023   p->iOffset = savedOffset;
109024   sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrB);
109025
109026   /* Generate a subroutine that outputs the current row of the A
109027   ** select as the next output row of the compound select.
109028   */
109029   VdbeNoopComment((v, "Output routine for A"));
109030   addrOutA = generateOutputSubroutine(pParse,
109031                  p, &destA, pDest, regOutA,
109032                  regPrev, pKeyDup, labelEnd);
109033   
109034   /* Generate a subroutine that outputs the current row of the B
109035   ** select as the next output row of the compound select.
109036   */
109037   if( op==TK_ALL || op==TK_UNION ){
109038     VdbeNoopComment((v, "Output routine for B"));
109039     addrOutB = generateOutputSubroutine(pParse,
109040                  p, &destB, pDest, regOutB,
109041                  regPrev, pKeyDup, labelEnd);
109042   }
109043   sqlite3KeyInfoUnref(pKeyDup);
109044
109045   /* Generate a subroutine to run when the results from select A
109046   ** are exhausted and only data in select B remains.
109047   */
109048   if( op==TK_EXCEPT || op==TK_INTERSECT ){
109049     addrEofA_noB = addrEofA = labelEnd;
109050   }else{  
109051     VdbeNoopComment((v, "eof-A subroutine"));
109052     addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
109053     addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
109054                                      VdbeCoverage(v);
109055     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
109056     p->nSelectRow += pPrior->nSelectRow;
109057   }
109058
109059   /* Generate a subroutine to run when the results from select B
109060   ** are exhausted and only data in select A remains.
109061   */
109062   if( op==TK_INTERSECT ){
109063     addrEofB = addrEofA;
109064     if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
109065   }else{  
109066     VdbeNoopComment((v, "eof-B subroutine"));
109067     addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
109068     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
109069     sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
109070   }
109071
109072   /* Generate code to handle the case of A<B
109073   */
109074   VdbeNoopComment((v, "A-lt-B subroutine"));
109075   addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
109076   sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
109077   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
109078
109079   /* Generate code to handle the case of A==B
109080   */
109081   if( op==TK_ALL ){
109082     addrAeqB = addrAltB;
109083   }else if( op==TK_INTERSECT ){
109084     addrAeqB = addrAltB;
109085     addrAltB++;
109086   }else{
109087     VdbeNoopComment((v, "A-eq-B subroutine"));
109088     addrAeqB =
109089     sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
109090     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
109091   }
109092
109093   /* Generate code to handle the case of A>B
109094   */
109095   VdbeNoopComment((v, "A-gt-B subroutine"));
109096   addrAgtB = sqlite3VdbeCurrentAddr(v);
109097   if( op==TK_ALL || op==TK_UNION ){
109098     sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
109099   }
109100   sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
109101   sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
109102
109103   /* This code runs once to initialize everything.
109104   */
109105   sqlite3VdbeJumpHere(v, j1);
109106   sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
109107   sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
109108
109109   /* Implement the main merge loop
109110   */
109111   sqlite3VdbeResolveLabel(v, labelCmpr);
109112   sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
109113   sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
109114                          (char*)pKeyMerge, P4_KEYINFO);
109115   sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
109116   sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
109117
109118   /* Jump to the this point in order to terminate the query.
109119   */
109120   sqlite3VdbeResolveLabel(v, labelEnd);
109121
109122   /* Set the number of output columns
109123   */
109124   if( pDest->eDest==SRT_Output ){
109125     Select *pFirst = pPrior;
109126     while( pFirst->pPrior ) pFirst = pFirst->pPrior;
109127     generateColumnNames(pParse, 0, pFirst->pEList);
109128   }
109129
109130   /* Reassembly the compound query so that it will be freed correctly
109131   ** by the calling function */
109132   if( p->pPrior ){
109133     sqlite3SelectDelete(db, p->pPrior);
109134   }
109135   p->pPrior = pPrior;
109136   pPrior->pNext = p;
109137
109138   /*** TBD:  Insert subroutine calls to close cursors on incomplete
109139   **** subqueries ****/
109140   explainComposite(pParse, p->op, iSub1, iSub2, 0);
109141   return SQLITE_OK;
109142 }
109143 #endif
109144
109145 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
109146 /* Forward Declarations */
109147 static void substExprList(sqlite3*, ExprList*, int, ExprList*);
109148 static void substSelect(sqlite3*, Select *, int, ExprList *);
109149
109150 /*
109151 ** Scan through the expression pExpr.  Replace every reference to
109152 ** a column in table number iTable with a copy of the iColumn-th
109153 ** entry in pEList.  (But leave references to the ROWID column 
109154 ** unchanged.)
109155 **
109156 ** This routine is part of the flattening procedure.  A subquery
109157 ** whose result set is defined by pEList appears as entry in the
109158 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
109159 ** FORM clause entry is iTable.  This routine make the necessary 
109160 ** changes to pExpr so that it refers directly to the source table
109161 ** of the subquery rather the result set of the subquery.
109162 */
109163 static Expr *substExpr(
109164   sqlite3 *db,        /* Report malloc errors to this connection */
109165   Expr *pExpr,        /* Expr in which substitution occurs */
109166   int iTable,         /* Table to be substituted */
109167   ExprList *pEList    /* Substitute expressions */
109168 ){
109169   if( pExpr==0 ) return 0;
109170   if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
109171     if( pExpr->iColumn<0 ){
109172       pExpr->op = TK_NULL;
109173     }else{
109174       Expr *pNew;
109175       assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
109176       assert( pExpr->pLeft==0 && pExpr->pRight==0 );
109177       pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
109178       sqlite3ExprDelete(db, pExpr);
109179       pExpr = pNew;
109180     }
109181   }else{
109182     pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
109183     pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
109184     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
109185       substSelect(db, pExpr->x.pSelect, iTable, pEList);
109186     }else{
109187       substExprList(db, pExpr->x.pList, iTable, pEList);
109188     }
109189   }
109190   return pExpr;
109191 }
109192 static void substExprList(
109193   sqlite3 *db,         /* Report malloc errors here */
109194   ExprList *pList,     /* List to scan and in which to make substitutes */
109195   int iTable,          /* Table to be substituted */
109196   ExprList *pEList     /* Substitute values */
109197 ){
109198   int i;
109199   if( pList==0 ) return;
109200   for(i=0; i<pList->nExpr; i++){
109201     pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
109202   }
109203 }
109204 static void substSelect(
109205   sqlite3 *db,         /* Report malloc errors here */
109206   Select *p,           /* SELECT statement in which to make substitutions */
109207   int iTable,          /* Table to be replaced */
109208   ExprList *pEList     /* Substitute values */
109209 ){
109210   SrcList *pSrc;
109211   struct SrcList_item *pItem;
109212   int i;
109213   if( !p ) return;
109214   substExprList(db, p->pEList, iTable, pEList);
109215   substExprList(db, p->pGroupBy, iTable, pEList);
109216   substExprList(db, p->pOrderBy, iTable, pEList);
109217   p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
109218   p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
109219   substSelect(db, p->pPrior, iTable, pEList);
109220   pSrc = p->pSrc;
109221   assert( pSrc );  /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
109222   if( ALWAYS(pSrc) ){
109223     for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
109224       substSelect(db, pItem->pSelect, iTable, pEList);
109225     }
109226   }
109227 }
109228 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
109229
109230 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
109231 /*
109232 ** This routine attempts to flatten subqueries as a performance optimization.
109233 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
109234 **
109235 ** To understand the concept of flattening, consider the following
109236 ** query:
109237 **
109238 **     SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
109239 **
109240 ** The default way of implementing this query is to execute the
109241 ** subquery first and store the results in a temporary table, then
109242 ** run the outer query on that temporary table.  This requires two
109243 ** passes over the data.  Furthermore, because the temporary table
109244 ** has no indices, the WHERE clause on the outer query cannot be
109245 ** optimized.
109246 **
109247 ** This routine attempts to rewrite queries such as the above into
109248 ** a single flat select, like this:
109249 **
109250 **     SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
109251 **
109252 ** The code generated for this simplification gives the same result
109253 ** but only has to scan the data once.  And because indices might 
109254 ** exist on the table t1, a complete scan of the data might be
109255 ** avoided.
109256 **
109257 ** Flattening is only attempted if all of the following are true:
109258 **
109259 **   (1)  The subquery and the outer query do not both use aggregates.
109260 **
109261 **   (2)  The subquery is not an aggregate or (2a) the outer query is not a join
109262 **        and (2b) the outer query does not use subqueries other than the one
109263 **        FROM-clause subquery that is a candidate for flattening.  (2b is
109264 **        due to ticket [2f7170d73bf9abf80] from 2015-02-09.)
109265 **
109266 **   (3)  The subquery is not the right operand of a left outer join
109267 **        (Originally ticket #306.  Strengthened by ticket #3300)
109268 **
109269 **   (4)  The subquery is not DISTINCT.
109270 **
109271 **  (**)  At one point restrictions (4) and (5) defined a subset of DISTINCT
109272 **        sub-queries that were excluded from this optimization. Restriction 
109273 **        (4) has since been expanded to exclude all DISTINCT subqueries.
109274 **
109275 **   (6)  The subquery does not use aggregates or the outer query is not
109276 **        DISTINCT.
109277 **
109278 **   (7)  The subquery has a FROM clause.  TODO:  For subqueries without
109279 **        A FROM clause, consider adding a FROM close with the special
109280 **        table sqlite_once that consists of a single row containing a
109281 **        single NULL.
109282 **
109283 **   (8)  The subquery does not use LIMIT or the outer query is not a join.
109284 **
109285 **   (9)  The subquery does not use LIMIT or the outer query does not use
109286 **        aggregates.
109287 **
109288 **  (**)  Restriction (10) was removed from the code on 2005-02-05 but we
109289 **        accidently carried the comment forward until 2014-09-15.  Original
109290 **        text: "The subquery does not use aggregates or the outer query does not
109291 **        use LIMIT."
109292 **
109293 **  (11)  The subquery and the outer query do not both have ORDER BY clauses.
109294 **
109295 **  (**)  Not implemented.  Subsumed into restriction (3).  Was previously
109296 **        a separate restriction deriving from ticket #350.
109297 **
109298 **  (13)  The subquery and outer query do not both use LIMIT.
109299 **
109300 **  (14)  The subquery does not use OFFSET.
109301 **
109302 **  (15)  The outer query is not part of a compound select or the
109303 **        subquery does not have a LIMIT clause.
109304 **        (See ticket #2339 and ticket [02a8e81d44]).
109305 **
109306 **  (16)  The outer query is not an aggregate or the subquery does
109307 **        not contain ORDER BY.  (Ticket #2942)  This used to not matter
109308 **        until we introduced the group_concat() function.  
109309 **
109310 **  (17)  The sub-query is not a compound select, or it is a UNION ALL 
109311 **        compound clause made up entirely of non-aggregate queries, and 
109312 **        the parent query:
109313 **
109314 **          * is not itself part of a compound select,
109315 **          * is not an aggregate or DISTINCT query, and
109316 **          * is not a join
109317 **
109318 **        The parent and sub-query may contain WHERE clauses. Subject to
109319 **        rules (11), (13) and (14), they may also contain ORDER BY,
109320 **        LIMIT and OFFSET clauses.  The subquery cannot use any compound
109321 **        operator other than UNION ALL because all the other compound
109322 **        operators have an implied DISTINCT which is disallowed by
109323 **        restriction (4).
109324 **
109325 **        Also, each component of the sub-query must return the same number
109326 **        of result columns. This is actually a requirement for any compound
109327 **        SELECT statement, but all the code here does is make sure that no
109328 **        such (illegal) sub-query is flattened. The caller will detect the
109329 **        syntax error and return a detailed message.
109330 **
109331 **  (18)  If the sub-query is a compound select, then all terms of the
109332 **        ORDER by clause of the parent must be simple references to 
109333 **        columns of the sub-query.
109334 **
109335 **  (19)  The subquery does not use LIMIT or the outer query does not
109336 **        have a WHERE clause.
109337 **
109338 **  (20)  If the sub-query is a compound select, then it must not use
109339 **        an ORDER BY clause.  Ticket #3773.  We could relax this constraint
109340 **        somewhat by saying that the terms of the ORDER BY clause must
109341 **        appear as unmodified result columns in the outer query.  But we
109342 **        have other optimizations in mind to deal with that case.
109343 **
109344 **  (21)  The subquery does not use LIMIT or the outer query is not
109345 **        DISTINCT.  (See ticket [752e1646fc]).
109346 **
109347 **  (22)  The subquery is not a recursive CTE.
109348 **
109349 **  (23)  The parent is not a recursive CTE, or the sub-query is not a
109350 **        compound query. This restriction is because transforming the
109351 **        parent to a compound query confuses the code that handles
109352 **        recursive queries in multiSelect().
109353 **
109354 **  (24)  The subquery is not an aggregate that uses the built-in min() or 
109355 **        or max() functions.  (Without this restriction, a query like:
109356 **        "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
109357 **        return the value X for which Y was maximal.)
109358 **
109359 **
109360 ** In this routine, the "p" parameter is a pointer to the outer query.
109361 ** The subquery is p->pSrc->a[iFrom].  isAgg is true if the outer query
109362 ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
109363 **
109364 ** If flattening is not attempted, this routine is a no-op and returns 0.
109365 ** If flattening is attempted this routine returns 1.
109366 **
109367 ** All of the expression analysis must occur on both the outer query and
109368 ** the subquery before this routine runs.
109369 */
109370 static int flattenSubquery(
109371   Parse *pParse,       /* Parsing context */
109372   Select *p,           /* The parent or outer SELECT statement */
109373   int iFrom,           /* Index in p->pSrc->a[] of the inner subquery */
109374   int isAgg,           /* True if outer SELECT uses aggregate functions */
109375   int subqueryIsAgg    /* True if the subquery uses aggregate functions */
109376 ){
109377   const char *zSavedAuthContext = pParse->zAuthContext;
109378   Select *pParent;
109379   Select *pSub;       /* The inner query or "subquery" */
109380   Select *pSub1;      /* Pointer to the rightmost select in sub-query */
109381   SrcList *pSrc;      /* The FROM clause of the outer query */
109382   SrcList *pSubSrc;   /* The FROM clause of the subquery */
109383   ExprList *pList;    /* The result set of the outer query */
109384   int iParent;        /* VDBE cursor number of the pSub result set temp table */
109385   int i;              /* Loop counter */
109386   Expr *pWhere;                    /* The WHERE clause */
109387   struct SrcList_item *pSubitem;   /* The subquery */
109388   sqlite3 *db = pParse->db;
109389
109390   /* Check to see if flattening is permitted.  Return 0 if not.
109391   */
109392   assert( p!=0 );
109393   assert( p->pPrior==0 );  /* Unable to flatten compound queries */
109394   if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
109395   pSrc = p->pSrc;
109396   assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
109397   pSubitem = &pSrc->a[iFrom];
109398   iParent = pSubitem->iCursor;
109399   pSub = pSubitem->pSelect;
109400   assert( pSub!=0 );
109401   if( subqueryIsAgg ){
109402     if( isAgg ) return 0;                                /* Restriction (1)   */
109403     if( pSrc->nSrc>1 ) return 0;                         /* Restriction (2a)  */
109404     if( (p->pWhere && ExprHasProperty(p->pWhere,EP_Subquery))
109405      || (sqlite3ExprListFlags(p->pEList) & EP_Subquery)!=0
109406      || (sqlite3ExprListFlags(p->pOrderBy) & EP_Subquery)!=0
109407     ){
109408       return 0;                                          /* Restriction (2b)  */
109409     }
109410   }
109411     
109412   pSubSrc = pSub->pSrc;
109413   assert( pSubSrc );
109414   /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
109415   ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
109416   ** because they could be computed at compile-time.  But when LIMIT and OFFSET
109417   ** became arbitrary expressions, we were forced to add restrictions (13)
109418   ** and (14). */
109419   if( pSub->pLimit && p->pLimit ) return 0;              /* Restriction (13) */
109420   if( pSub->pOffset ) return 0;                          /* Restriction (14) */
109421   if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
109422     return 0;                                            /* Restriction (15) */
109423   }
109424   if( pSubSrc->nSrc==0 ) return 0;                       /* Restriction (7)  */
109425   if( pSub->selFlags & SF_Distinct ) return 0;           /* Restriction (5)  */
109426   if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
109427      return 0;         /* Restrictions (8)(9) */
109428   }
109429   if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
109430      return 0;         /* Restriction (6)  */
109431   }
109432   if( p->pOrderBy && pSub->pOrderBy ){
109433      return 0;                                           /* Restriction (11) */
109434   }
109435   if( isAgg && pSub->pOrderBy ) return 0;                /* Restriction (16) */
109436   if( pSub->pLimit && p->pWhere ) return 0;              /* Restriction (19) */
109437   if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
109438      return 0;         /* Restriction (21) */
109439   }
109440   testcase( pSub->selFlags & SF_Recursive );
109441   testcase( pSub->selFlags & SF_MinMaxAgg );
109442   if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
109443     return 0; /* Restrictions (22) and (24) */
109444   }
109445   if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
109446     return 0; /* Restriction (23) */
109447   }
109448
109449   /* OBSOLETE COMMENT 1:
109450   ** Restriction 3:  If the subquery is a join, make sure the subquery is 
109451   ** not used as the right operand of an outer join.  Examples of why this
109452   ** is not allowed:
109453   **
109454   **         t1 LEFT OUTER JOIN (t2 JOIN t3)
109455   **
109456   ** If we flatten the above, we would get
109457   **
109458   **         (t1 LEFT OUTER JOIN t2) JOIN t3
109459   **
109460   ** which is not at all the same thing.
109461   **
109462   ** OBSOLETE COMMENT 2:
109463   ** Restriction 12:  If the subquery is the right operand of a left outer
109464   ** join, make sure the subquery has no WHERE clause.
109465   ** An examples of why this is not allowed:
109466   **
109467   **         t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
109468   **
109469   ** If we flatten the above, we would get
109470   **
109471   **         (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
109472   **
109473   ** But the t2.x>0 test will always fail on a NULL row of t2, which
109474   ** effectively converts the OUTER JOIN into an INNER JOIN.
109475   **
109476   ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
109477   ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
109478   ** is fraught with danger.  Best to avoid the whole thing.  If the
109479   ** subquery is the right term of a LEFT JOIN, then do not flatten.
109480   */
109481   if( (pSubitem->jointype & JT_OUTER)!=0 ){
109482     return 0;
109483   }
109484
109485   /* Restriction 17: If the sub-query is a compound SELECT, then it must
109486   ** use only the UNION ALL operator. And none of the simple select queries
109487   ** that make up the compound SELECT are allowed to be aggregate or distinct
109488   ** queries.
109489   */
109490   if( pSub->pPrior ){
109491     if( pSub->pOrderBy ){
109492       return 0;  /* Restriction 20 */
109493     }
109494     if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
109495       return 0;
109496     }
109497     for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
109498       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
109499       testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
109500       assert( pSub->pSrc!=0 );
109501       if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
109502        || (pSub1->pPrior && pSub1->op!=TK_ALL) 
109503        || pSub1->pSrc->nSrc<1
109504        || pSub->pEList->nExpr!=pSub1->pEList->nExpr
109505       ){
109506         return 0;
109507       }
109508       testcase( pSub1->pSrc->nSrc>1 );
109509     }
109510
109511     /* Restriction 18. */
109512     if( p->pOrderBy ){
109513       int ii;
109514       for(ii=0; ii<p->pOrderBy->nExpr; ii++){
109515         if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
109516       }
109517     }
109518   }
109519
109520   /***** If we reach this point, flattening is permitted. *****/
109521   SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
109522                    pSub->zSelName, pSub, iFrom));
109523
109524   /* Authorize the subquery */
109525   pParse->zAuthContext = pSubitem->zName;
109526   TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
109527   testcase( i==SQLITE_DENY );
109528   pParse->zAuthContext = zSavedAuthContext;
109529
109530   /* If the sub-query is a compound SELECT statement, then (by restrictions
109531   ** 17 and 18 above) it must be a UNION ALL and the parent query must 
109532   ** be of the form:
109533   **
109534   **     SELECT <expr-list> FROM (<sub-query>) <where-clause> 
109535   **
109536   ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
109537   ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or 
109538   ** OFFSET clauses and joins them to the left-hand-side of the original
109539   ** using UNION ALL operators. In this case N is the number of simple
109540   ** select statements in the compound sub-query.
109541   **
109542   ** Example:
109543   **
109544   **     SELECT a+1 FROM (
109545   **        SELECT x FROM tab
109546   **        UNION ALL
109547   **        SELECT y FROM tab
109548   **        UNION ALL
109549   **        SELECT abs(z*2) FROM tab2
109550   **     ) WHERE a!=5 ORDER BY 1
109551   **
109552   ** Transformed into:
109553   **
109554   **     SELECT x+1 FROM tab WHERE x+1!=5
109555   **     UNION ALL
109556   **     SELECT y+1 FROM tab WHERE y+1!=5
109557   **     UNION ALL
109558   **     SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
109559   **     ORDER BY 1
109560   **
109561   ** We call this the "compound-subquery flattening".
109562   */
109563   for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
109564     Select *pNew;
109565     ExprList *pOrderBy = p->pOrderBy;
109566     Expr *pLimit = p->pLimit;
109567     Expr *pOffset = p->pOffset;
109568     Select *pPrior = p->pPrior;
109569     p->pOrderBy = 0;
109570     p->pSrc = 0;
109571     p->pPrior = 0;
109572     p->pLimit = 0;
109573     p->pOffset = 0;
109574     pNew = sqlite3SelectDup(db, p, 0);
109575     sqlite3SelectSetName(pNew, pSub->zSelName);
109576     p->pOffset = pOffset;
109577     p->pLimit = pLimit;
109578     p->pOrderBy = pOrderBy;
109579     p->pSrc = pSrc;
109580     p->op = TK_ALL;
109581     if( pNew==0 ){
109582       p->pPrior = pPrior;
109583     }else{
109584       pNew->pPrior = pPrior;
109585       if( pPrior ) pPrior->pNext = pNew;
109586       pNew->pNext = p;
109587       p->pPrior = pNew;
109588       SELECTTRACE(2,pParse,p,
109589          ("compound-subquery flattener creates %s.%p as peer\n",
109590          pNew->zSelName, pNew));
109591     }
109592     if( db->mallocFailed ) return 1;
109593   }
109594
109595   /* Begin flattening the iFrom-th entry of the FROM clause 
109596   ** in the outer query.
109597   */
109598   pSub = pSub1 = pSubitem->pSelect;
109599
109600   /* Delete the transient table structure associated with the
109601   ** subquery
109602   */
109603   sqlite3DbFree(db, pSubitem->zDatabase);
109604   sqlite3DbFree(db, pSubitem->zName);
109605   sqlite3DbFree(db, pSubitem->zAlias);
109606   pSubitem->zDatabase = 0;
109607   pSubitem->zName = 0;
109608   pSubitem->zAlias = 0;
109609   pSubitem->pSelect = 0;
109610
109611   /* Defer deleting the Table object associated with the
109612   ** subquery until code generation is
109613   ** complete, since there may still exist Expr.pTab entries that
109614   ** refer to the subquery even after flattening.  Ticket #3346.
109615   **
109616   ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
109617   */
109618   if( ALWAYS(pSubitem->pTab!=0) ){
109619     Table *pTabToDel = pSubitem->pTab;
109620     if( pTabToDel->nRef==1 ){
109621       Parse *pToplevel = sqlite3ParseToplevel(pParse);
109622       pTabToDel->pNextZombie = pToplevel->pZombieTab;
109623       pToplevel->pZombieTab = pTabToDel;
109624     }else{
109625       pTabToDel->nRef--;
109626     }
109627     pSubitem->pTab = 0;
109628   }
109629
109630   /* The following loop runs once for each term in a compound-subquery
109631   ** flattening (as described above).  If we are doing a different kind
109632   ** of flattening - a flattening other than a compound-subquery flattening -
109633   ** then this loop only runs once.
109634   **
109635   ** This loop moves all of the FROM elements of the subquery into the
109636   ** the FROM clause of the outer query.  Before doing this, remember
109637   ** the cursor number for the original outer query FROM element in
109638   ** iParent.  The iParent cursor will never be used.  Subsequent code
109639   ** will scan expressions looking for iParent references and replace
109640   ** those references with expressions that resolve to the subquery FROM
109641   ** elements we are now copying in.
109642   */
109643   for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
109644     int nSubSrc;
109645     u8 jointype = 0;
109646     pSubSrc = pSub->pSrc;     /* FROM clause of subquery */
109647     nSubSrc = pSubSrc->nSrc;  /* Number of terms in subquery FROM clause */
109648     pSrc = pParent->pSrc;     /* FROM clause of the outer query */
109649
109650     if( pSrc ){
109651       assert( pParent==p );  /* First time through the loop */
109652       jointype = pSubitem->jointype;
109653     }else{
109654       assert( pParent!=p );  /* 2nd and subsequent times through the loop */
109655       pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
109656       if( pSrc==0 ){
109657         assert( db->mallocFailed );
109658         break;
109659       }
109660     }
109661
109662     /* The subquery uses a single slot of the FROM clause of the outer
109663     ** query.  If the subquery has more than one element in its FROM clause,
109664     ** then expand the outer query to make space for it to hold all elements
109665     ** of the subquery.
109666     **
109667     ** Example:
109668     **
109669     **    SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
109670     **
109671     ** The outer query has 3 slots in its FROM clause.  One slot of the
109672     ** outer query (the middle slot) is used by the subquery.  The next
109673     ** block of code will expand the out query to 4 slots.  The middle
109674     ** slot is expanded to two slots in order to make space for the
109675     ** two elements in the FROM clause of the subquery.
109676     */
109677     if( nSubSrc>1 ){
109678       pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
109679       if( db->mallocFailed ){
109680         break;
109681       }
109682     }
109683
109684     /* Transfer the FROM clause terms from the subquery into the
109685     ** outer query.
109686     */
109687     for(i=0; i<nSubSrc; i++){
109688       sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
109689       pSrc->a[i+iFrom] = pSubSrc->a[i];
109690       memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
109691     }
109692     pSrc->a[iFrom].jointype = jointype;
109693   
109694     /* Now begin substituting subquery result set expressions for 
109695     ** references to the iParent in the outer query.
109696     ** 
109697     ** Example:
109698     **
109699     **   SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
109700     **   \                     \_____________ subquery __________/          /
109701     **    \_____________________ outer query ______________________________/
109702     **
109703     ** We look at every expression in the outer query and every place we see
109704     ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
109705     */
109706     pList = pParent->pEList;
109707     for(i=0; i<pList->nExpr; i++){
109708       if( pList->a[i].zName==0 ){
109709         char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
109710         sqlite3Dequote(zName);
109711         pList->a[i].zName = zName;
109712       }
109713     }
109714     substExprList(db, pParent->pEList, iParent, pSub->pEList);
109715     if( isAgg ){
109716       substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
109717       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
109718     }
109719     if( pSub->pOrderBy ){
109720       /* At this point, any non-zero iOrderByCol values indicate that the
109721       ** ORDER BY column expression is identical to the iOrderByCol'th
109722       ** expression returned by SELECT statement pSub. Since these values
109723       ** do not necessarily correspond to columns in SELECT statement pParent,
109724       ** zero them before transfering the ORDER BY clause.
109725       **
109726       ** Not doing this may cause an error if a subsequent call to this
109727       ** function attempts to flatten a compound sub-query into pParent
109728       ** (the only way this can happen is if the compound sub-query is
109729       ** currently part of pSub->pSrc). See ticket [d11a6e908f].  */
109730       ExprList *pOrderBy = pSub->pOrderBy;
109731       for(i=0; i<pOrderBy->nExpr; i++){
109732         pOrderBy->a[i].u.x.iOrderByCol = 0;
109733       }
109734       assert( pParent->pOrderBy==0 );
109735       assert( pSub->pPrior==0 );
109736       pParent->pOrderBy = pOrderBy;
109737       pSub->pOrderBy = 0;
109738     }else if( pParent->pOrderBy ){
109739       substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
109740     }
109741     if( pSub->pWhere ){
109742       pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
109743     }else{
109744       pWhere = 0;
109745     }
109746     if( subqueryIsAgg ){
109747       assert( pParent->pHaving==0 );
109748       pParent->pHaving = pParent->pWhere;
109749       pParent->pWhere = pWhere;
109750       pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
109751       pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving, 
109752                                   sqlite3ExprDup(db, pSub->pHaving, 0));
109753       assert( pParent->pGroupBy==0 );
109754       pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
109755     }else{
109756       pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
109757       pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
109758     }
109759   
109760     /* The flattened query is distinct if either the inner or the
109761     ** outer query is distinct. 
109762     */
109763     pParent->selFlags |= pSub->selFlags & SF_Distinct;
109764   
109765     /*
109766     ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
109767     **
109768     ** One is tempted to try to add a and b to combine the limits.  But this
109769     ** does not work if either limit is negative.
109770     */
109771     if( pSub->pLimit ){
109772       pParent->pLimit = pSub->pLimit;
109773       pSub->pLimit = 0;
109774     }
109775   }
109776
109777   /* Finially, delete what is left of the subquery and return
109778   ** success.
109779   */
109780   sqlite3SelectDelete(db, pSub1);
109781
109782 #if SELECTTRACE_ENABLED
109783   if( sqlite3SelectTrace & 0x100 ){
109784     sqlite3DebugPrintf("After flattening:\n");
109785     sqlite3TreeViewSelect(0, p, 0);
109786   }
109787 #endif
109788
109789   return 1;
109790 }
109791 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
109792
109793 /*
109794 ** Based on the contents of the AggInfo structure indicated by the first
109795 ** argument, this function checks if the following are true:
109796 **
109797 **    * the query contains just a single aggregate function,
109798 **    * the aggregate function is either min() or max(), and
109799 **    * the argument to the aggregate function is a column value.
109800 **
109801 ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
109802 ** is returned as appropriate. Also, *ppMinMax is set to point to the 
109803 ** list of arguments passed to the aggregate before returning.
109804 **
109805 ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
109806 ** WHERE_ORDERBY_NORMAL is returned.
109807 */
109808 static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
109809   int eRet = WHERE_ORDERBY_NORMAL;          /* Return value */
109810
109811   *ppMinMax = 0;
109812   if( pAggInfo->nFunc==1 ){
109813     Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
109814     ExprList *pEList = pExpr->x.pList;      /* Arguments to agg function */
109815
109816     assert( pExpr->op==TK_AGG_FUNCTION );
109817     if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
109818       const char *zFunc = pExpr->u.zToken;
109819       if( sqlite3StrICmp(zFunc, "min")==0 ){
109820         eRet = WHERE_ORDERBY_MIN;
109821         *ppMinMax = pEList;
109822       }else if( sqlite3StrICmp(zFunc, "max")==0 ){
109823         eRet = WHERE_ORDERBY_MAX;
109824         *ppMinMax = pEList;
109825       }
109826     }
109827   }
109828
109829   assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
109830   return eRet;
109831 }
109832
109833 /*
109834 ** The select statement passed as the first argument is an aggregate query.
109835 ** The second argument is the associated aggregate-info object. This 
109836 ** function tests if the SELECT is of the form:
109837 **
109838 **   SELECT count(*) FROM <tbl>
109839 **
109840 ** where table is a database table, not a sub-select or view. If the query
109841 ** does match this pattern, then a pointer to the Table object representing
109842 ** <tbl> is returned. Otherwise, 0 is returned.
109843 */
109844 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
109845   Table *pTab;
109846   Expr *pExpr;
109847
109848   assert( !p->pGroupBy );
109849
109850   if( p->pWhere || p->pEList->nExpr!=1 
109851    || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
109852   ){
109853     return 0;
109854   }
109855   pTab = p->pSrc->a[0].pTab;
109856   pExpr = p->pEList->a[0].pExpr;
109857   assert( pTab && !pTab->pSelect && pExpr );
109858
109859   if( IsVirtual(pTab) ) return 0;
109860   if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
109861   if( NEVER(pAggInfo->nFunc==0) ) return 0;
109862   if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
109863   if( pExpr->flags&EP_Distinct ) return 0;
109864
109865   return pTab;
109866 }
109867
109868 /*
109869 ** If the source-list item passed as an argument was augmented with an
109870 ** INDEXED BY clause, then try to locate the specified index. If there
109871 ** was such a clause and the named index cannot be found, return 
109872 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate 
109873 ** pFrom->pIndex and return SQLITE_OK.
109874 */
109875 SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
109876   if( pFrom->pTab && pFrom->zIndex ){
109877     Table *pTab = pFrom->pTab;
109878     char *zIndex = pFrom->zIndex;
109879     Index *pIdx;
109880     for(pIdx=pTab->pIndex; 
109881         pIdx && sqlite3StrICmp(pIdx->zName, zIndex); 
109882         pIdx=pIdx->pNext
109883     );
109884     if( !pIdx ){
109885       sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
109886       pParse->checkSchema = 1;
109887       return SQLITE_ERROR;
109888     }
109889     pFrom->pIndex = pIdx;
109890   }
109891   return SQLITE_OK;
109892 }
109893 /*
109894 ** Detect compound SELECT statements that use an ORDER BY clause with 
109895 ** an alternative collating sequence.
109896 **
109897 **    SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
109898 **
109899 ** These are rewritten as a subquery:
109900 **
109901 **    SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
109902 **     ORDER BY ... COLLATE ...
109903 **
109904 ** This transformation is necessary because the multiSelectOrderBy() routine
109905 ** above that generates the code for a compound SELECT with an ORDER BY clause
109906 ** uses a merge algorithm that requires the same collating sequence on the
109907 ** result columns as on the ORDER BY clause.  See ticket
109908 ** http://www.sqlite.org/src/info/6709574d2a
109909 **
109910 ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
109911 ** The UNION ALL operator works fine with multiSelectOrderBy() even when
109912 ** there are COLLATE terms in the ORDER BY.
109913 */
109914 static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
109915   int i;
109916   Select *pNew;
109917   Select *pX;
109918   sqlite3 *db;
109919   struct ExprList_item *a;
109920   SrcList *pNewSrc;
109921   Parse *pParse;
109922   Token dummy;
109923
109924   if( p->pPrior==0 ) return WRC_Continue;
109925   if( p->pOrderBy==0 ) return WRC_Continue;
109926   for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
109927   if( pX==0 ) return WRC_Continue;
109928   a = p->pOrderBy->a;
109929   for(i=p->pOrderBy->nExpr-1; i>=0; i--){
109930     if( a[i].pExpr->flags & EP_Collate ) break;
109931   }
109932   if( i<0 ) return WRC_Continue;
109933
109934   /* If we reach this point, that means the transformation is required. */
109935
109936   pParse = pWalker->pParse;
109937   db = pParse->db;
109938   pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
109939   if( pNew==0 ) return WRC_Abort;
109940   memset(&dummy, 0, sizeof(dummy));
109941   pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
109942   if( pNewSrc==0 ) return WRC_Abort;
109943   *pNew = *p;
109944   p->pSrc = pNewSrc;
109945   p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
109946   p->op = TK_SELECT;
109947   p->pWhere = 0;
109948   pNew->pGroupBy = 0;
109949   pNew->pHaving = 0;
109950   pNew->pOrderBy = 0;
109951   p->pPrior = 0;
109952   p->pNext = 0;
109953   p->selFlags &= ~SF_Compound;
109954   assert( (p->selFlags & SF_Converted)==0 );
109955   p->selFlags |= SF_Converted;
109956   assert( pNew->pPrior!=0 );
109957   pNew->pPrior->pNext = pNew;
109958   pNew->pLimit = 0;
109959   pNew->pOffset = 0;
109960   return WRC_Continue;
109961 }
109962
109963 #ifndef SQLITE_OMIT_CTE
109964 /*
109965 ** Argument pWith (which may be NULL) points to a linked list of nested 
109966 ** WITH contexts, from inner to outermost. If the table identified by 
109967 ** FROM clause element pItem is really a common-table-expression (CTE) 
109968 ** then return a pointer to the CTE definition for that table. Otherwise
109969 ** return NULL.
109970 **
109971 ** If a non-NULL value is returned, set *ppContext to point to the With
109972 ** object that the returned CTE belongs to.
109973 */
109974 static struct Cte *searchWith(
109975   With *pWith,                    /* Current outermost WITH clause */
109976   struct SrcList_item *pItem,     /* FROM clause element to resolve */
109977   With **ppContext                /* OUT: WITH clause return value belongs to */
109978 ){
109979   const char *zName;
109980   if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
109981     With *p;
109982     for(p=pWith; p; p=p->pOuter){
109983       int i;
109984       for(i=0; i<p->nCte; i++){
109985         if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
109986           *ppContext = p;
109987           return &p->a[i];
109988         }
109989       }
109990     }
109991   }
109992   return 0;
109993 }
109994
109995 /* The code generator maintains a stack of active WITH clauses
109996 ** with the inner-most WITH clause being at the top of the stack.
109997 **
109998 ** This routine pushes the WITH clause passed as the second argument
109999 ** onto the top of the stack. If argument bFree is true, then this
110000 ** WITH clause will never be popped from the stack. In this case it
110001 ** should be freed along with the Parse object. In other cases, when
110002 ** bFree==0, the With object will be freed along with the SELECT 
110003 ** statement with which it is associated.
110004 */
110005 SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
110006   assert( bFree==0 || pParse->pWith==0 );
110007   if( pWith ){
110008     pWith->pOuter = pParse->pWith;
110009     pParse->pWith = pWith;
110010     pParse->bFreeWith = bFree;
110011   }
110012 }
110013
110014 /*
110015 ** This function checks if argument pFrom refers to a CTE declared by 
110016 ** a WITH clause on the stack currently maintained by the parser. And,
110017 ** if currently processing a CTE expression, if it is a recursive
110018 ** reference to the current CTE.
110019 **
110020 ** If pFrom falls into either of the two categories above, pFrom->pTab
110021 ** and other fields are populated accordingly. The caller should check
110022 ** (pFrom->pTab!=0) to determine whether or not a successful match
110023 ** was found.
110024 **
110025 ** Whether or not a match is found, SQLITE_OK is returned if no error
110026 ** occurs. If an error does occur, an error message is stored in the
110027 ** parser and some error code other than SQLITE_OK returned.
110028 */
110029 static int withExpand(
110030   Walker *pWalker, 
110031   struct SrcList_item *pFrom
110032 ){
110033   Parse *pParse = pWalker->pParse;
110034   sqlite3 *db = pParse->db;
110035   struct Cte *pCte;               /* Matched CTE (or NULL if no match) */
110036   With *pWith;                    /* WITH clause that pCte belongs to */
110037
110038   assert( pFrom->pTab==0 );
110039
110040   pCte = searchWith(pParse->pWith, pFrom, &pWith);
110041   if( pCte ){
110042     Table *pTab;
110043     ExprList *pEList;
110044     Select *pSel;
110045     Select *pLeft;                /* Left-most SELECT statement */
110046     int bMayRecursive;            /* True if compound joined by UNION [ALL] */
110047     With *pSavedWith;             /* Initial value of pParse->pWith */
110048
110049     /* If pCte->zErr is non-NULL at this point, then this is an illegal
110050     ** recursive reference to CTE pCte. Leave an error in pParse and return
110051     ** early. If pCte->zErr is NULL, then this is not a recursive reference.
110052     ** In this case, proceed.  */
110053     if( pCte->zErr ){
110054       sqlite3ErrorMsg(pParse, pCte->zErr, pCte->zName);
110055       return SQLITE_ERROR;
110056     }
110057
110058     assert( pFrom->pTab==0 );
110059     pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
110060     if( pTab==0 ) return WRC_Abort;
110061     pTab->nRef = 1;
110062     pTab->zName = sqlite3DbStrDup(db, pCte->zName);
110063     pTab->iPKey = -1;
110064     pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
110065     pTab->tabFlags |= TF_Ephemeral;
110066     pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
110067     if( db->mallocFailed ) return SQLITE_NOMEM;
110068     assert( pFrom->pSelect );
110069
110070     /* Check if this is a recursive CTE. */
110071     pSel = pFrom->pSelect;
110072     bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
110073     if( bMayRecursive ){
110074       int i;
110075       SrcList *pSrc = pFrom->pSelect->pSrc;
110076       for(i=0; i<pSrc->nSrc; i++){
110077         struct SrcList_item *pItem = &pSrc->a[i];
110078         if( pItem->zDatabase==0 
110079          && pItem->zName!=0 
110080          && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
110081           ){
110082           pItem->pTab = pTab;
110083           pItem->isRecursive = 1;
110084           pTab->nRef++;
110085           pSel->selFlags |= SF_Recursive;
110086         }
110087       }
110088     }
110089
110090     /* Only one recursive reference is permitted. */ 
110091     if( pTab->nRef>2 ){
110092       sqlite3ErrorMsg(
110093           pParse, "multiple references to recursive table: %s", pCte->zName
110094       );
110095       return SQLITE_ERROR;
110096     }
110097     assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
110098
110099     pCte->zErr = "circular reference: %s";
110100     pSavedWith = pParse->pWith;
110101     pParse->pWith = pWith;
110102     sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
110103
110104     for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
110105     pEList = pLeft->pEList;
110106     if( pCte->pCols ){
110107       if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
110108         sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
110109             pCte->zName, pEList->nExpr, pCte->pCols->nExpr
110110         );
110111         pParse->pWith = pSavedWith;
110112         return SQLITE_ERROR;
110113       }
110114       pEList = pCte->pCols;
110115     }
110116
110117     selectColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
110118     if( bMayRecursive ){
110119       if( pSel->selFlags & SF_Recursive ){
110120         pCte->zErr = "multiple recursive references: %s";
110121       }else{
110122         pCte->zErr = "recursive reference in a subquery: %s";
110123       }
110124       sqlite3WalkSelect(pWalker, pSel);
110125     }
110126     pCte->zErr = 0;
110127     pParse->pWith = pSavedWith;
110128   }
110129
110130   return SQLITE_OK;
110131 }
110132 #endif
110133
110134 #ifndef SQLITE_OMIT_CTE
110135 /*
110136 ** If the SELECT passed as the second argument has an associated WITH 
110137 ** clause, pop it from the stack stored as part of the Parse object.
110138 **
110139 ** This function is used as the xSelectCallback2() callback by
110140 ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
110141 ** names and other FROM clause elements. 
110142 */
110143 static void selectPopWith(Walker *pWalker, Select *p){
110144   Parse *pParse = pWalker->pParse;
110145   With *pWith = findRightmost(p)->pWith;
110146   if( pWith!=0 ){
110147     assert( pParse->pWith==pWith );
110148     pParse->pWith = pWith->pOuter;
110149   }
110150 }
110151 #else
110152 #define selectPopWith 0
110153 #endif
110154
110155 /*
110156 ** This routine is a Walker callback for "expanding" a SELECT statement.
110157 ** "Expanding" means to do the following:
110158 **
110159 **    (1)  Make sure VDBE cursor numbers have been assigned to every
110160 **         element of the FROM clause.
110161 **
110162 **    (2)  Fill in the pTabList->a[].pTab fields in the SrcList that 
110163 **         defines FROM clause.  When views appear in the FROM clause,
110164 **         fill pTabList->a[].pSelect with a copy of the SELECT statement
110165 **         that implements the view.  A copy is made of the view's SELECT
110166 **         statement so that we can freely modify or delete that statement
110167 **         without worrying about messing up the persistent representation
110168 **         of the view.
110169 **
110170 **    (3)  Add terms to the WHERE clause to accommodate the NATURAL keyword
110171 **         on joins and the ON and USING clause of joins.
110172 **
110173 **    (4)  Scan the list of columns in the result set (pEList) looking
110174 **         for instances of the "*" operator or the TABLE.* operator.
110175 **         If found, expand each "*" to be every column in every table
110176 **         and TABLE.* to be every column in TABLE.
110177 **
110178 */
110179 static int selectExpander(Walker *pWalker, Select *p){
110180   Parse *pParse = pWalker->pParse;
110181   int i, j, k;
110182   SrcList *pTabList;
110183   ExprList *pEList;
110184   struct SrcList_item *pFrom;
110185   sqlite3 *db = pParse->db;
110186   Expr *pE, *pRight, *pExpr;
110187   u16 selFlags = p->selFlags;
110188
110189   p->selFlags |= SF_Expanded;
110190   if( db->mallocFailed  ){
110191     return WRC_Abort;
110192   }
110193   if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
110194     return WRC_Prune;
110195   }
110196   pTabList = p->pSrc;
110197   pEList = p->pEList;
110198   if( pWalker->xSelectCallback2==selectPopWith ){
110199     sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
110200   }
110201
110202   /* Make sure cursor numbers have been assigned to all entries in
110203   ** the FROM clause of the SELECT statement.
110204   */
110205   sqlite3SrcListAssignCursors(pParse, pTabList);
110206
110207   /* Look up every table named in the FROM clause of the select.  If
110208   ** an entry of the FROM clause is a subquery instead of a table or view,
110209   ** then create a transient table structure to describe the subquery.
110210   */
110211   for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
110212     Table *pTab;
110213     assert( pFrom->isRecursive==0 || pFrom->pTab );
110214     if( pFrom->isRecursive ) continue;
110215     if( pFrom->pTab!=0 ){
110216       /* This statement has already been prepared.  There is no need
110217       ** to go further. */
110218       assert( i==0 );
110219 #ifndef SQLITE_OMIT_CTE
110220       selectPopWith(pWalker, p);
110221 #endif
110222       return WRC_Prune;
110223     }
110224 #ifndef SQLITE_OMIT_CTE
110225     if( withExpand(pWalker, pFrom) ) return WRC_Abort;
110226     if( pFrom->pTab ) {} else
110227 #endif
110228     if( pFrom->zName==0 ){
110229 #ifndef SQLITE_OMIT_SUBQUERY
110230       Select *pSel = pFrom->pSelect;
110231       /* A sub-query in the FROM clause of a SELECT */
110232       assert( pSel!=0 );
110233       assert( pFrom->pTab==0 );
110234       if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
110235       pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
110236       if( pTab==0 ) return WRC_Abort;
110237       pTab->nRef = 1;
110238       pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
110239       while( pSel->pPrior ){ pSel = pSel->pPrior; }
110240       selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
110241       pTab->iPKey = -1;
110242       pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
110243       pTab->tabFlags |= TF_Ephemeral;
110244 #endif
110245     }else{
110246       /* An ordinary table or view name in the FROM clause */
110247       assert( pFrom->pTab==0 );
110248       pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
110249       if( pTab==0 ) return WRC_Abort;
110250       if( pTab->nRef==0xffff ){
110251         sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
110252            pTab->zName);
110253         pFrom->pTab = 0;
110254         return WRC_Abort;
110255       }
110256       pTab->nRef++;
110257 #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
110258       if( pTab->pSelect || IsVirtual(pTab) ){
110259         /* We reach here if the named table is a really a view */
110260         if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
110261         assert( pFrom->pSelect==0 );
110262         pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
110263         sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
110264         sqlite3WalkSelect(pWalker, pFrom->pSelect);
110265       }
110266 #endif
110267     }
110268
110269     /* Locate the index named by the INDEXED BY clause, if any. */
110270     if( sqlite3IndexedByLookup(pParse, pFrom) ){
110271       return WRC_Abort;
110272     }
110273   }
110274
110275   /* Process NATURAL keywords, and ON and USING clauses of joins.
110276   */
110277   if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
110278     return WRC_Abort;
110279   }
110280
110281   /* For every "*" that occurs in the column list, insert the names of
110282   ** all columns in all tables.  And for every TABLE.* insert the names
110283   ** of all columns in TABLE.  The parser inserted a special expression
110284   ** with the TK_ALL operator for each "*" that it found in the column list.
110285   ** The following code just has to locate the TK_ALL expressions and expand
110286   ** each one to the list of all columns in all tables.
110287   **
110288   ** The first loop just checks to see if there are any "*" operators
110289   ** that need expanding.
110290   */
110291   for(k=0; k<pEList->nExpr; k++){
110292     pE = pEList->a[k].pExpr;
110293     if( pE->op==TK_ALL ) break;
110294     assert( pE->op!=TK_DOT || pE->pRight!=0 );
110295     assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
110296     if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
110297   }
110298   if( k<pEList->nExpr ){
110299     /*
110300     ** If we get here it means the result set contains one or more "*"
110301     ** operators that need to be expanded.  Loop through each expression
110302     ** in the result set and expand them one by one.
110303     */
110304     struct ExprList_item *a = pEList->a;
110305     ExprList *pNew = 0;
110306     int flags = pParse->db->flags;
110307     int longNames = (flags & SQLITE_FullColNames)!=0
110308                       && (flags & SQLITE_ShortColNames)==0;
110309
110310     /* When processing FROM-clause subqueries, it is always the case
110311     ** that full_column_names=OFF and short_column_names=ON.  The
110312     ** sqlite3ResultSetOfSelect() routine makes it so. */
110313     assert( (p->selFlags & SF_NestedFrom)==0
110314           || ((flags & SQLITE_FullColNames)==0 &&
110315               (flags & SQLITE_ShortColNames)!=0) );
110316
110317     for(k=0; k<pEList->nExpr; k++){
110318       pE = a[k].pExpr;
110319       pRight = pE->pRight;
110320       assert( pE->op!=TK_DOT || pRight!=0 );
110321       if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
110322         /* This particular expression does not need to be expanded.
110323         */
110324         pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
110325         if( pNew ){
110326           pNew->a[pNew->nExpr-1].zName = a[k].zName;
110327           pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
110328           a[k].zName = 0;
110329           a[k].zSpan = 0;
110330         }
110331         a[k].pExpr = 0;
110332       }else{
110333         /* This expression is a "*" or a "TABLE.*" and needs to be
110334         ** expanded. */
110335         int tableSeen = 0;      /* Set to 1 when TABLE matches */
110336         char *zTName = 0;       /* text of name of TABLE */
110337         if( pE->op==TK_DOT ){
110338           assert( pE->pLeft!=0 );
110339           assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
110340           zTName = pE->pLeft->u.zToken;
110341         }
110342         for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
110343           Table *pTab = pFrom->pTab;
110344           Select *pSub = pFrom->pSelect;
110345           char *zTabName = pFrom->zAlias;
110346           const char *zSchemaName = 0;
110347           int iDb;
110348           if( zTabName==0 ){
110349             zTabName = pTab->zName;
110350           }
110351           if( db->mallocFailed ) break;
110352           if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
110353             pSub = 0;
110354             if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
110355               continue;
110356             }
110357             iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
110358             zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
110359           }
110360           for(j=0; j<pTab->nCol; j++){
110361             char *zName = pTab->aCol[j].zName;
110362             char *zColname;  /* The computed column name */
110363             char *zToFree;   /* Malloced string that needs to be freed */
110364             Token sColname;  /* Computed column name as a token */
110365
110366             assert( zName );
110367             if( zTName && pSub
110368              && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
110369             ){
110370               continue;
110371             }
110372
110373             /* If a column is marked as 'hidden' (currently only possible
110374             ** for virtual tables), do not include it in the expanded
110375             ** result-set list.
110376             */
110377             if( IsHiddenColumn(&pTab->aCol[j]) ){
110378               assert(IsVirtual(pTab));
110379               continue;
110380             }
110381             tableSeen = 1;
110382
110383             if( i>0 && zTName==0 ){
110384               if( (pFrom->jointype & JT_NATURAL)!=0
110385                 && tableAndColumnIndex(pTabList, i, zName, 0, 0)
110386               ){
110387                 /* In a NATURAL join, omit the join columns from the 
110388                 ** table to the right of the join */
110389                 continue;
110390               }
110391               if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
110392                 /* In a join with a USING clause, omit columns in the
110393                 ** using clause from the table on the right. */
110394                 continue;
110395               }
110396             }
110397             pRight = sqlite3Expr(db, TK_ID, zName);
110398             zColname = zName;
110399             zToFree = 0;
110400             if( longNames || pTabList->nSrc>1 ){
110401               Expr *pLeft;
110402               pLeft = sqlite3Expr(db, TK_ID, zTabName);
110403               pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
110404               if( zSchemaName ){
110405                 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
110406                 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
110407               }
110408               if( longNames ){
110409                 zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
110410                 zToFree = zColname;
110411               }
110412             }else{
110413               pExpr = pRight;
110414             }
110415             pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
110416             sColname.z = zColname;
110417             sColname.n = sqlite3Strlen30(zColname);
110418             sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
110419             if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
110420               struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
110421               if( pSub ){
110422                 pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
110423                 testcase( pX->zSpan==0 );
110424               }else{
110425                 pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
110426                                            zSchemaName, zTabName, zColname);
110427                 testcase( pX->zSpan==0 );
110428               }
110429               pX->bSpanIsTab = 1;
110430             }
110431             sqlite3DbFree(db, zToFree);
110432           }
110433         }
110434         if( !tableSeen ){
110435           if( zTName ){
110436             sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
110437           }else{
110438             sqlite3ErrorMsg(pParse, "no tables specified");
110439           }
110440         }
110441       }
110442     }
110443     sqlite3ExprListDelete(db, pEList);
110444     p->pEList = pNew;
110445   }
110446 #if SQLITE_MAX_COLUMN
110447   if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
110448     sqlite3ErrorMsg(pParse, "too many columns in result set");
110449   }
110450 #endif
110451   return WRC_Continue;
110452 }
110453
110454 /*
110455 ** No-op routine for the parse-tree walker.
110456 **
110457 ** When this routine is the Walker.xExprCallback then expression trees
110458 ** are walked without any actions being taken at each node.  Presumably,
110459 ** when this routine is used for Walker.xExprCallback then 
110460 ** Walker.xSelectCallback is set to do something useful for every 
110461 ** subquery in the parser tree.
110462 */
110463 static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
110464   UNUSED_PARAMETER2(NotUsed, NotUsed2);
110465   return WRC_Continue;
110466 }
110467
110468 /*
110469 ** This routine "expands" a SELECT statement and all of its subqueries.
110470 ** For additional information on what it means to "expand" a SELECT
110471 ** statement, see the comment on the selectExpand worker callback above.
110472 **
110473 ** Expanding a SELECT statement is the first step in processing a
110474 ** SELECT statement.  The SELECT statement must be expanded before
110475 ** name resolution is performed.
110476 **
110477 ** If anything goes wrong, an error message is written into pParse.
110478 ** The calling function can detect the problem by looking at pParse->nErr
110479 ** and/or pParse->db->mallocFailed.
110480 */
110481 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
110482   Walker w;
110483   memset(&w, 0, sizeof(w));
110484   w.xExprCallback = exprWalkNoop;
110485   w.pParse = pParse;
110486   if( pParse->hasCompound ){
110487     w.xSelectCallback = convertCompoundSelectToSubquery;
110488     sqlite3WalkSelect(&w, pSelect);
110489   }
110490   w.xSelectCallback = selectExpander;
110491   if( (pSelect->selFlags & SF_AllValues)==0 ){
110492     w.xSelectCallback2 = selectPopWith;
110493   }
110494   sqlite3WalkSelect(&w, pSelect);
110495 }
110496
110497
110498 #ifndef SQLITE_OMIT_SUBQUERY
110499 /*
110500 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
110501 ** interface.
110502 **
110503 ** For each FROM-clause subquery, add Column.zType and Column.zColl
110504 ** information to the Table structure that represents the result set
110505 ** of that subquery.
110506 **
110507 ** The Table structure that represents the result set was constructed
110508 ** by selectExpander() but the type and collation information was omitted
110509 ** at that point because identifiers had not yet been resolved.  This
110510 ** routine is called after identifier resolution.
110511 */
110512 static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
110513   Parse *pParse;
110514   int i;
110515   SrcList *pTabList;
110516   struct SrcList_item *pFrom;
110517
110518   assert( p->selFlags & SF_Resolved );
110519   if( (p->selFlags & SF_HasTypeInfo)==0 ){
110520     p->selFlags |= SF_HasTypeInfo;
110521     pParse = pWalker->pParse;
110522     pTabList = p->pSrc;
110523     for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
110524       Table *pTab = pFrom->pTab;
110525       if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
110526         /* A sub-query in the FROM clause of a SELECT */
110527         Select *pSel = pFrom->pSelect;
110528         if( pSel ){
110529           while( pSel->pPrior ) pSel = pSel->pPrior;
110530           selectAddColumnTypeAndCollation(pParse, pTab, pSel);
110531         }
110532       }
110533     }
110534   }
110535 }
110536 #endif
110537
110538
110539 /*
110540 ** This routine adds datatype and collating sequence information to
110541 ** the Table structures of all FROM-clause subqueries in a
110542 ** SELECT statement.
110543 **
110544 ** Use this routine after name resolution.
110545 */
110546 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
110547 #ifndef SQLITE_OMIT_SUBQUERY
110548   Walker w;
110549   memset(&w, 0, sizeof(w));
110550   w.xSelectCallback2 = selectAddSubqueryTypeInfo;
110551   w.xExprCallback = exprWalkNoop;
110552   w.pParse = pParse;
110553   sqlite3WalkSelect(&w, pSelect);
110554 #endif
110555 }
110556
110557
110558 /*
110559 ** This routine sets up a SELECT statement for processing.  The
110560 ** following is accomplished:
110561 **
110562 **     *  VDBE Cursor numbers are assigned to all FROM-clause terms.
110563 **     *  Ephemeral Table objects are created for all FROM-clause subqueries.
110564 **     *  ON and USING clauses are shifted into WHERE statements
110565 **     *  Wildcards "*" and "TABLE.*" in result sets are expanded.
110566 **     *  Identifiers in expression are matched to tables.
110567 **
110568 ** This routine acts recursively on all subqueries within the SELECT.
110569 */
110570 SQLITE_PRIVATE void sqlite3SelectPrep(
110571   Parse *pParse,         /* The parser context */
110572   Select *p,             /* The SELECT statement being coded. */
110573   NameContext *pOuterNC  /* Name context for container */
110574 ){
110575   sqlite3 *db;
110576   if( NEVER(p==0) ) return;
110577   db = pParse->db;
110578   if( db->mallocFailed ) return;
110579   if( p->selFlags & SF_HasTypeInfo ) return;
110580   sqlite3SelectExpand(pParse, p);
110581   if( pParse->nErr || db->mallocFailed ) return;
110582   sqlite3ResolveSelectNames(pParse, p, pOuterNC);
110583   if( pParse->nErr || db->mallocFailed ) return;
110584   sqlite3SelectAddTypeInfo(pParse, p);
110585 }
110586
110587 /*
110588 ** Reset the aggregate accumulator.
110589 **
110590 ** The aggregate accumulator is a set of memory cells that hold
110591 ** intermediate results while calculating an aggregate.  This
110592 ** routine generates code that stores NULLs in all of those memory
110593 ** cells.
110594 */
110595 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
110596   Vdbe *v = pParse->pVdbe;
110597   int i;
110598   struct AggInfo_func *pFunc;
110599   int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
110600   if( nReg==0 ) return;
110601 #ifdef SQLITE_DEBUG
110602   /* Verify that all AggInfo registers are within the range specified by
110603   ** AggInfo.mnReg..AggInfo.mxReg */
110604   assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
110605   for(i=0; i<pAggInfo->nColumn; i++){
110606     assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
110607          && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
110608   }
110609   for(i=0; i<pAggInfo->nFunc; i++){
110610     assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
110611          && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
110612   }
110613 #endif
110614   sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
110615   for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
110616     if( pFunc->iDistinct>=0 ){
110617       Expr *pE = pFunc->pExpr;
110618       assert( !ExprHasProperty(pE, EP_xIsSelect) );
110619       if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
110620         sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
110621            "argument");
110622         pFunc->iDistinct = -1;
110623       }else{
110624         KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
110625         sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
110626                           (char*)pKeyInfo, P4_KEYINFO);
110627       }
110628     }
110629   }
110630 }
110631
110632 /*
110633 ** Invoke the OP_AggFinalize opcode for every aggregate function
110634 ** in the AggInfo structure.
110635 */
110636 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
110637   Vdbe *v = pParse->pVdbe;
110638   int i;
110639   struct AggInfo_func *pF;
110640   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
110641     ExprList *pList = pF->pExpr->x.pList;
110642     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
110643     sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
110644                       (void*)pF->pFunc, P4_FUNCDEF);
110645   }
110646 }
110647
110648 /*
110649 ** Update the accumulator memory cells for an aggregate based on
110650 ** the current cursor position.
110651 */
110652 static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
110653   Vdbe *v = pParse->pVdbe;
110654   int i;
110655   int regHit = 0;
110656   int addrHitTest = 0;
110657   struct AggInfo_func *pF;
110658   struct AggInfo_col *pC;
110659
110660   pAggInfo->directMode = 1;
110661   for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
110662     int nArg;
110663     int addrNext = 0;
110664     int regAgg;
110665     ExprList *pList = pF->pExpr->x.pList;
110666     assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
110667     if( pList ){
110668       nArg = pList->nExpr;
110669       regAgg = sqlite3GetTempRange(pParse, nArg);
110670       sqlite3ExprCodeExprList(pParse, pList, regAgg, SQLITE_ECEL_DUP);
110671     }else{
110672       nArg = 0;
110673       regAgg = 0;
110674     }
110675     if( pF->iDistinct>=0 ){
110676       addrNext = sqlite3VdbeMakeLabel(v);
110677       assert( nArg==1 );
110678       codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
110679     }
110680     if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
110681       CollSeq *pColl = 0;
110682       struct ExprList_item *pItem;
110683       int j;
110684       assert( pList!=0 );  /* pList!=0 if pF->pFunc has NEEDCOLL */
110685       for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
110686         pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
110687       }
110688       if( !pColl ){
110689         pColl = pParse->db->pDfltColl;
110690       }
110691       if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
110692       sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
110693     }
110694     sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
110695                       (void*)pF->pFunc, P4_FUNCDEF);
110696     sqlite3VdbeChangeP5(v, (u8)nArg);
110697     sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
110698     sqlite3ReleaseTempRange(pParse, regAgg, nArg);
110699     if( addrNext ){
110700       sqlite3VdbeResolveLabel(v, addrNext);
110701       sqlite3ExprCacheClear(pParse);
110702     }
110703   }
110704
110705   /* Before populating the accumulator registers, clear the column cache.
110706   ** Otherwise, if any of the required column values are already present 
110707   ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
110708   ** to pC->iMem. But by the time the value is used, the original register
110709   ** may have been used, invalidating the underlying buffer holding the
110710   ** text or blob value. See ticket [883034dcb5].
110711   **
110712   ** Another solution would be to change the OP_SCopy used to copy cached
110713   ** values to an OP_Copy.
110714   */
110715   if( regHit ){
110716     addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
110717   }
110718   sqlite3ExprCacheClear(pParse);
110719   for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
110720     sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
110721   }
110722   pAggInfo->directMode = 0;
110723   sqlite3ExprCacheClear(pParse);
110724   if( addrHitTest ){
110725     sqlite3VdbeJumpHere(v, addrHitTest);
110726   }
110727 }
110728
110729 /*
110730 ** Add a single OP_Explain instruction to the VDBE to explain a simple
110731 ** count(*) query ("SELECT count(*) FROM pTab").
110732 */
110733 #ifndef SQLITE_OMIT_EXPLAIN
110734 static void explainSimpleCount(
110735   Parse *pParse,                  /* Parse context */
110736   Table *pTab,                    /* Table being queried */
110737   Index *pIdx                     /* Index used to optimize scan, or NULL */
110738 ){
110739   if( pParse->explain==2 ){
110740     int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
110741     char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
110742         pTab->zName,
110743         bCover ? " USING COVERING INDEX " : "",
110744         bCover ? pIdx->zName : ""
110745     );
110746     sqlite3VdbeAddOp4(
110747         pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
110748     );
110749   }
110750 }
110751 #else
110752 # define explainSimpleCount(a,b,c)
110753 #endif
110754
110755 /*
110756 ** Generate code for the SELECT statement given in the p argument.  
110757 **
110758 ** The results are returned according to the SelectDest structure.
110759 ** See comments in sqliteInt.h for further information.
110760 **
110761 ** This routine returns the number of errors.  If any errors are
110762 ** encountered, then an appropriate error message is left in
110763 ** pParse->zErrMsg.
110764 **
110765 ** This routine does NOT free the Select structure passed in.  The
110766 ** calling function needs to do that.
110767 */
110768 SQLITE_PRIVATE int sqlite3Select(
110769   Parse *pParse,         /* The parser context */
110770   Select *p,             /* The SELECT statement being coded. */
110771   SelectDest *pDest      /* What to do with the query results */
110772 ){
110773   int i, j;              /* Loop counters */
110774   WhereInfo *pWInfo;     /* Return from sqlite3WhereBegin() */
110775   Vdbe *v;               /* The virtual machine under construction */
110776   int isAgg;             /* True for select lists like "count(*)" */
110777   ExprList *pEList;      /* List of columns to extract. */
110778   SrcList *pTabList;     /* List of tables to select from */
110779   Expr *pWhere;          /* The WHERE clause.  May be NULL */
110780   ExprList *pGroupBy;    /* The GROUP BY clause.  May be NULL */
110781   Expr *pHaving;         /* The HAVING clause.  May be NULL */
110782   int rc = 1;            /* Value to return from this function */
110783   DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
110784   SortCtx sSort;         /* Info on how to code the ORDER BY clause */
110785   AggInfo sAggInfo;      /* Information used by aggregate queries */
110786   int iEnd;              /* Address of the end of the query */
110787   sqlite3 *db;           /* The database connection */
110788
110789 #ifndef SQLITE_OMIT_EXPLAIN
110790   int iRestoreSelectId = pParse->iSelectId;
110791   pParse->iSelectId = pParse->iNextSelectId++;
110792 #endif
110793
110794   db = pParse->db;
110795   if( p==0 || db->mallocFailed || pParse->nErr ){
110796     return 1;
110797   }
110798   if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
110799   memset(&sAggInfo, 0, sizeof(sAggInfo));
110800 #if SELECTTRACE_ENABLED
110801   pParse->nSelectIndent++;
110802   SELECTTRACE(1,pParse,p, ("begin processing:\n"));
110803   if( sqlite3SelectTrace & 0x100 ){
110804     sqlite3TreeViewSelect(0, p, 0);
110805   }
110806 #endif
110807
110808   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
110809   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
110810   assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
110811   assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
110812   if( IgnorableOrderby(pDest) ){
110813     assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union || 
110814            pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
110815            pDest->eDest==SRT_Queue  || pDest->eDest==SRT_DistFifo ||
110816            pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
110817     /* If ORDER BY makes no difference in the output then neither does
110818     ** DISTINCT so it can be removed too. */
110819     sqlite3ExprListDelete(db, p->pOrderBy);
110820     p->pOrderBy = 0;
110821     p->selFlags &= ~SF_Distinct;
110822   }
110823   sqlite3SelectPrep(pParse, p, 0);
110824   memset(&sSort, 0, sizeof(sSort));
110825   sSort.pOrderBy = p->pOrderBy;
110826   pTabList = p->pSrc;
110827   pEList = p->pEList;
110828   if( pParse->nErr || db->mallocFailed ){
110829     goto select_end;
110830   }
110831   isAgg = (p->selFlags & SF_Aggregate)!=0;
110832   assert( pEList!=0 );
110833 #if SELECTTRACE_ENABLED
110834   if( sqlite3SelectTrace & 0x100 ){
110835     SELECTTRACE(0x100,pParse,p, ("after name resolution:\n"));
110836     sqlite3TreeViewSelect(0, p, 0);
110837   }
110838 #endif
110839
110840
110841   /* Begin generating code.
110842   */
110843   v = sqlite3GetVdbe(pParse);
110844   if( v==0 ) goto select_end;
110845
110846   /* If writing to memory or generating a set
110847   ** only a single column may be output.
110848   */
110849 #ifndef SQLITE_OMIT_SUBQUERY
110850   if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
110851     goto select_end;
110852   }
110853 #endif
110854
110855   /* Generate code for all sub-queries in the FROM clause
110856   */
110857 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
110858   for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
110859     struct SrcList_item *pItem = &pTabList->a[i];
110860     SelectDest dest;
110861     Select *pSub = pItem->pSelect;
110862     int isAggSub;
110863
110864     if( pSub==0 ) continue;
110865
110866     /* Sometimes the code for a subquery will be generated more than
110867     ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
110868     ** for example.  In that case, do not regenerate the code to manifest
110869     ** a view or the co-routine to implement a view.  The first instance
110870     ** is sufficient, though the subroutine to manifest the view does need
110871     ** to be invoked again. */
110872     if( pItem->addrFillSub ){
110873       if( pItem->viaCoroutine==0 ){
110874         sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
110875       }
110876       continue;
110877     }
110878
110879     /* Increment Parse.nHeight by the height of the largest expression
110880     ** tree referred to by this, the parent select. The child select
110881     ** may contain expression trees of at most
110882     ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
110883     ** more conservative than necessary, but much easier than enforcing
110884     ** an exact limit.
110885     */
110886     pParse->nHeight += sqlite3SelectExprHeight(p);
110887
110888     isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
110889     if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
110890       /* This subquery can be absorbed into its parent. */
110891       if( isAggSub ){
110892         isAgg = 1;
110893         p->selFlags |= SF_Aggregate;
110894       }
110895       i = -1;
110896     }else if( pTabList->nSrc==1
110897            && OptimizationEnabled(db, SQLITE_SubqCoroutine)
110898     ){
110899       /* Implement a co-routine that will return a single row of the result
110900       ** set on each invocation.
110901       */
110902       int addrTop = sqlite3VdbeCurrentAddr(v)+1;
110903       pItem->regReturn = ++pParse->nMem;
110904       sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
110905       VdbeComment((v, "%s", pItem->pTab->zName));
110906       pItem->addrFillSub = addrTop;
110907       sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
110908       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
110909       sqlite3Select(pParse, pSub, &dest);
110910       pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
110911       pItem->viaCoroutine = 1;
110912       pItem->regResult = dest.iSdst;
110913       sqlite3VdbeAddOp1(v, OP_EndCoroutine, pItem->regReturn);
110914       sqlite3VdbeJumpHere(v, addrTop-1);
110915       sqlite3ClearTempRegCache(pParse);
110916     }else{
110917       /* Generate a subroutine that will fill an ephemeral table with
110918       ** the content of this subquery.  pItem->addrFillSub will point
110919       ** to the address of the generated subroutine.  pItem->regReturn
110920       ** is a register allocated to hold the subroutine return address
110921       */
110922       int topAddr;
110923       int onceAddr = 0;
110924       int retAddr;
110925       assert( pItem->addrFillSub==0 );
110926       pItem->regReturn = ++pParse->nMem;
110927       topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
110928       pItem->addrFillSub = topAddr+1;
110929       if( pItem->isCorrelated==0 ){
110930         /* If the subquery is not correlated and if we are not inside of
110931         ** a trigger, then we only need to compute the value of the subquery
110932         ** once. */
110933         onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
110934         VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
110935       }else{
110936         VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
110937       }
110938       sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
110939       explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
110940       sqlite3Select(pParse, pSub, &dest);
110941       pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
110942       if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
110943       retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
110944       VdbeComment((v, "end %s", pItem->pTab->zName));
110945       sqlite3VdbeChangeP1(v, topAddr, retAddr);
110946       sqlite3ClearTempRegCache(pParse);
110947     }
110948     if( /*pParse->nErr ||*/ db->mallocFailed ){
110949       goto select_end;
110950     }
110951     pParse->nHeight -= sqlite3SelectExprHeight(p);
110952     pTabList = p->pSrc;
110953     if( !IgnorableOrderby(pDest) ){
110954       sSort.pOrderBy = p->pOrderBy;
110955     }
110956   }
110957   pEList = p->pEList;
110958 #endif
110959   pWhere = p->pWhere;
110960   pGroupBy = p->pGroupBy;
110961   pHaving = p->pHaving;
110962   sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
110963
110964 #ifndef SQLITE_OMIT_COMPOUND_SELECT
110965   /* If there is are a sequence of queries, do the earlier ones first.
110966   */
110967   if( p->pPrior ){
110968     rc = multiSelect(pParse, p, pDest);
110969     explainSetInteger(pParse->iSelectId, iRestoreSelectId);
110970 #if SELECTTRACE_ENABLED
110971     SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
110972     pParse->nSelectIndent--;
110973 #endif
110974     return rc;
110975   }
110976 #endif
110977
110978   /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and 
110979   ** if the select-list is the same as the ORDER BY list, then this query
110980   ** can be rewritten as a GROUP BY. In other words, this:
110981   **
110982   **     SELECT DISTINCT xyz FROM ... ORDER BY xyz
110983   **
110984   ** is transformed to:
110985   **
110986   **     SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
110987   **
110988   ** The second form is preferred as a single index (or temp-table) may be 
110989   ** used for both the ORDER BY and DISTINCT processing. As originally 
110990   ** written the query must use a temp-table for at least one of the ORDER 
110991   ** BY and DISTINCT, and an index or separate temp-table for the other.
110992   */
110993   if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct 
110994    && sqlite3ExprListCompare(sSort.pOrderBy, p->pEList, -1)==0
110995   ){
110996     p->selFlags &= ~SF_Distinct;
110997     p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
110998     pGroupBy = p->pGroupBy;
110999     /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
111000     ** the sDistinct.isTnct is still set.  Hence, isTnct represents the
111001     ** original setting of the SF_Distinct flag, not the current setting */
111002     assert( sDistinct.isTnct );
111003   }
111004
111005   /* If there is an ORDER BY clause, then this sorting
111006   ** index might end up being unused if the data can be 
111007   ** extracted in pre-sorted order.  If that is the case, then the
111008   ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
111009   ** we figure out that the sorting index is not needed.  The addrSortIndex
111010   ** variable is used to facilitate that change.
111011   */
111012   if( sSort.pOrderBy ){
111013     KeyInfo *pKeyInfo;
111014     pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, pEList->nExpr);
111015     sSort.iECursor = pParse->nTab++;
111016     sSort.addrSortIndex =
111017       sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
111018           sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
111019           (char*)pKeyInfo, P4_KEYINFO
111020       );
111021   }else{
111022     sSort.addrSortIndex = -1;
111023   }
111024
111025   /* If the output is destined for a temporary table, open that table.
111026   */
111027   if( pDest->eDest==SRT_EphemTab ){
111028     sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
111029   }
111030
111031   /* Set the limiter.
111032   */
111033   iEnd = sqlite3VdbeMakeLabel(v);
111034   p->nSelectRow = LARGEST_INT64;
111035   computeLimitRegisters(pParse, p, iEnd);
111036   if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
111037     sqlite3VdbeGetOp(v, sSort.addrSortIndex)->opcode = OP_SorterOpen;
111038     sSort.sortFlags |= SORTFLAG_UseSorter;
111039   }
111040
111041   /* Open a virtual index to use for the distinct set.
111042   */
111043   if( p->selFlags & SF_Distinct ){
111044     sDistinct.tabTnct = pParse->nTab++;
111045     sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
111046                                 sDistinct.tabTnct, 0, 0,
111047                                 (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
111048                                 P4_KEYINFO);
111049     sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
111050     sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
111051   }else{
111052     sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
111053   }
111054
111055   if( !isAgg && pGroupBy==0 ){
111056     /* No aggregate functions and no GROUP BY clause */
111057     u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
111058
111059     /* Begin the database scan. */
111060     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
111061                                p->pEList, wctrlFlags, 0);
111062     if( pWInfo==0 ) goto select_end;
111063     if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
111064       p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
111065     }
111066     if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
111067       sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
111068     }
111069     if( sSort.pOrderBy ){
111070       sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
111071       if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
111072         sSort.pOrderBy = 0;
111073       }
111074     }
111075
111076     /* If sorting index that was created by a prior OP_OpenEphemeral 
111077     ** instruction ended up not being needed, then change the OP_OpenEphemeral
111078     ** into an OP_Noop.
111079     */
111080     if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
111081       sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
111082     }
111083
111084     /* Use the standard inner loop. */
111085     selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
111086                     sqlite3WhereContinueLabel(pWInfo),
111087                     sqlite3WhereBreakLabel(pWInfo));
111088
111089     /* End the database scan loop.
111090     */
111091     sqlite3WhereEnd(pWInfo);
111092   }else{
111093     /* This case when there exist aggregate functions or a GROUP BY clause
111094     ** or both */
111095     NameContext sNC;    /* Name context for processing aggregate information */
111096     int iAMem;          /* First Mem address for storing current GROUP BY */
111097     int iBMem;          /* First Mem address for previous GROUP BY */
111098     int iUseFlag;       /* Mem address holding flag indicating that at least
111099                         ** one row of the input to the aggregator has been
111100                         ** processed */
111101     int iAbortFlag;     /* Mem address which causes query abort if positive */
111102     int groupBySort;    /* Rows come from source in GROUP BY order */
111103     int addrEnd;        /* End of processing for this SELECT */
111104     int sortPTab = 0;   /* Pseudotable used to decode sorting results */
111105     int sortOut = 0;    /* Output register from the sorter */
111106     int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
111107
111108     /* Remove any and all aliases between the result set and the
111109     ** GROUP BY clause.
111110     */
111111     if( pGroupBy ){
111112       int k;                        /* Loop counter */
111113       struct ExprList_item *pItem;  /* For looping over expression in a list */
111114
111115       for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
111116         pItem->u.x.iAlias = 0;
111117       }
111118       for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
111119         pItem->u.x.iAlias = 0;
111120       }
111121       if( p->nSelectRow>100 ) p->nSelectRow = 100;
111122     }else{
111123       p->nSelectRow = 1;
111124     }
111125
111126
111127     /* If there is both a GROUP BY and an ORDER BY clause and they are
111128     ** identical, then it may be possible to disable the ORDER BY clause 
111129     ** on the grounds that the GROUP BY will cause elements to come out 
111130     ** in the correct order. It also may not - the GROUP BY may use a
111131     ** database index that causes rows to be grouped together as required
111132     ** but not actually sorted. Either way, record the fact that the
111133     ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
111134     ** variable.  */
111135     if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
111136       orderByGrp = 1;
111137     }
111138  
111139     /* Create a label to jump to when we want to abort the query */
111140     addrEnd = sqlite3VdbeMakeLabel(v);
111141
111142     /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
111143     ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
111144     ** SELECT statement.
111145     */
111146     memset(&sNC, 0, sizeof(sNC));
111147     sNC.pParse = pParse;
111148     sNC.pSrcList = pTabList;
111149     sNC.pAggInfo = &sAggInfo;
111150     sAggInfo.mnReg = pParse->nMem+1;
111151     sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
111152     sAggInfo.pGroupBy = pGroupBy;
111153     sqlite3ExprAnalyzeAggList(&sNC, pEList);
111154     sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
111155     if( pHaving ){
111156       sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
111157     }
111158     sAggInfo.nAccumulator = sAggInfo.nColumn;
111159     for(i=0; i<sAggInfo.nFunc; i++){
111160       assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
111161       sNC.ncFlags |= NC_InAggFunc;
111162       sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
111163       sNC.ncFlags &= ~NC_InAggFunc;
111164     }
111165     sAggInfo.mxReg = pParse->nMem;
111166     if( db->mallocFailed ) goto select_end;
111167
111168     /* Processing for aggregates with GROUP BY is very different and
111169     ** much more complex than aggregates without a GROUP BY.
111170     */
111171     if( pGroupBy ){
111172       KeyInfo *pKeyInfo;  /* Keying information for the group by clause */
111173       int j1;             /* A-vs-B comparision jump */
111174       int addrOutputRow;  /* Start of subroutine that outputs a result row */
111175       int regOutputRow;   /* Return address register for output subroutine */
111176       int addrSetAbort;   /* Set the abort flag and return */
111177       int addrTopOfLoop;  /* Top of the input loop */
111178       int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
111179       int addrReset;      /* Subroutine for resetting the accumulator */
111180       int regReset;       /* Return address register for reset subroutine */
111181
111182       /* If there is a GROUP BY clause we might need a sorting index to
111183       ** implement it.  Allocate that sorting index now.  If it turns out
111184       ** that we do not need it after all, the OP_SorterOpen instruction
111185       ** will be converted into a Noop.  
111186       */
111187       sAggInfo.sortingIdx = pParse->nTab++;
111188       pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, sAggInfo.nColumn);
111189       addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen, 
111190           sAggInfo.sortingIdx, sAggInfo.nSortingColumn, 
111191           0, (char*)pKeyInfo, P4_KEYINFO);
111192
111193       /* Initialize memory locations used by GROUP BY aggregate processing
111194       */
111195       iUseFlag = ++pParse->nMem;
111196       iAbortFlag = ++pParse->nMem;
111197       regOutputRow = ++pParse->nMem;
111198       addrOutputRow = sqlite3VdbeMakeLabel(v);
111199       regReset = ++pParse->nMem;
111200       addrReset = sqlite3VdbeMakeLabel(v);
111201       iAMem = pParse->nMem + 1;
111202       pParse->nMem += pGroupBy->nExpr;
111203       iBMem = pParse->nMem + 1;
111204       pParse->nMem += pGroupBy->nExpr;
111205       sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
111206       VdbeComment((v, "clear abort flag"));
111207       sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
111208       VdbeComment((v, "indicate accumulator empty"));
111209       sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
111210
111211       /* Begin a loop that will extract all source rows in GROUP BY order.
111212       ** This might involve two separate loops with an OP_Sort in between, or
111213       ** it might be a single loop that uses an index to extract information
111214       ** in the right order to begin with.
111215       */
111216       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
111217       pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
111218           WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
111219       );
111220       if( pWInfo==0 ) goto select_end;
111221       if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
111222         /* The optimizer is able to deliver rows in group by order so
111223         ** we do not have to sort.  The OP_OpenEphemeral table will be
111224         ** cancelled later because we still need to use the pKeyInfo
111225         */
111226         groupBySort = 0;
111227       }else{
111228         /* Rows are coming out in undetermined order.  We have to push
111229         ** each row into a sorting index, terminate the first loop,
111230         ** then loop over the sorting index in order to get the output
111231         ** in sorted order
111232         */
111233         int regBase;
111234         int regRecord;
111235         int nCol;
111236         int nGroupBy;
111237
111238         explainTempTable(pParse, 
111239             (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
111240                     "DISTINCT" : "GROUP BY");
111241
111242         groupBySort = 1;
111243         nGroupBy = pGroupBy->nExpr;
111244         nCol = nGroupBy;
111245         j = nGroupBy;
111246         for(i=0; i<sAggInfo.nColumn; i++){
111247           if( sAggInfo.aCol[i].iSorterColumn>=j ){
111248             nCol++;
111249             j++;
111250           }
111251         }
111252         regBase = sqlite3GetTempRange(pParse, nCol);
111253         sqlite3ExprCacheClear(pParse);
111254         sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
111255         j = nGroupBy;
111256         for(i=0; i<sAggInfo.nColumn; i++){
111257           struct AggInfo_col *pCol = &sAggInfo.aCol[i];
111258           if( pCol->iSorterColumn>=j ){
111259             int r1 = j + regBase;
111260             int r2;
111261
111262             r2 = sqlite3ExprCodeGetColumn(pParse, 
111263                                pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
111264             if( r1!=r2 ){
111265               sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
111266             }
111267             j++;
111268           }
111269         }
111270         regRecord = sqlite3GetTempReg(pParse);
111271         sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
111272         sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
111273         sqlite3ReleaseTempReg(pParse, regRecord);
111274         sqlite3ReleaseTempRange(pParse, regBase, nCol);
111275         sqlite3WhereEnd(pWInfo);
111276         sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
111277         sortOut = sqlite3GetTempReg(pParse);
111278         sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
111279         sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
111280         VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
111281         sAggInfo.useSortingIdx = 1;
111282         sqlite3ExprCacheClear(pParse);
111283
111284       }
111285
111286       /* If the index or temporary table used by the GROUP BY sort
111287       ** will naturally deliver rows in the order required by the ORDER BY
111288       ** clause, cancel the ephemeral table open coded earlier.
111289       **
111290       ** This is an optimization - the correct answer should result regardless.
111291       ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to 
111292       ** disable this optimization for testing purposes.  */
111293       if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder) 
111294        && (groupBySort || sqlite3WhereIsSorted(pWInfo))
111295       ){
111296         sSort.pOrderBy = 0;
111297         sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
111298       }
111299
111300       /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
111301       ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
111302       ** Then compare the current GROUP BY terms against the GROUP BY terms
111303       ** from the previous row currently stored in a0, a1, a2...
111304       */
111305       addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
111306       sqlite3ExprCacheClear(pParse);
111307       if( groupBySort ){
111308         sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx, sortOut,sortPTab);
111309       }
111310       for(j=0; j<pGroupBy->nExpr; j++){
111311         if( groupBySort ){
111312           sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
111313         }else{
111314           sAggInfo.directMode = 1;
111315           sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
111316         }
111317       }
111318       sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
111319                           (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
111320       j1 = sqlite3VdbeCurrentAddr(v);
111321       sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1); VdbeCoverage(v);
111322
111323       /* Generate code that runs whenever the GROUP BY changes.
111324       ** Changes in the GROUP BY are detected by the previous code
111325       ** block.  If there were no changes, this block is skipped.
111326       **
111327       ** This code copies current group by terms in b0,b1,b2,...
111328       ** over to a0,a1,a2.  It then calls the output subroutine
111329       ** and resets the aggregate accumulator registers in preparation
111330       ** for the next GROUP BY batch.
111331       */
111332       sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
111333       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
111334       VdbeComment((v, "output one row"));
111335       sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
111336       VdbeComment((v, "check abort flag"));
111337       sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
111338       VdbeComment((v, "reset accumulator"));
111339
111340       /* Update the aggregate accumulators based on the content of
111341       ** the current row
111342       */
111343       sqlite3VdbeJumpHere(v, j1);
111344       updateAccumulator(pParse, &sAggInfo);
111345       sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
111346       VdbeComment((v, "indicate data in accumulator"));
111347
111348       /* End of the loop
111349       */
111350       if( groupBySort ){
111351         sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
111352         VdbeCoverage(v);
111353       }else{
111354         sqlite3WhereEnd(pWInfo);
111355         sqlite3VdbeChangeToNoop(v, addrSortingIdx);
111356       }
111357
111358       /* Output the final row of result
111359       */
111360       sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
111361       VdbeComment((v, "output final row"));
111362
111363       /* Jump over the subroutines
111364       */
111365       sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
111366
111367       /* Generate a subroutine that outputs a single row of the result
111368       ** set.  This subroutine first looks at the iUseFlag.  If iUseFlag
111369       ** is less than or equal to zero, the subroutine is a no-op.  If
111370       ** the processing calls for the query to abort, this subroutine
111371       ** increments the iAbortFlag memory location before returning in
111372       ** order to signal the caller to abort.
111373       */
111374       addrSetAbort = sqlite3VdbeCurrentAddr(v);
111375       sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
111376       VdbeComment((v, "set abort flag"));
111377       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
111378       sqlite3VdbeResolveLabel(v, addrOutputRow);
111379       addrOutputRow = sqlite3VdbeCurrentAddr(v);
111380       sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); VdbeCoverage(v);
111381       VdbeComment((v, "Groupby result generator entry point"));
111382       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
111383       finalizeAggFunctions(pParse, &sAggInfo);
111384       sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
111385       selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
111386                       &sDistinct, pDest,
111387                       addrOutputRow+1, addrSetAbort);
111388       sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
111389       VdbeComment((v, "end groupby result generator"));
111390
111391       /* Generate a subroutine that will reset the group-by accumulator
111392       */
111393       sqlite3VdbeResolveLabel(v, addrReset);
111394       resetAccumulator(pParse, &sAggInfo);
111395       sqlite3VdbeAddOp1(v, OP_Return, regReset);
111396      
111397     } /* endif pGroupBy.  Begin aggregate queries without GROUP BY: */
111398     else {
111399       ExprList *pDel = 0;
111400 #ifndef SQLITE_OMIT_BTREECOUNT
111401       Table *pTab;
111402       if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
111403         /* If isSimpleCount() returns a pointer to a Table structure, then
111404         ** the SQL statement is of the form:
111405         **
111406         **   SELECT count(*) FROM <tbl>
111407         **
111408         ** where the Table structure returned represents table <tbl>.
111409         **
111410         ** This statement is so common that it is optimized specially. The
111411         ** OP_Count instruction is executed either on the intkey table that
111412         ** contains the data for table <tbl> or on one of its indexes. It
111413         ** is better to execute the op on an index, as indexes are almost
111414         ** always spread across less pages than their corresponding tables.
111415         */
111416         const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
111417         const int iCsr = pParse->nTab++;     /* Cursor to scan b-tree */
111418         Index *pIdx;                         /* Iterator variable */
111419         KeyInfo *pKeyInfo = 0;               /* Keyinfo for scanned index */
111420         Index *pBest = 0;                    /* Best index found so far */
111421         int iRoot = pTab->tnum;              /* Root page of scanned b-tree */
111422
111423         sqlite3CodeVerifySchema(pParse, iDb);
111424         sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
111425
111426         /* Search for the index that has the lowest scan cost.
111427         **
111428         ** (2011-04-15) Do not do a full scan of an unordered index.
111429         **
111430         ** (2013-10-03) Do not count the entries in a partial index.
111431         **
111432         ** In practice the KeyInfo structure will not be used. It is only 
111433         ** passed to keep OP_OpenRead happy.
111434         */
111435         if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
111436         for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
111437           if( pIdx->bUnordered==0
111438            && pIdx->szIdxRow<pTab->szTabRow
111439            && pIdx->pPartIdxWhere==0
111440            && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
111441           ){
111442             pBest = pIdx;
111443           }
111444         }
111445         if( pBest ){
111446           iRoot = pBest->tnum;
111447           pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
111448         }
111449
111450         /* Open a read-only cursor, execute the OP_Count, close the cursor. */
111451         sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
111452         if( pKeyInfo ){
111453           sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
111454         }
111455         sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
111456         sqlite3VdbeAddOp1(v, OP_Close, iCsr);
111457         explainSimpleCount(pParse, pTab, pBest);
111458       }else
111459 #endif /* SQLITE_OMIT_BTREECOUNT */
111460       {
111461         /* Check if the query is of one of the following forms:
111462         **
111463         **   SELECT min(x) FROM ...
111464         **   SELECT max(x) FROM ...
111465         **
111466         ** If it is, then ask the code in where.c to attempt to sort results
111467         ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause. 
111468         ** If where.c is able to produce results sorted in this order, then
111469         ** add vdbe code to break out of the processing loop after the 
111470         ** first iteration (since the first iteration of the loop is 
111471         ** guaranteed to operate on the row with the minimum or maximum 
111472         ** value of x, the only row required).
111473         **
111474         ** A special flag must be passed to sqlite3WhereBegin() to slightly
111475         ** modify behavior as follows:
111476         **
111477         **   + If the query is a "SELECT min(x)", then the loop coded by
111478         **     where.c should not iterate over any values with a NULL value
111479         **     for x.
111480         **
111481         **   + The optimizer code in where.c (the thing that decides which
111482         **     index or indices to use) should place a different priority on 
111483         **     satisfying the 'ORDER BY' clause than it does in other cases.
111484         **     Refer to code and comments in where.c for details.
111485         */
111486         ExprList *pMinMax = 0;
111487         u8 flag = WHERE_ORDERBY_NORMAL;
111488         
111489         assert( p->pGroupBy==0 );
111490         assert( flag==0 );
111491         if( p->pHaving==0 ){
111492           flag = minMaxQuery(&sAggInfo, &pMinMax);
111493         }
111494         assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
111495
111496         if( flag ){
111497           pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
111498           pDel = pMinMax;
111499           if( pMinMax && !db->mallocFailed ){
111500             pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
111501             pMinMax->a[0].pExpr->op = TK_COLUMN;
111502           }
111503         }
111504   
111505         /* This case runs if the aggregate has no GROUP BY clause.  The
111506         ** processing is much simpler since there is only a single row
111507         ** of output.
111508         */
111509         resetAccumulator(pParse, &sAggInfo);
111510         pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
111511         if( pWInfo==0 ){
111512           sqlite3ExprListDelete(db, pDel);
111513           goto select_end;
111514         }
111515         updateAccumulator(pParse, &sAggInfo);
111516         assert( pMinMax==0 || pMinMax->nExpr==1 );
111517         if( sqlite3WhereIsOrdered(pWInfo)>0 ){
111518           sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
111519           VdbeComment((v, "%s() by index",
111520                 (flag==WHERE_ORDERBY_MIN?"min":"max")));
111521         }
111522         sqlite3WhereEnd(pWInfo);
111523         finalizeAggFunctions(pParse, &sAggInfo);
111524       }
111525
111526       sSort.pOrderBy = 0;
111527       sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
111528       selectInnerLoop(pParse, p, p->pEList, -1, 0, 0, 
111529                       pDest, addrEnd, addrEnd);
111530       sqlite3ExprListDelete(db, pDel);
111531     }
111532     sqlite3VdbeResolveLabel(v, addrEnd);
111533     
111534   } /* endif aggregate query */
111535
111536   if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
111537     explainTempTable(pParse, "DISTINCT");
111538   }
111539
111540   /* If there is an ORDER BY clause, then we need to sort the results
111541   ** and send them to the callback one by one.
111542   */
111543   if( sSort.pOrderBy ){
111544     explainTempTable(pParse, sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
111545     generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
111546   }
111547
111548   /* Jump here to skip this query
111549   */
111550   sqlite3VdbeResolveLabel(v, iEnd);
111551
111552   /* The SELECT was successfully coded.   Set the return code to 0
111553   ** to indicate no errors.
111554   */
111555   rc = 0;
111556
111557   /* Control jumps to here if an error is encountered above, or upon
111558   ** successful coding of the SELECT.
111559   */
111560 select_end:
111561   explainSetInteger(pParse->iSelectId, iRestoreSelectId);
111562
111563   /* Identify column names if results of the SELECT are to be output.
111564   */
111565   if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
111566     generateColumnNames(pParse, pTabList, pEList);
111567   }
111568
111569   sqlite3DbFree(db, sAggInfo.aCol);
111570   sqlite3DbFree(db, sAggInfo.aFunc);
111571 #if SELECTTRACE_ENABLED
111572   SELECTTRACE(1,pParse,p,("end processing\n"));
111573   pParse->nSelectIndent--;
111574 #endif
111575   return rc;
111576 }
111577
111578 #ifdef SQLITE_DEBUG
111579 /*
111580 ** Generate a human-readable description of a the Select object.
111581 */
111582 SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
111583   int n = 0;
111584   pView = sqlite3TreeViewPush(pView, moreToFollow);
111585   sqlite3TreeViewLine(pView, "SELECT%s%s (0x%p)",
111586     ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
111587     ((p->selFlags & SF_Aggregate) ? " agg_flag" : ""), p
111588   );
111589   if( p->pSrc && p->pSrc->nSrc ) n++;
111590   if( p->pWhere ) n++;
111591   if( p->pGroupBy ) n++;
111592   if( p->pHaving ) n++;
111593   if( p->pOrderBy ) n++;
111594   if( p->pLimit ) n++;
111595   if( p->pOffset ) n++;
111596   if( p->pPrior ) n++;
111597   sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
111598   if( p->pSrc && p->pSrc->nSrc ){
111599     int i;
111600     pView = sqlite3TreeViewPush(pView, (n--)>0);
111601     sqlite3TreeViewLine(pView, "FROM");
111602     for(i=0; i<p->pSrc->nSrc; i++){
111603       struct SrcList_item *pItem = &p->pSrc->a[i];
111604       StrAccum x;
111605       char zLine[100];
111606       sqlite3StrAccumInit(&x, zLine, sizeof(zLine), 0);
111607       sqlite3XPrintf(&x, 0, "{%d,*}", pItem->iCursor);
111608       if( pItem->zDatabase ){
111609         sqlite3XPrintf(&x, 0, " %s.%s", pItem->zDatabase, pItem->zName);
111610       }else if( pItem->zName ){
111611         sqlite3XPrintf(&x, 0, " %s", pItem->zName);
111612       }
111613       if( pItem->pTab ){
111614         sqlite3XPrintf(&x, 0, " tabname=%Q", pItem->pTab->zName);
111615       }
111616       if( pItem->zAlias ){
111617         sqlite3XPrintf(&x, 0, " (AS %s)", pItem->zAlias);
111618       }
111619       if( pItem->jointype & JT_LEFT ){
111620         sqlite3XPrintf(&x, 0, " LEFT-JOIN");
111621       }
111622       sqlite3StrAccumFinish(&x);
111623       sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1); 
111624       if( pItem->pSelect ){
111625         sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
111626       }
111627       sqlite3TreeViewPop(pView);
111628     }
111629     sqlite3TreeViewPop(pView);
111630   }
111631   if( p->pWhere ){
111632     sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
111633     sqlite3TreeViewExpr(pView, p->pWhere, 0);
111634     sqlite3TreeViewPop(pView);
111635   }
111636   if( p->pGroupBy ){
111637     sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
111638   }
111639   if( p->pHaving ){
111640     sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
111641     sqlite3TreeViewExpr(pView, p->pHaving, 0);
111642     sqlite3TreeViewPop(pView);
111643   }
111644   if( p->pOrderBy ){
111645     sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
111646   }
111647   if( p->pLimit ){
111648     sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
111649     sqlite3TreeViewExpr(pView, p->pLimit, 0);
111650     sqlite3TreeViewPop(pView);
111651   }
111652   if( p->pOffset ){
111653     sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
111654     sqlite3TreeViewExpr(pView, p->pOffset, 0);
111655     sqlite3TreeViewPop(pView);
111656   }
111657   if( p->pPrior ){
111658     const char *zOp = "UNION";
111659     switch( p->op ){
111660       case TK_ALL:         zOp = "UNION ALL";  break;
111661       case TK_INTERSECT:   zOp = "INTERSECT";  break;
111662       case TK_EXCEPT:      zOp = "EXCEPT";     break;
111663     }
111664     sqlite3TreeViewItem(pView, zOp, (n--)>0);
111665     sqlite3TreeViewSelect(pView, p->pPrior, 0);
111666     sqlite3TreeViewPop(pView);
111667   }
111668   sqlite3TreeViewPop(pView);
111669 }
111670 #endif /* SQLITE_DEBUG */
111671
111672 /************** End of select.c **********************************************/
111673 /************** Begin file table.c *******************************************/
111674 /*
111675 ** 2001 September 15
111676 **
111677 ** The author disclaims copyright to this source code.  In place of
111678 ** a legal notice, here is a blessing:
111679 **
111680 **    May you do good and not evil.
111681 **    May you find forgiveness for yourself and forgive others.
111682 **    May you share freely, never taking more than you give.
111683 **
111684 *************************************************************************
111685 ** This file contains the sqlite3_get_table() and sqlite3_free_table()
111686 ** interface routines.  These are just wrappers around the main
111687 ** interface routine of sqlite3_exec().
111688 **
111689 ** These routines are in a separate files so that they will not be linked
111690 ** if they are not used.
111691 */
111692 /* #include <stdlib.h> */
111693 /* #include <string.h> */
111694
111695 #ifndef SQLITE_OMIT_GET_TABLE
111696
111697 /*
111698 ** This structure is used to pass data from sqlite3_get_table() through
111699 ** to the callback function is uses to build the result.
111700 */
111701 typedef struct TabResult {
111702   char **azResult;   /* Accumulated output */
111703   char *zErrMsg;     /* Error message text, if an error occurs */
111704   u32 nAlloc;        /* Slots allocated for azResult[] */
111705   u32 nRow;          /* Number of rows in the result */
111706   u32 nColumn;       /* Number of columns in the result */
111707   u32 nData;         /* Slots used in azResult[].  (nRow+1)*nColumn */
111708   int rc;            /* Return code from sqlite3_exec() */
111709 } TabResult;
111710
111711 /*
111712 ** This routine is called once for each row in the result table.  Its job
111713 ** is to fill in the TabResult structure appropriately, allocating new
111714 ** memory as necessary.
111715 */
111716 static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
111717   TabResult *p = (TabResult*)pArg;  /* Result accumulator */
111718   int need;                         /* Slots needed in p->azResult[] */
111719   int i;                            /* Loop counter */
111720   char *z;                          /* A single column of result */
111721
111722   /* Make sure there is enough space in p->azResult to hold everything
111723   ** we need to remember from this invocation of the callback.
111724   */
111725   if( p->nRow==0 && argv!=0 ){
111726     need = nCol*2;
111727   }else{
111728     need = nCol;
111729   }
111730   if( p->nData + need > p->nAlloc ){
111731     char **azNew;
111732     p->nAlloc = p->nAlloc*2 + need;
111733     azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
111734     if( azNew==0 ) goto malloc_failed;
111735     p->azResult = azNew;
111736   }
111737
111738   /* If this is the first row, then generate an extra row containing
111739   ** the names of all columns.
111740   */
111741   if( p->nRow==0 ){
111742     p->nColumn = nCol;
111743     for(i=0; i<nCol; i++){
111744       z = sqlite3_mprintf("%s", colv[i]);
111745       if( z==0 ) goto malloc_failed;
111746       p->azResult[p->nData++] = z;
111747     }
111748   }else if( (int)p->nColumn!=nCol ){
111749     sqlite3_free(p->zErrMsg);
111750     p->zErrMsg = sqlite3_mprintf(
111751        "sqlite3_get_table() called with two or more incompatible queries"
111752     );
111753     p->rc = SQLITE_ERROR;
111754     return 1;
111755   }
111756
111757   /* Copy over the row data
111758   */
111759   if( argv!=0 ){
111760     for(i=0; i<nCol; i++){
111761       if( argv[i]==0 ){
111762         z = 0;
111763       }else{
111764         int n = sqlite3Strlen30(argv[i])+1;
111765         z = sqlite3_malloc( n );
111766         if( z==0 ) goto malloc_failed;
111767         memcpy(z, argv[i], n);
111768       }
111769       p->azResult[p->nData++] = z;
111770     }
111771     p->nRow++;
111772   }
111773   return 0;
111774
111775 malloc_failed:
111776   p->rc = SQLITE_NOMEM;
111777   return 1;
111778 }
111779
111780 /*
111781 ** Query the database.  But instead of invoking a callback for each row,
111782 ** malloc() for space to hold the result and return the entire results
111783 ** at the conclusion of the call.
111784 **
111785 ** The result that is written to ***pazResult is held in memory obtained
111786 ** from malloc().  But the caller cannot free this memory directly.  
111787 ** Instead, the entire table should be passed to sqlite3_free_table() when
111788 ** the calling procedure is finished using it.
111789 */
111790 SQLITE_API int SQLITE_STDCALL sqlite3_get_table(
111791   sqlite3 *db,                /* The database on which the SQL executes */
111792   const char *zSql,           /* The SQL to be executed */
111793   char ***pazResult,          /* Write the result table here */
111794   int *pnRow,                 /* Write the number of rows in the result here */
111795   int *pnColumn,              /* Write the number of columns of result here */
111796   char **pzErrMsg             /* Write error messages here */
111797 ){
111798   int rc;
111799   TabResult res;
111800
111801 #ifdef SQLITE_ENABLE_API_ARMOR
111802   if( !sqlite3SafetyCheckOk(db) || pazResult==0 ) return SQLITE_MISUSE_BKPT;
111803 #endif
111804   *pazResult = 0;
111805   if( pnColumn ) *pnColumn = 0;
111806   if( pnRow ) *pnRow = 0;
111807   if( pzErrMsg ) *pzErrMsg = 0;
111808   res.zErrMsg = 0;
111809   res.nRow = 0;
111810   res.nColumn = 0;
111811   res.nData = 1;
111812   res.nAlloc = 20;
111813   res.rc = SQLITE_OK;
111814   res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
111815   if( res.azResult==0 ){
111816      db->errCode = SQLITE_NOMEM;
111817      return SQLITE_NOMEM;
111818   }
111819   res.azResult[0] = 0;
111820   rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
111821   assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
111822   res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
111823   if( (rc&0xff)==SQLITE_ABORT ){
111824     sqlite3_free_table(&res.azResult[1]);
111825     if( res.zErrMsg ){
111826       if( pzErrMsg ){
111827         sqlite3_free(*pzErrMsg);
111828         *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
111829       }
111830       sqlite3_free(res.zErrMsg);
111831     }
111832     db->errCode = res.rc;  /* Assume 32-bit assignment is atomic */
111833     return res.rc;
111834   }
111835   sqlite3_free(res.zErrMsg);
111836   if( rc!=SQLITE_OK ){
111837     sqlite3_free_table(&res.azResult[1]);
111838     return rc;
111839   }
111840   if( res.nAlloc>res.nData ){
111841     char **azNew;
111842     azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
111843     if( azNew==0 ){
111844       sqlite3_free_table(&res.azResult[1]);
111845       db->errCode = SQLITE_NOMEM;
111846       return SQLITE_NOMEM;
111847     }
111848     res.azResult = azNew;
111849   }
111850   *pazResult = &res.azResult[1];
111851   if( pnColumn ) *pnColumn = res.nColumn;
111852   if( pnRow ) *pnRow = res.nRow;
111853   return rc;
111854 }
111855
111856 /*
111857 ** This routine frees the space the sqlite3_get_table() malloced.
111858 */
111859 SQLITE_API void SQLITE_STDCALL sqlite3_free_table(
111860   char **azResult            /* Result returned from sqlite3_get_table() */
111861 ){
111862   if( azResult ){
111863     int i, n;
111864     azResult--;
111865     assert( azResult!=0 );
111866     n = SQLITE_PTR_TO_INT(azResult[0]);
111867     for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
111868     sqlite3_free(azResult);
111869   }
111870 }
111871
111872 #endif /* SQLITE_OMIT_GET_TABLE */
111873
111874 /************** End of table.c ***********************************************/
111875 /************** Begin file trigger.c *****************************************/
111876 /*
111877 **
111878 ** The author disclaims copyright to this source code.  In place of
111879 ** a legal notice, here is a blessing:
111880 **
111881 **    May you do good and not evil.
111882 **    May you find forgiveness for yourself and forgive others.
111883 **    May you share freely, never taking more than you give.
111884 **
111885 *************************************************************************
111886 ** This file contains the implementation for TRIGGERs
111887 */
111888
111889 #ifndef SQLITE_OMIT_TRIGGER
111890 /*
111891 ** Delete a linked list of TriggerStep structures.
111892 */
111893 SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
111894   while( pTriggerStep ){
111895     TriggerStep * pTmp = pTriggerStep;
111896     pTriggerStep = pTriggerStep->pNext;
111897
111898     sqlite3ExprDelete(db, pTmp->pWhere);
111899     sqlite3ExprListDelete(db, pTmp->pExprList);
111900     sqlite3SelectDelete(db, pTmp->pSelect);
111901     sqlite3IdListDelete(db, pTmp->pIdList);
111902
111903     sqlite3DbFree(db, pTmp);
111904   }
111905 }
111906
111907 /*
111908 ** Given table pTab, return a list of all the triggers attached to 
111909 ** the table. The list is connected by Trigger.pNext pointers.
111910 **
111911 ** All of the triggers on pTab that are in the same database as pTab
111912 ** are already attached to pTab->pTrigger.  But there might be additional
111913 ** triggers on pTab in the TEMP schema.  This routine prepends all
111914 ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
111915 ** and returns the combined list.
111916 **
111917 ** To state it another way:  This routine returns a list of all triggers
111918 ** that fire off of pTab.  The list will include any TEMP triggers on
111919 ** pTab as well as the triggers lised in pTab->pTrigger.
111920 */
111921 SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
111922   Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
111923   Trigger *pList = 0;                  /* List of triggers to return */
111924
111925   if( pParse->disableTriggers ){
111926     return 0;
111927   }
111928
111929   if( pTmpSchema!=pTab->pSchema ){
111930     HashElem *p;
111931     assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
111932     for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
111933       Trigger *pTrig = (Trigger *)sqliteHashData(p);
111934       if( pTrig->pTabSchema==pTab->pSchema
111935        && 0==sqlite3StrICmp(pTrig->table, pTab->zName) 
111936       ){
111937         pTrig->pNext = (pList ? pList : pTab->pTrigger);
111938         pList = pTrig;
111939       }
111940     }
111941   }
111942
111943   return (pList ? pList : pTab->pTrigger);
111944 }
111945
111946 /*
111947 ** This is called by the parser when it sees a CREATE TRIGGER statement
111948 ** up to the point of the BEGIN before the trigger actions.  A Trigger
111949 ** structure is generated based on the information available and stored
111950 ** in pParse->pNewTrigger.  After the trigger actions have been parsed, the
111951 ** sqlite3FinishTrigger() function is called to complete the trigger
111952 ** construction process.
111953 */
111954 SQLITE_PRIVATE void sqlite3BeginTrigger(
111955   Parse *pParse,      /* The parse context of the CREATE TRIGGER statement */
111956   Token *pName1,      /* The name of the trigger */
111957   Token *pName2,      /* The name of the trigger */
111958   int tr_tm,          /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
111959   int op,             /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
111960   IdList *pColumns,   /* column list if this is an UPDATE OF trigger */
111961   SrcList *pTableName,/* The name of the table/view the trigger applies to */
111962   Expr *pWhen,        /* WHEN clause */
111963   int isTemp,         /* True if the TEMPORARY keyword is present */
111964   int noErr           /* Suppress errors if the trigger already exists */
111965 ){
111966   Trigger *pTrigger = 0;  /* The new trigger */
111967   Table *pTab;            /* Table that the trigger fires off of */
111968   char *zName = 0;        /* Name of the trigger */
111969   sqlite3 *db = pParse->db;  /* The database connection */
111970   int iDb;                /* The database to store the trigger in */
111971   Token *pName;           /* The unqualified db name */
111972   DbFixer sFix;           /* State vector for the DB fixer */
111973   int iTabDb;             /* Index of the database holding pTab */
111974
111975   assert( pName1!=0 );   /* pName1->z might be NULL, but not pName1 itself */
111976   assert( pName2!=0 );
111977   assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
111978   assert( op>0 && op<0xff );
111979   if( isTemp ){
111980     /* If TEMP was specified, then the trigger name may not be qualified. */
111981     if( pName2->n>0 ){
111982       sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
111983       goto trigger_cleanup;
111984     }
111985     iDb = 1;
111986     pName = pName1;
111987   }else{
111988     /* Figure out the db that the trigger will be created in */
111989     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
111990     if( iDb<0 ){
111991       goto trigger_cleanup;
111992     }
111993   }
111994   if( !pTableName || db->mallocFailed ){
111995     goto trigger_cleanup;
111996   }
111997
111998   /* A long-standing parser bug is that this syntax was allowed:
111999   **
112000   **    CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
112001   **                                                 ^^^^^^^^
112002   **
112003   ** To maintain backwards compatibility, ignore the database
112004   ** name on pTableName if we are reparsing out of SQLITE_MASTER.
112005   */
112006   if( db->init.busy && iDb!=1 ){
112007     sqlite3DbFree(db, pTableName->a[0].zDatabase);
112008     pTableName->a[0].zDatabase = 0;
112009   }
112010
112011   /* If the trigger name was unqualified, and the table is a temp table,
112012   ** then set iDb to 1 to create the trigger in the temporary database.
112013   ** If sqlite3SrcListLookup() returns 0, indicating the table does not
112014   ** exist, the error is caught by the block below.
112015   */
112016   pTab = sqlite3SrcListLookup(pParse, pTableName);
112017   if( db->init.busy==0 && pName2->n==0 && pTab
112018         && pTab->pSchema==db->aDb[1].pSchema ){
112019     iDb = 1;
112020   }
112021
112022   /* Ensure the table name matches database name and that the table exists */
112023   if( db->mallocFailed ) goto trigger_cleanup;
112024   assert( pTableName->nSrc==1 );
112025   sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
112026   if( sqlite3FixSrcList(&sFix, pTableName) ){
112027     goto trigger_cleanup;
112028   }
112029   pTab = sqlite3SrcListLookup(pParse, pTableName);
112030   if( !pTab ){
112031     /* The table does not exist. */
112032     if( db->init.iDb==1 ){
112033       /* Ticket #3810.
112034       ** Normally, whenever a table is dropped, all associated triggers are
112035       ** dropped too.  But if a TEMP trigger is created on a non-TEMP table
112036       ** and the table is dropped by a different database connection, the
112037       ** trigger is not visible to the database connection that does the
112038       ** drop so the trigger cannot be dropped.  This results in an
112039       ** "orphaned trigger" - a trigger whose associated table is missing.
112040       */
112041       db->init.orphanTrigger = 1;
112042     }
112043     goto trigger_cleanup;
112044   }
112045   if( IsVirtual(pTab) ){
112046     sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
112047     goto trigger_cleanup;
112048   }
112049
112050   /* Check that the trigger name is not reserved and that no trigger of the
112051   ** specified name exists */
112052   zName = sqlite3NameFromToken(db, pName);
112053   if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
112054     goto trigger_cleanup;
112055   }
112056   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
112057   if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
112058     if( !noErr ){
112059       sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
112060     }else{
112061       assert( !db->init.busy );
112062       sqlite3CodeVerifySchema(pParse, iDb);
112063     }
112064     goto trigger_cleanup;
112065   }
112066
112067   /* Do not create a trigger on a system table */
112068   if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
112069     sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
112070     pParse->nErr++;
112071     goto trigger_cleanup;
112072   }
112073
112074   /* INSTEAD of triggers are only for views and views only support INSTEAD
112075   ** of triggers.
112076   */
112077   if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
112078     sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S", 
112079         (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
112080     goto trigger_cleanup;
112081   }
112082   if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
112083     sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
112084         " trigger on table: %S", pTableName, 0);
112085     goto trigger_cleanup;
112086   }
112087   iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
112088
112089 #ifndef SQLITE_OMIT_AUTHORIZATION
112090   {
112091     int code = SQLITE_CREATE_TRIGGER;
112092     const char *zDb = db->aDb[iTabDb].zName;
112093     const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
112094     if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
112095     if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
112096       goto trigger_cleanup;
112097     }
112098     if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
112099       goto trigger_cleanup;
112100     }
112101   }
112102 #endif
112103
112104   /* INSTEAD OF triggers can only appear on views and BEFORE triggers
112105   ** cannot appear on views.  So we might as well translate every
112106   ** INSTEAD OF trigger into a BEFORE trigger.  It simplifies code
112107   ** elsewhere.
112108   */
112109   if (tr_tm == TK_INSTEAD){
112110     tr_tm = TK_BEFORE;
112111   }
112112
112113   /* Build the Trigger object */
112114   pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
112115   if( pTrigger==0 ) goto trigger_cleanup;
112116   pTrigger->zName = zName;
112117   zName = 0;
112118   pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
112119   pTrigger->pSchema = db->aDb[iDb].pSchema;
112120   pTrigger->pTabSchema = pTab->pSchema;
112121   pTrigger->op = (u8)op;
112122   pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
112123   pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
112124   pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
112125   assert( pParse->pNewTrigger==0 );
112126   pParse->pNewTrigger = pTrigger;
112127
112128 trigger_cleanup:
112129   sqlite3DbFree(db, zName);
112130   sqlite3SrcListDelete(db, pTableName);
112131   sqlite3IdListDelete(db, pColumns);
112132   sqlite3ExprDelete(db, pWhen);
112133   if( !pParse->pNewTrigger ){
112134     sqlite3DeleteTrigger(db, pTrigger);
112135   }else{
112136     assert( pParse->pNewTrigger==pTrigger );
112137   }
112138 }
112139
112140 /*
112141 ** This routine is called after all of the trigger actions have been parsed
112142 ** in order to complete the process of building the trigger.
112143 */
112144 SQLITE_PRIVATE void sqlite3FinishTrigger(
112145   Parse *pParse,          /* Parser context */
112146   TriggerStep *pStepList, /* The triggered program */
112147   Token *pAll             /* Token that describes the complete CREATE TRIGGER */
112148 ){
112149   Trigger *pTrig = pParse->pNewTrigger;   /* Trigger being finished */
112150   char *zName;                            /* Name of trigger */
112151   sqlite3 *db = pParse->db;               /* The database */
112152   DbFixer sFix;                           /* Fixer object */
112153   int iDb;                                /* Database containing the trigger */
112154   Token nameToken;                        /* Trigger name for error reporting */
112155
112156   pParse->pNewTrigger = 0;
112157   if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
112158   zName = pTrig->zName;
112159   iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
112160   pTrig->step_list = pStepList;
112161   while( pStepList ){
112162     pStepList->pTrig = pTrig;
112163     pStepList = pStepList->pNext;
112164   }
112165   nameToken.z = pTrig->zName;
112166   nameToken.n = sqlite3Strlen30(nameToken.z);
112167   sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
112168   if( sqlite3FixTriggerStep(&sFix, pTrig->step_list) 
112169    || sqlite3FixExpr(&sFix, pTrig->pWhen) 
112170   ){
112171     goto triggerfinish_cleanup;
112172   }
112173
112174   /* if we are not initializing,
112175   ** build the sqlite_master entry
112176   */
112177   if( !db->init.busy ){
112178     Vdbe *v;
112179     char *z;
112180
112181     /* Make an entry in the sqlite_master table */
112182     v = sqlite3GetVdbe(pParse);
112183     if( v==0 ) goto triggerfinish_cleanup;
112184     sqlite3BeginWriteOperation(pParse, 0, iDb);
112185     z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
112186     sqlite3NestedParse(pParse,
112187        "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
112188        db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
112189        pTrig->table, z);
112190     sqlite3DbFree(db, z);
112191     sqlite3ChangeCookie(pParse, iDb);
112192     sqlite3VdbeAddParseSchemaOp(v, iDb,
112193         sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
112194   }
112195
112196   if( db->init.busy ){
112197     Trigger *pLink = pTrig;
112198     Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
112199     assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
112200     pTrig = sqlite3HashInsert(pHash, zName, pTrig);
112201     if( pTrig ){
112202       db->mallocFailed = 1;
112203     }else if( pLink->pSchema==pLink->pTabSchema ){
112204       Table *pTab;
112205       pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
112206       assert( pTab!=0 );
112207       pLink->pNext = pTab->pTrigger;
112208       pTab->pTrigger = pLink;
112209     }
112210   }
112211
112212 triggerfinish_cleanup:
112213   sqlite3DeleteTrigger(db, pTrig);
112214   assert( !pParse->pNewTrigger );
112215   sqlite3DeleteTriggerStep(db, pStepList);
112216 }
112217
112218 /*
112219 ** Turn a SELECT statement (that the pSelect parameter points to) into
112220 ** a trigger step.  Return a pointer to a TriggerStep structure.
112221 **
112222 ** The parser calls this routine when it finds a SELECT statement in
112223 ** body of a TRIGGER.  
112224 */
112225 SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
112226   TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
112227   if( pTriggerStep==0 ) {
112228     sqlite3SelectDelete(db, pSelect);
112229     return 0;
112230   }
112231   pTriggerStep->op = TK_SELECT;
112232   pTriggerStep->pSelect = pSelect;
112233   pTriggerStep->orconf = OE_Default;
112234   return pTriggerStep;
112235 }
112236
112237 /*
112238 ** Allocate space to hold a new trigger step.  The allocated space
112239 ** holds both the TriggerStep object and the TriggerStep.target.z string.
112240 **
112241 ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
112242 */
112243 static TriggerStep *triggerStepAllocate(
112244   sqlite3 *db,                /* Database connection */
112245   u8 op,                      /* Trigger opcode */
112246   Token *pName                /* The target name */
112247 ){
112248   TriggerStep *pTriggerStep;
112249
112250   pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
112251   if( pTriggerStep ){
112252     char *z = (char*)&pTriggerStep[1];
112253     memcpy(z, pName->z, pName->n);
112254     pTriggerStep->target.z = z;
112255     pTriggerStep->target.n = pName->n;
112256     pTriggerStep->op = op;
112257   }
112258   return pTriggerStep;
112259 }
112260
112261 /*
112262 ** Build a trigger step out of an INSERT statement.  Return a pointer
112263 ** to the new trigger step.
112264 **
112265 ** The parser calls this routine when it sees an INSERT inside the
112266 ** body of a trigger.
112267 */
112268 SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
112269   sqlite3 *db,        /* The database connection */
112270   Token *pTableName,  /* Name of the table into which we insert */
112271   IdList *pColumn,    /* List of columns in pTableName to insert into */
112272   Select *pSelect,    /* A SELECT statement that supplies values */
112273   u8 orconf           /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
112274 ){
112275   TriggerStep *pTriggerStep;
112276
112277   assert(pSelect != 0 || db->mallocFailed);
112278
112279   pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
112280   if( pTriggerStep ){
112281     pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
112282     pTriggerStep->pIdList = pColumn;
112283     pTriggerStep->orconf = orconf;
112284   }else{
112285     sqlite3IdListDelete(db, pColumn);
112286   }
112287   sqlite3SelectDelete(db, pSelect);
112288
112289   return pTriggerStep;
112290 }
112291
112292 /*
112293 ** Construct a trigger step that implements an UPDATE statement and return
112294 ** a pointer to that trigger step.  The parser calls this routine when it
112295 ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
112296 */
112297 SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
112298   sqlite3 *db,         /* The database connection */
112299   Token *pTableName,   /* Name of the table to be updated */
112300   ExprList *pEList,    /* The SET clause: list of column and new values */
112301   Expr *pWhere,        /* The WHERE clause */
112302   u8 orconf            /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
112303 ){
112304   TriggerStep *pTriggerStep;
112305
112306   pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
112307   if( pTriggerStep ){
112308     pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
112309     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
112310     pTriggerStep->orconf = orconf;
112311   }
112312   sqlite3ExprListDelete(db, pEList);
112313   sqlite3ExprDelete(db, pWhere);
112314   return pTriggerStep;
112315 }
112316
112317 /*
112318 ** Construct a trigger step that implements a DELETE statement and return
112319 ** a pointer to that trigger step.  The parser calls this routine when it
112320 ** sees a DELETE statement inside the body of a CREATE TRIGGER.
112321 */
112322 SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
112323   sqlite3 *db,            /* Database connection */
112324   Token *pTableName,      /* The table from which rows are deleted */
112325   Expr *pWhere            /* The WHERE clause */
112326 ){
112327   TriggerStep *pTriggerStep;
112328
112329   pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
112330   if( pTriggerStep ){
112331     pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
112332     pTriggerStep->orconf = OE_Default;
112333   }
112334   sqlite3ExprDelete(db, pWhere);
112335   return pTriggerStep;
112336 }
112337
112338 /* 
112339 ** Recursively delete a Trigger structure
112340 */
112341 SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
112342   if( pTrigger==0 ) return;
112343   sqlite3DeleteTriggerStep(db, pTrigger->step_list);
112344   sqlite3DbFree(db, pTrigger->zName);
112345   sqlite3DbFree(db, pTrigger->table);
112346   sqlite3ExprDelete(db, pTrigger->pWhen);
112347   sqlite3IdListDelete(db, pTrigger->pColumns);
112348   sqlite3DbFree(db, pTrigger);
112349 }
112350
112351 /*
112352 ** This function is called to drop a trigger from the database schema. 
112353 **
112354 ** This may be called directly from the parser and therefore identifies
112355 ** the trigger by name.  The sqlite3DropTriggerPtr() routine does the
112356 ** same job as this routine except it takes a pointer to the trigger
112357 ** instead of the trigger name.
112358 **/
112359 SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
112360   Trigger *pTrigger = 0;
112361   int i;
112362   const char *zDb;
112363   const char *zName;
112364   sqlite3 *db = pParse->db;
112365
112366   if( db->mallocFailed ) goto drop_trigger_cleanup;
112367   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
112368     goto drop_trigger_cleanup;
112369   }
112370
112371   assert( pName->nSrc==1 );
112372   zDb = pName->a[0].zDatabase;
112373   zName = pName->a[0].zName;
112374   assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
112375   for(i=OMIT_TEMPDB; i<db->nDb; i++){
112376     int j = (i<2) ? i^1 : i;  /* Search TEMP before MAIN */
112377     if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
112378     assert( sqlite3SchemaMutexHeld(db, j, 0) );
112379     pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
112380     if( pTrigger ) break;
112381   }
112382   if( !pTrigger ){
112383     if( !noErr ){
112384       sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
112385     }else{
112386       sqlite3CodeVerifyNamedSchema(pParse, zDb);
112387     }
112388     pParse->checkSchema = 1;
112389     goto drop_trigger_cleanup;
112390   }
112391   sqlite3DropTriggerPtr(pParse, pTrigger);
112392
112393 drop_trigger_cleanup:
112394   sqlite3SrcListDelete(db, pName);
112395 }
112396
112397 /*
112398 ** Return a pointer to the Table structure for the table that a trigger
112399 ** is set on.
112400 */
112401 static Table *tableOfTrigger(Trigger *pTrigger){
112402   return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
112403 }
112404
112405
112406 /*
112407 ** Drop a trigger given a pointer to that trigger. 
112408 */
112409 SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
112410   Table   *pTable;
112411   Vdbe *v;
112412   sqlite3 *db = pParse->db;
112413   int iDb;
112414
112415   iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
112416   assert( iDb>=0 && iDb<db->nDb );
112417   pTable = tableOfTrigger(pTrigger);
112418   assert( pTable );
112419   assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
112420 #ifndef SQLITE_OMIT_AUTHORIZATION
112421   {
112422     int code = SQLITE_DROP_TRIGGER;
112423     const char *zDb = db->aDb[iDb].zName;
112424     const char *zTab = SCHEMA_TABLE(iDb);
112425     if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
112426     if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
112427       sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
112428       return;
112429     }
112430   }
112431 #endif
112432
112433   /* Generate code to destroy the database record of the trigger.
112434   */
112435   assert( pTable!=0 );
112436   if( (v = sqlite3GetVdbe(pParse))!=0 ){
112437     int base;
112438     static const int iLn = VDBE_OFFSET_LINENO(2);
112439     static const VdbeOpList dropTrigger[] = {
112440       { OP_Rewind,     0, ADDR(9),  0},
112441       { OP_String8,    0, 1,        0}, /* 1 */
112442       { OP_Column,     0, 1,        2},
112443       { OP_Ne,         2, ADDR(8),  1},
112444       { OP_String8,    0, 1,        0}, /* 4: "trigger" */
112445       { OP_Column,     0, 0,        2},
112446       { OP_Ne,         2, ADDR(8),  1},
112447       { OP_Delete,     0, 0,        0},
112448       { OP_Next,       0, ADDR(1),  0}, /* 8 */
112449     };
112450
112451     sqlite3BeginWriteOperation(pParse, 0, iDb);
112452     sqlite3OpenMasterTable(pParse, iDb);
112453     base = sqlite3VdbeAddOpList(v,  ArraySize(dropTrigger), dropTrigger, iLn);
112454     sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
112455     sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
112456     sqlite3ChangeCookie(pParse, iDb);
112457     sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
112458     sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
112459     if( pParse->nMem<3 ){
112460       pParse->nMem = 3;
112461     }
112462   }
112463 }
112464
112465 /*
112466 ** Remove a trigger from the hash tables of the sqlite* pointer.
112467 */
112468 SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
112469   Trigger *pTrigger;
112470   Hash *pHash;
112471
112472   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
112473   pHash = &(db->aDb[iDb].pSchema->trigHash);
112474   pTrigger = sqlite3HashInsert(pHash, zName, 0);
112475   if( ALWAYS(pTrigger) ){
112476     if( pTrigger->pSchema==pTrigger->pTabSchema ){
112477       Table *pTab = tableOfTrigger(pTrigger);
112478       Trigger **pp;
112479       for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
112480       *pp = (*pp)->pNext;
112481     }
112482     sqlite3DeleteTrigger(db, pTrigger);
112483     db->flags |= SQLITE_InternChanges;
112484   }
112485 }
112486
112487 /*
112488 ** pEList is the SET clause of an UPDATE statement.  Each entry
112489 ** in pEList is of the format <id>=<expr>.  If any of the entries
112490 ** in pEList have an <id> which matches an identifier in pIdList,
112491 ** then return TRUE.  If pIdList==NULL, then it is considered a
112492 ** wildcard that matches anything.  Likewise if pEList==NULL then
112493 ** it matches anything so always return true.  Return false only
112494 ** if there is no match.
112495 */
112496 static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
112497   int e;
112498   if( pIdList==0 || NEVER(pEList==0) ) return 1;
112499   for(e=0; e<pEList->nExpr; e++){
112500     if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
112501   }
112502   return 0; 
112503 }
112504
112505 /*
112506 ** Return a list of all triggers on table pTab if there exists at least
112507 ** one trigger that must be fired when an operation of type 'op' is 
112508 ** performed on the table, and, if that operation is an UPDATE, if at
112509 ** least one of the columns in pChanges is being modified.
112510 */
112511 SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
112512   Parse *pParse,          /* Parse context */
112513   Table *pTab,            /* The table the contains the triggers */
112514   int op,                 /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
112515   ExprList *pChanges,     /* Columns that change in an UPDATE statement */
112516   int *pMask              /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
112517 ){
112518   int mask = 0;
112519   Trigger *pList = 0;
112520   Trigger *p;
112521
112522   if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
112523     pList = sqlite3TriggerList(pParse, pTab);
112524   }
112525   assert( pList==0 || IsVirtual(pTab)==0 );
112526   for(p=pList; p; p=p->pNext){
112527     if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
112528       mask |= p->tr_tm;
112529     }
112530   }
112531   if( pMask ){
112532     *pMask = mask;
112533   }
112534   return (mask ? pList : 0);
112535 }
112536
112537 /*
112538 ** Convert the pStep->target token into a SrcList and return a pointer
112539 ** to that SrcList.
112540 **
112541 ** This routine adds a specific database name, if needed, to the target when
112542 ** forming the SrcList.  This prevents a trigger in one database from
112543 ** referring to a target in another database.  An exception is when the
112544 ** trigger is in TEMP in which case it can refer to any other database it
112545 ** wants.
112546 */
112547 static SrcList *targetSrcList(
112548   Parse *pParse,       /* The parsing context */
112549   TriggerStep *pStep   /* The trigger containing the target token */
112550 ){
112551   int iDb;             /* Index of the database to use */
112552   SrcList *pSrc;       /* SrcList to be returned */
112553
112554   pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
112555   if( pSrc ){
112556     assert( pSrc->nSrc>0 );
112557     assert( pSrc->a!=0 );
112558     iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
112559     if( iDb==0 || iDb>=2 ){
112560       sqlite3 *db = pParse->db;
112561       assert( iDb<pParse->db->nDb );
112562       pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
112563     }
112564   }
112565   return pSrc;
112566 }
112567
112568 /*
112569 ** Generate VDBE code for the statements inside the body of a single 
112570 ** trigger.
112571 */
112572 static int codeTriggerProgram(
112573   Parse *pParse,            /* The parser context */
112574   TriggerStep *pStepList,   /* List of statements inside the trigger body */
112575   int orconf                /* Conflict algorithm. (OE_Abort, etc) */  
112576 ){
112577   TriggerStep *pStep;
112578   Vdbe *v = pParse->pVdbe;
112579   sqlite3 *db = pParse->db;
112580
112581   assert( pParse->pTriggerTab && pParse->pToplevel );
112582   assert( pStepList );
112583   assert( v!=0 );
112584   for(pStep=pStepList; pStep; pStep=pStep->pNext){
112585     /* Figure out the ON CONFLICT policy that will be used for this step
112586     ** of the trigger program. If the statement that caused this trigger
112587     ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
112588     ** the ON CONFLICT policy that was specified as part of the trigger
112589     ** step statement. Example:
112590     **
112591     **   CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
112592     **     INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
112593     **   END;
112594     **
112595     **   INSERT INTO t1 ... ;            -- insert into t2 uses REPLACE policy
112596     **   INSERT OR IGNORE INTO t1 ... ;  -- insert into t2 uses IGNORE policy
112597     */
112598     pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
112599     assert( pParse->okConstFactor==0 );
112600
112601     switch( pStep->op ){
112602       case TK_UPDATE: {
112603         sqlite3Update(pParse, 
112604           targetSrcList(pParse, pStep),
112605           sqlite3ExprListDup(db, pStep->pExprList, 0), 
112606           sqlite3ExprDup(db, pStep->pWhere, 0), 
112607           pParse->eOrconf
112608         );
112609         break;
112610       }
112611       case TK_INSERT: {
112612         sqlite3Insert(pParse, 
112613           targetSrcList(pParse, pStep),
112614           sqlite3SelectDup(db, pStep->pSelect, 0), 
112615           sqlite3IdListDup(db, pStep->pIdList), 
112616           pParse->eOrconf
112617         );
112618         break;
112619       }
112620       case TK_DELETE: {
112621         sqlite3DeleteFrom(pParse, 
112622           targetSrcList(pParse, pStep),
112623           sqlite3ExprDup(db, pStep->pWhere, 0)
112624         );
112625         break;
112626       }
112627       default: assert( pStep->op==TK_SELECT ); {
112628         SelectDest sDest;
112629         Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
112630         sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
112631         sqlite3Select(pParse, pSelect, &sDest);
112632         sqlite3SelectDelete(db, pSelect);
112633         break;
112634       }
112635     } 
112636     if( pStep->op!=TK_SELECT ){
112637       sqlite3VdbeAddOp0(v, OP_ResetCount);
112638     }
112639   }
112640
112641   return 0;
112642 }
112643
112644 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
112645 /*
112646 ** This function is used to add VdbeComment() annotations to a VDBE
112647 ** program. It is not used in production code, only for debugging.
112648 */
112649 static const char *onErrorText(int onError){
112650   switch( onError ){
112651     case OE_Abort:    return "abort";
112652     case OE_Rollback: return "rollback";
112653     case OE_Fail:     return "fail";
112654     case OE_Replace:  return "replace";
112655     case OE_Ignore:   return "ignore";
112656     case OE_Default:  return "default";
112657   }
112658   return "n/a";
112659 }
112660 #endif
112661
112662 /*
112663 ** Parse context structure pFrom has just been used to create a sub-vdbe
112664 ** (trigger program). If an error has occurred, transfer error information
112665 ** from pFrom to pTo.
112666 */
112667 static void transferParseError(Parse *pTo, Parse *pFrom){
112668   assert( pFrom->zErrMsg==0 || pFrom->nErr );
112669   assert( pTo->zErrMsg==0 || pTo->nErr );
112670   if( pTo->nErr==0 ){
112671     pTo->zErrMsg = pFrom->zErrMsg;
112672     pTo->nErr = pFrom->nErr;
112673   }else{
112674     sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
112675   }
112676 }
112677
112678 /*
112679 ** Create and populate a new TriggerPrg object with a sub-program 
112680 ** implementing trigger pTrigger with ON CONFLICT policy orconf.
112681 */
112682 static TriggerPrg *codeRowTrigger(
112683   Parse *pParse,       /* Current parse context */
112684   Trigger *pTrigger,   /* Trigger to code */
112685   Table *pTab,         /* The table pTrigger is attached to */
112686   int orconf           /* ON CONFLICT policy to code trigger program with */
112687 ){
112688   Parse *pTop = sqlite3ParseToplevel(pParse);
112689   sqlite3 *db = pParse->db;   /* Database handle */
112690   TriggerPrg *pPrg;           /* Value to return */
112691   Expr *pWhen = 0;            /* Duplicate of trigger WHEN expression */
112692   Vdbe *v;                    /* Temporary VM */
112693   NameContext sNC;            /* Name context for sub-vdbe */
112694   SubProgram *pProgram = 0;   /* Sub-vdbe for trigger program */
112695   Parse *pSubParse;           /* Parse context for sub-vdbe */
112696   int iEndTrigger = 0;        /* Label to jump to if WHEN is false */
112697
112698   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
112699   assert( pTop->pVdbe );
112700
112701   /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
112702   ** are freed if an error occurs, link them into the Parse.pTriggerPrg 
112703   ** list of the top-level Parse object sooner rather than later.  */
112704   pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
112705   if( !pPrg ) return 0;
112706   pPrg->pNext = pTop->pTriggerPrg;
112707   pTop->pTriggerPrg = pPrg;
112708   pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
112709   if( !pProgram ) return 0;
112710   sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
112711   pPrg->pTrigger = pTrigger;
112712   pPrg->orconf = orconf;
112713   pPrg->aColmask[0] = 0xffffffff;
112714   pPrg->aColmask[1] = 0xffffffff;
112715
112716   /* Allocate and populate a new Parse context to use for coding the 
112717   ** trigger sub-program.  */
112718   pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
112719   if( !pSubParse ) return 0;
112720   memset(&sNC, 0, sizeof(sNC));
112721   sNC.pParse = pSubParse;
112722   pSubParse->db = db;
112723   pSubParse->pTriggerTab = pTab;
112724   pSubParse->pToplevel = pTop;
112725   pSubParse->zAuthContext = pTrigger->zName;
112726   pSubParse->eTriggerOp = pTrigger->op;
112727   pSubParse->nQueryLoop = pParse->nQueryLoop;
112728
112729   v = sqlite3GetVdbe(pSubParse);
112730   if( v ){
112731     VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)", 
112732       pTrigger->zName, onErrorText(orconf),
112733       (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
112734         (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
112735         (pTrigger->op==TK_INSERT ? "INSERT" : ""),
112736         (pTrigger->op==TK_DELETE ? "DELETE" : ""),
112737       pTab->zName
112738     ));
112739 #ifndef SQLITE_OMIT_TRACE
112740     sqlite3VdbeChangeP4(v, -1, 
112741       sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
112742     );
112743 #endif
112744
112745     /* If one was specified, code the WHEN clause. If it evaluates to false
112746     ** (or NULL) the sub-vdbe is immediately halted by jumping to the 
112747     ** OP_Halt inserted at the end of the program.  */
112748     if( pTrigger->pWhen ){
112749       pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
112750       if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen) 
112751        && db->mallocFailed==0 
112752       ){
112753         iEndTrigger = sqlite3VdbeMakeLabel(v);
112754         sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
112755       }
112756       sqlite3ExprDelete(db, pWhen);
112757     }
112758
112759     /* Code the trigger program into the sub-vdbe. */
112760     codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
112761
112762     /* Insert an OP_Halt at the end of the sub-program. */
112763     if( iEndTrigger ){
112764       sqlite3VdbeResolveLabel(v, iEndTrigger);
112765     }
112766     sqlite3VdbeAddOp0(v, OP_Halt);
112767     VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
112768
112769     transferParseError(pParse, pSubParse);
112770     if( db->mallocFailed==0 ){
112771       pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
112772     }
112773     pProgram->nMem = pSubParse->nMem;
112774     pProgram->nCsr = pSubParse->nTab;
112775     pProgram->nOnce = pSubParse->nOnce;
112776     pProgram->token = (void *)pTrigger;
112777     pPrg->aColmask[0] = pSubParse->oldmask;
112778     pPrg->aColmask[1] = pSubParse->newmask;
112779     sqlite3VdbeDelete(v);
112780   }
112781
112782   assert( !pSubParse->pAinc       && !pSubParse->pZombieTab );
112783   assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
112784   sqlite3ParserReset(pSubParse);
112785   sqlite3StackFree(db, pSubParse);
112786
112787   return pPrg;
112788 }
112789     
112790 /*
112791 ** Return a pointer to a TriggerPrg object containing the sub-program for
112792 ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
112793 ** TriggerPrg object exists, a new object is allocated and populated before
112794 ** being returned.
112795 */
112796 static TriggerPrg *getRowTrigger(
112797   Parse *pParse,       /* Current parse context */
112798   Trigger *pTrigger,   /* Trigger to code */
112799   Table *pTab,         /* The table trigger pTrigger is attached to */
112800   int orconf           /* ON CONFLICT algorithm. */
112801 ){
112802   Parse *pRoot = sqlite3ParseToplevel(pParse);
112803   TriggerPrg *pPrg;
112804
112805   assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
112806
112807   /* It may be that this trigger has already been coded (or is in the
112808   ** process of being coded). If this is the case, then an entry with
112809   ** a matching TriggerPrg.pTrigger field will be present somewhere
112810   ** in the Parse.pTriggerPrg list. Search for such an entry.  */
112811   for(pPrg=pRoot->pTriggerPrg; 
112812       pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf); 
112813       pPrg=pPrg->pNext
112814   );
112815
112816   /* If an existing TriggerPrg could not be located, create a new one. */
112817   if( !pPrg ){
112818     pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
112819   }
112820
112821   return pPrg;
112822 }
112823
112824 /*
112825 ** Generate code for the trigger program associated with trigger p on 
112826 ** table pTab. The reg, orconf and ignoreJump parameters passed to this
112827 ** function are the same as those described in the header function for
112828 ** sqlite3CodeRowTrigger()
112829 */
112830 SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
112831   Parse *pParse,       /* Parse context */
112832   Trigger *p,          /* Trigger to code */
112833   Table *pTab,         /* The table to code triggers from */
112834   int reg,             /* Reg array containing OLD.* and NEW.* values */
112835   int orconf,          /* ON CONFLICT policy */
112836   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
112837 ){
112838   Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
112839   TriggerPrg *pPrg;
112840   pPrg = getRowTrigger(pParse, p, pTab, orconf);
112841   assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
112842
112843   /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program 
112844   ** is a pointer to the sub-vdbe containing the trigger program.  */
112845   if( pPrg ){
112846     int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
112847
112848     sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
112849     sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
112850     VdbeComment(
112851         (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
112852
112853     /* Set the P5 operand of the OP_Program instruction to non-zero if
112854     ** recursive invocation of this trigger program is disallowed. Recursive
112855     ** invocation is disallowed if (a) the sub-program is really a trigger,
112856     ** not a foreign key action, and (b) the flag to enable recursive triggers
112857     ** is clear.  */
112858     sqlite3VdbeChangeP5(v, (u8)bRecursive);
112859   }
112860 }
112861
112862 /*
112863 ** This is called to code the required FOR EACH ROW triggers for an operation
112864 ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
112865 ** is given by the op parameter. The tr_tm parameter determines whether the
112866 ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
112867 ** parameter pChanges is passed the list of columns being modified.
112868 **
112869 ** If there are no triggers that fire at the specified time for the specified
112870 ** operation on pTab, this function is a no-op.
112871 **
112872 ** The reg argument is the address of the first in an array of registers 
112873 ** that contain the values substituted for the new.* and old.* references
112874 ** in the trigger program. If N is the number of columns in table pTab
112875 ** (a copy of pTab->nCol), then registers are populated as follows:
112876 **
112877 **   Register       Contains
112878 **   ------------------------------------------------------
112879 **   reg+0          OLD.rowid
112880 **   reg+1          OLD.* value of left-most column of pTab
112881 **   ...            ...
112882 **   reg+N          OLD.* value of right-most column of pTab
112883 **   reg+N+1        NEW.rowid
112884 **   reg+N+2        OLD.* value of left-most column of pTab
112885 **   ...            ...
112886 **   reg+N+N+1      NEW.* value of right-most column of pTab
112887 **
112888 ** For ON DELETE triggers, the registers containing the NEW.* values will
112889 ** never be accessed by the trigger program, so they are not allocated or 
112890 ** populated by the caller (there is no data to populate them with anyway). 
112891 ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
112892 ** are never accessed, and so are not allocated by the caller. So, for an
112893 ** ON INSERT trigger, the value passed to this function as parameter reg
112894 ** is not a readable register, although registers (reg+N) through 
112895 ** (reg+N+N+1) are.
112896 **
112897 ** Parameter orconf is the default conflict resolution algorithm for the
112898 ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
112899 ** is the instruction that control should jump to if a trigger program
112900 ** raises an IGNORE exception.
112901 */
112902 SQLITE_PRIVATE void sqlite3CodeRowTrigger(
112903   Parse *pParse,       /* Parse context */
112904   Trigger *pTrigger,   /* List of triggers on table pTab */
112905   int op,              /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
112906   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
112907   int tr_tm,           /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
112908   Table *pTab,         /* The table to code triggers from */
112909   int reg,             /* The first in an array of registers (see above) */
112910   int orconf,          /* ON CONFLICT policy */
112911   int ignoreJump       /* Instruction to jump to for RAISE(IGNORE) */
112912 ){
112913   Trigger *p;          /* Used to iterate through pTrigger list */
112914
112915   assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
112916   assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
112917   assert( (op==TK_UPDATE)==(pChanges!=0) );
112918
112919   for(p=pTrigger; p; p=p->pNext){
112920
112921     /* Sanity checking:  The schema for the trigger and for the table are
112922     ** always defined.  The trigger must be in the same schema as the table
112923     ** or else it must be a TEMP trigger. */
112924     assert( p->pSchema!=0 );
112925     assert( p->pTabSchema!=0 );
112926     assert( p->pSchema==p->pTabSchema 
112927          || p->pSchema==pParse->db->aDb[1].pSchema );
112928
112929     /* Determine whether we should code this trigger */
112930     if( p->op==op 
112931      && p->tr_tm==tr_tm 
112932      && checkColumnOverlap(p->pColumns, pChanges)
112933     ){
112934       sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
112935     }
112936   }
112937 }
112938
112939 /*
112940 ** Triggers may access values stored in the old.* or new.* pseudo-table. 
112941 ** This function returns a 32-bit bitmask indicating which columns of the 
112942 ** old.* or new.* tables actually are used by triggers. This information 
112943 ** may be used by the caller, for example, to avoid having to load the entire
112944 ** old.* record into memory when executing an UPDATE or DELETE command.
112945 **
112946 ** Bit 0 of the returned mask is set if the left-most column of the
112947 ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
112948 ** the second leftmost column value is required, and so on. If there
112949 ** are more than 32 columns in the table, and at least one of the columns
112950 ** with an index greater than 32 may be accessed, 0xffffffff is returned.
112951 **
112952 ** It is not possible to determine if the old.rowid or new.rowid column is 
112953 ** accessed by triggers. The caller must always assume that it is.
112954 **
112955 ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
112956 ** applies to the old.* table. If 1, the new.* table.
112957 **
112958 ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
112959 ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
112960 ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
112961 ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
112962 ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
112963 */
112964 SQLITE_PRIVATE u32 sqlite3TriggerColmask(
112965   Parse *pParse,       /* Parse context */
112966   Trigger *pTrigger,   /* List of triggers on table pTab */
112967   ExprList *pChanges,  /* Changes list for any UPDATE OF triggers */
112968   int isNew,           /* 1 for new.* ref mask, 0 for old.* ref mask */
112969   int tr_tm,           /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
112970   Table *pTab,         /* The table to code triggers from */
112971   int orconf           /* Default ON CONFLICT policy for trigger steps */
112972 ){
112973   const int op = pChanges ? TK_UPDATE : TK_DELETE;
112974   u32 mask = 0;
112975   Trigger *p;
112976
112977   assert( isNew==1 || isNew==0 );
112978   for(p=pTrigger; p; p=p->pNext){
112979     if( p->op==op && (tr_tm&p->tr_tm)
112980      && checkColumnOverlap(p->pColumns,pChanges)
112981     ){
112982       TriggerPrg *pPrg;
112983       pPrg = getRowTrigger(pParse, p, pTab, orconf);
112984       if( pPrg ){
112985         mask |= pPrg->aColmask[isNew];
112986       }
112987     }
112988   }
112989
112990   return mask;
112991 }
112992
112993 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
112994
112995 /************** End of trigger.c *********************************************/
112996 /************** Begin file update.c ******************************************/
112997 /*
112998 ** 2001 September 15
112999 **
113000 ** The author disclaims copyright to this source code.  In place of
113001 ** a legal notice, here is a blessing:
113002 **
113003 **    May you do good and not evil.
113004 **    May you find forgiveness for yourself and forgive others.
113005 **    May you share freely, never taking more than you give.
113006 **
113007 *************************************************************************
113008 ** This file contains C code routines that are called by the parser
113009 ** to handle UPDATE statements.
113010 */
113011
113012 #ifndef SQLITE_OMIT_VIRTUALTABLE
113013 /* Forward declaration */
113014 static void updateVirtualTable(
113015   Parse *pParse,       /* The parsing context */
113016   SrcList *pSrc,       /* The virtual table to be modified */
113017   Table *pTab,         /* The virtual table */
113018   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
113019   Expr *pRowidExpr,    /* Expression used to recompute the rowid */
113020   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
113021   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
113022   int onError          /* ON CONFLICT strategy */
113023 );
113024 #endif /* SQLITE_OMIT_VIRTUALTABLE */
113025
113026 /*
113027 ** The most recently coded instruction was an OP_Column to retrieve the
113028 ** i-th column of table pTab. This routine sets the P4 parameter of the 
113029 ** OP_Column to the default value, if any.
113030 **
113031 ** The default value of a column is specified by a DEFAULT clause in the 
113032 ** column definition. This was either supplied by the user when the table
113033 ** was created, or added later to the table definition by an ALTER TABLE
113034 ** command. If the latter, then the row-records in the table btree on disk
113035 ** may not contain a value for the column and the default value, taken
113036 ** from the P4 parameter of the OP_Column instruction, is returned instead.
113037 ** If the former, then all row-records are guaranteed to include a value
113038 ** for the column and the P4 value is not required.
113039 **
113040 ** Column definitions created by an ALTER TABLE command may only have 
113041 ** literal default values specified: a number, null or a string. (If a more
113042 ** complicated default expression value was provided, it is evaluated 
113043 ** when the ALTER TABLE is executed and one of the literal values written
113044 ** into the sqlite_master table.)
113045 **
113046 ** Therefore, the P4 parameter is only required if the default value for
113047 ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
113048 ** function is capable of transforming these types of expressions into
113049 ** sqlite3_value objects.
113050 **
113051 ** If parameter iReg is not negative, code an OP_RealAffinity instruction
113052 ** on register iReg. This is used when an equivalent integer value is 
113053 ** stored in place of an 8-byte floating point value in order to save 
113054 ** space.
113055 */
113056 SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
113057   assert( pTab!=0 );
113058   if( !pTab->pSelect ){
113059     sqlite3_value *pValue = 0;
113060     u8 enc = ENC(sqlite3VdbeDb(v));
113061     Column *pCol = &pTab->aCol[i];
113062     VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
113063     assert( i<pTab->nCol );
113064     sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc, 
113065                          pCol->affinity, &pValue);
113066     if( pValue ){
113067       sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
113068     }
113069 #ifndef SQLITE_OMIT_FLOATING_POINT
113070     if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
113071       sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
113072     }
113073 #endif
113074   }
113075 }
113076
113077 /*
113078 ** Process an UPDATE statement.
113079 **
113080 **   UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
113081 **          \_______/ \________/     \______/       \________________/
113082 *            onError   pTabList      pChanges             pWhere
113083 */
113084 SQLITE_PRIVATE void sqlite3Update(
113085   Parse *pParse,         /* The parser context */
113086   SrcList *pTabList,     /* The table in which we should change things */
113087   ExprList *pChanges,    /* Things to be changed */
113088   Expr *pWhere,          /* The WHERE clause.  May be null */
113089   int onError            /* How to handle constraint errors */
113090 ){
113091   int i, j;              /* Loop counters */
113092   Table *pTab;           /* The table to be updated */
113093   int addrTop = 0;       /* VDBE instruction address of the start of the loop */
113094   WhereInfo *pWInfo;     /* Information about the WHERE clause */
113095   Vdbe *v;               /* The virtual database engine */
113096   Index *pIdx;           /* For looping over indices */
113097   Index *pPk;            /* The PRIMARY KEY index for WITHOUT ROWID tables */
113098   int nIdx;              /* Number of indices that need updating */
113099   int iBaseCur;          /* Base cursor number */
113100   int iDataCur;          /* Cursor for the canonical data btree */
113101   int iIdxCur;           /* Cursor for the first index */
113102   sqlite3 *db;           /* The database structure */
113103   int *aRegIdx = 0;      /* One register assigned to each index to be updated */
113104   int *aXRef = 0;        /* aXRef[i] is the index in pChanges->a[] of the
113105                          ** an expression for the i-th column of the table.
113106                          ** aXRef[i]==-1 if the i-th column is not changed. */
113107   u8 *aToOpen;           /* 1 for tables and indices to be opened */
113108   u8 chngPk;             /* PRIMARY KEY changed in a WITHOUT ROWID table */
113109   u8 chngRowid;          /* Rowid changed in a normal table */
113110   u8 chngKey;            /* Either chngPk or chngRowid */
113111   Expr *pRowidExpr = 0;  /* Expression defining the new record number */
113112   AuthContext sContext;  /* The authorization context */
113113   NameContext sNC;       /* The name-context to resolve expressions in */
113114   int iDb;               /* Database containing the table being updated */
113115   int okOnePass;         /* True for one-pass algorithm without the FIFO */
113116   int hasFK;             /* True if foreign key processing is required */
113117   int labelBreak;        /* Jump here to break out of UPDATE loop */
113118   int labelContinue;     /* Jump here to continue next step of UPDATE loop */
113119
113120 #ifndef SQLITE_OMIT_TRIGGER
113121   int isView;            /* True when updating a view (INSTEAD OF trigger) */
113122   Trigger *pTrigger;     /* List of triggers on pTab, if required */
113123   int tmask;             /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
113124 #endif
113125   int newmask;           /* Mask of NEW.* columns accessed by BEFORE triggers */
113126   int iEph = 0;          /* Ephemeral table holding all primary key values */
113127   int nKey = 0;          /* Number of elements in regKey for WITHOUT ROWID */
113128   int aiCurOnePass[2];   /* The write cursors opened by WHERE_ONEPASS */
113129
113130   /* Register Allocations */
113131   int regRowCount = 0;   /* A count of rows changed */
113132   int regOldRowid;       /* The old rowid */
113133   int regNewRowid;       /* The new rowid */
113134   int regNew;            /* Content of the NEW.* table in triggers */
113135   int regOld = 0;        /* Content of OLD.* table in triggers */
113136   int regRowSet = 0;     /* Rowset of rows to be updated */
113137   int regKey = 0;        /* composite PRIMARY KEY value */
113138
113139   memset(&sContext, 0, sizeof(sContext));
113140   db = pParse->db;
113141   if( pParse->nErr || db->mallocFailed ){
113142     goto update_cleanup;
113143   }
113144   assert( pTabList->nSrc==1 );
113145
113146   /* Locate the table which we want to update. 
113147   */
113148   pTab = sqlite3SrcListLookup(pParse, pTabList);
113149   if( pTab==0 ) goto update_cleanup;
113150   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
113151
113152   /* Figure out if we have any triggers and if the table being
113153   ** updated is a view.
113154   */
113155 #ifndef SQLITE_OMIT_TRIGGER
113156   pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
113157   isView = pTab->pSelect!=0;
113158   assert( pTrigger || tmask==0 );
113159 #else
113160 # define pTrigger 0
113161 # define isView 0
113162 # define tmask 0
113163 #endif
113164 #ifdef SQLITE_OMIT_VIEW
113165 # undef isView
113166 # define isView 0
113167 #endif
113168
113169   if( sqlite3ViewGetColumnNames(pParse, pTab) ){
113170     goto update_cleanup;
113171   }
113172   if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
113173     goto update_cleanup;
113174   }
113175
113176   /* Allocate a cursors for the main database table and for all indices.
113177   ** The index cursors might not be used, but if they are used they
113178   ** need to occur right after the database cursor.  So go ahead and
113179   ** allocate enough space, just in case.
113180   */
113181   pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
113182   iIdxCur = iDataCur+1;
113183   pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
113184   for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
113185     if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
113186       iDataCur = pParse->nTab;
113187       pTabList->a[0].iCursor = iDataCur;
113188     }
113189     pParse->nTab++;
113190   }
113191
113192   /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].  
113193   ** Initialize aXRef[] and aToOpen[] to their default values.
113194   */
113195   aXRef = sqlite3DbMallocRaw(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
113196   if( aXRef==0 ) goto update_cleanup;
113197   aRegIdx = aXRef+pTab->nCol;
113198   aToOpen = (u8*)(aRegIdx+nIdx);
113199   memset(aToOpen, 1, nIdx+1);
113200   aToOpen[nIdx+1] = 0;
113201   for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
113202
113203   /* Initialize the name-context */
113204   memset(&sNC, 0, sizeof(sNC));
113205   sNC.pParse = pParse;
113206   sNC.pSrcList = pTabList;
113207
113208   /* Resolve the column names in all the expressions of the
113209   ** of the UPDATE statement.  Also find the column index
113210   ** for each column to be updated in the pChanges array.  For each
113211   ** column to be updated, make sure we have authorization to change
113212   ** that column.
113213   */
113214   chngRowid = chngPk = 0;
113215   for(i=0; i<pChanges->nExpr; i++){
113216     if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
113217       goto update_cleanup;
113218     }
113219     for(j=0; j<pTab->nCol; j++){
113220       if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
113221         if( j==pTab->iPKey ){
113222           chngRowid = 1;
113223           pRowidExpr = pChanges->a[i].pExpr;
113224         }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
113225           chngPk = 1;
113226         }
113227         aXRef[j] = i;
113228         break;
113229       }
113230     }
113231     if( j>=pTab->nCol ){
113232       if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
113233         j = -1;
113234         chngRowid = 1;
113235         pRowidExpr = pChanges->a[i].pExpr;
113236       }else{
113237         sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
113238         pParse->checkSchema = 1;
113239         goto update_cleanup;
113240       }
113241     }
113242 #ifndef SQLITE_OMIT_AUTHORIZATION
113243     {
113244       int rc;
113245       rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
113246                             j<0 ? "ROWID" : pTab->aCol[j].zName,
113247                             db->aDb[iDb].zName);
113248       if( rc==SQLITE_DENY ){
113249         goto update_cleanup;
113250       }else if( rc==SQLITE_IGNORE ){
113251         aXRef[j] = -1;
113252       }
113253     }
113254 #endif
113255   }
113256   assert( (chngRowid & chngPk)==0 );
113257   assert( chngRowid==0 || chngRowid==1 );
113258   assert( chngPk==0 || chngPk==1 );
113259   chngKey = chngRowid + chngPk;
113260
113261   /* The SET expressions are not actually used inside the WHERE loop.
113262   ** So reset the colUsed mask
113263   */
113264   pTabList->a[0].colUsed = 0;
113265
113266   hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
113267
113268   /* There is one entry in the aRegIdx[] array for each index on the table
113269   ** being updated.  Fill in aRegIdx[] with a register number that will hold
113270   ** the key for accessing each index.  
113271   */
113272   for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
113273     int reg;
113274     if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
113275       reg = ++pParse->nMem;
113276     }else{
113277       reg = 0;
113278       for(i=0; i<pIdx->nKeyCol; i++){
113279         if( aXRef[pIdx->aiColumn[i]]>=0 ){
113280           reg = ++pParse->nMem;
113281           break;
113282         }
113283       }
113284     }
113285     if( reg==0 ) aToOpen[j+1] = 0;
113286     aRegIdx[j] = reg;
113287   }
113288
113289   /* Begin generating code. */
113290   v = sqlite3GetVdbe(pParse);
113291   if( v==0 ) goto update_cleanup;
113292   if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
113293   sqlite3BeginWriteOperation(pParse, 1, iDb);
113294
113295 #ifndef SQLITE_OMIT_VIRTUALTABLE
113296   /* Virtual tables must be handled separately */
113297   if( IsVirtual(pTab) ){
113298     updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
113299                        pWhere, onError);
113300     pWhere = 0;
113301     pTabList = 0;
113302     goto update_cleanup;
113303   }
113304 #endif
113305
113306   /* Allocate required registers. */
113307   regRowSet = ++pParse->nMem;
113308   regOldRowid = regNewRowid = ++pParse->nMem;
113309   if( chngPk || pTrigger || hasFK ){
113310     regOld = pParse->nMem + 1;
113311     pParse->nMem += pTab->nCol;
113312   }
113313   if( chngKey || pTrigger || hasFK ){
113314     regNewRowid = ++pParse->nMem;
113315   }
113316   regNew = pParse->nMem + 1;
113317   pParse->nMem += pTab->nCol;
113318
113319   /* Start the view context. */
113320   if( isView ){
113321     sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
113322   }
113323
113324   /* If we are trying to update a view, realize that view into
113325   ** an ephemeral table.
113326   */
113327 #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
113328   if( isView ){
113329     sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
113330   }
113331 #endif
113332
113333   /* Resolve the column names in all the expressions in the
113334   ** WHERE clause.
113335   */
113336   if( sqlite3ResolveExprNames(&sNC, pWhere) ){
113337     goto update_cleanup;
113338   }
113339
113340   /* Begin the database scan
113341   */
113342   if( HasRowid(pTab) ){
113343     sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
113344     pWInfo = sqlite3WhereBegin(
113345         pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, iIdxCur
113346     );
113347     if( pWInfo==0 ) goto update_cleanup;
113348     okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
113349   
113350     /* Remember the rowid of every item to be updated.
113351     */
113352     sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
113353     if( !okOnePass ){
113354       sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
113355     }
113356   
113357     /* End the database scan loop.
113358     */
113359     sqlite3WhereEnd(pWInfo);
113360   }else{
113361     int iPk;         /* First of nPk memory cells holding PRIMARY KEY value */
113362     i16 nPk;         /* Number of components of the PRIMARY KEY */
113363     int addrOpen;    /* Address of the OpenEphemeral instruction */
113364
113365     assert( pPk!=0 );
113366     nPk = pPk->nKeyCol;
113367     iPk = pParse->nMem+1;
113368     pParse->nMem += nPk;
113369     regKey = ++pParse->nMem;
113370     iEph = pParse->nTab++;
113371     sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
113372     addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
113373     sqlite3VdbeSetP4KeyInfo(pParse, pPk);
113374     pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0, 
113375                                WHERE_ONEPASS_DESIRED, iIdxCur);
113376     if( pWInfo==0 ) goto update_cleanup;
113377     okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
113378     for(i=0; i<nPk; i++){
113379       sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
113380                                       iPk+i);
113381     }
113382     if( okOnePass ){
113383       sqlite3VdbeChangeToNoop(v, addrOpen);
113384       nKey = nPk;
113385       regKey = iPk;
113386     }else{
113387       sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
113388                         sqlite3IndexAffinityStr(v, pPk), nPk);
113389       sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
113390     }
113391     sqlite3WhereEnd(pWInfo);
113392   }
113393
113394   /* Initialize the count of updated rows
113395   */
113396   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
113397     regRowCount = ++pParse->nMem;
113398     sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
113399   }
113400
113401   labelBreak = sqlite3VdbeMakeLabel(v);
113402   if( !isView ){
113403     /* 
113404     ** Open every index that needs updating.  Note that if any
113405     ** index could potentially invoke a REPLACE conflict resolution 
113406     ** action, then we need to open all indices because we might need
113407     ** to be deleting some records.
113408     */
113409     if( onError==OE_Replace ){
113410       memset(aToOpen, 1, nIdx+1);
113411     }else{
113412       for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
113413         if( pIdx->onError==OE_Replace ){
113414           memset(aToOpen, 1, nIdx+1);
113415           break;
113416         }
113417       }
113418     }
113419     if( okOnePass ){
113420       if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
113421       if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
113422     }
113423     sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iBaseCur, aToOpen,
113424                                0, 0);
113425   }
113426
113427   /* Top of the update loop */
113428   if( okOnePass ){
113429     if( aToOpen[iDataCur-iBaseCur] && !isView ){
113430       assert( pPk );
113431       sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
113432       VdbeCoverageNeverTaken(v);
113433     }
113434     labelContinue = labelBreak;
113435     sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
113436     VdbeCoverageIf(v, pPk==0);
113437     VdbeCoverageIf(v, pPk!=0);
113438   }else if( pPk ){
113439     labelContinue = sqlite3VdbeMakeLabel(v);
113440     sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
113441     addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
113442     sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
113443     VdbeCoverage(v);
113444   }else{
113445     labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
113446                              regOldRowid);
113447     VdbeCoverage(v);
113448     sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
113449     VdbeCoverage(v);
113450   }
113451
113452   /* If the record number will change, set register regNewRowid to
113453   ** contain the new value. If the record number is not being modified,
113454   ** then regNewRowid is the same register as regOldRowid, which is
113455   ** already populated.  */
113456   assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
113457   if( chngRowid ){
113458     sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
113459     sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
113460   }
113461
113462   /* Compute the old pre-UPDATE content of the row being changed, if that
113463   ** information is needed */
113464   if( chngPk || hasFK || pTrigger ){
113465     u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
113466     oldmask |= sqlite3TriggerColmask(pParse, 
113467         pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
113468     );
113469     for(i=0; i<pTab->nCol; i++){
113470       if( oldmask==0xffffffff
113471        || (i<32 && (oldmask & MASKBIT32(i))!=0)
113472        || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
113473       ){
113474         testcase(  oldmask!=0xffffffff && i==31 );
113475         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
113476       }else{
113477         sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
113478       }
113479     }
113480     if( chngRowid==0 && pPk==0 ){
113481       sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
113482     }
113483   }
113484
113485   /* Populate the array of registers beginning at regNew with the new
113486   ** row data. This array is used to check constants, create the new
113487   ** table and index records, and as the values for any new.* references
113488   ** made by triggers.
113489   **
113490   ** If there are one or more BEFORE triggers, then do not populate the
113491   ** registers associated with columns that are (a) not modified by
113492   ** this UPDATE statement and (b) not accessed by new.* references. The
113493   ** values for registers not modified by the UPDATE must be reloaded from 
113494   ** the database after the BEFORE triggers are fired anyway (as the trigger 
113495   ** may have modified them). So not loading those that are not going to
113496   ** be used eliminates some redundant opcodes.
113497   */
113498   newmask = sqlite3TriggerColmask(
113499       pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
113500   );
113501   /*sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);*/
113502   for(i=0; i<pTab->nCol; i++){
113503     if( i==pTab->iPKey ){
113504       sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
113505     }else{
113506       j = aXRef[i];
113507       if( j>=0 ){
113508         sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
113509       }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
113510         /* This branch loads the value of a column that will not be changed 
113511         ** into a register. This is done if there are no BEFORE triggers, or
113512         ** if there are one or more BEFORE triggers that use this value via
113513         ** a new.* reference in a trigger program.
113514         */
113515         testcase( i==31 );
113516         testcase( i==32 );
113517         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
113518       }else{
113519         sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
113520       }
113521     }
113522   }
113523
113524   /* Fire any BEFORE UPDATE triggers. This happens before constraints are
113525   ** verified. One could argue that this is wrong.
113526   */
113527   if( tmask&TRIGGER_BEFORE ){
113528     sqlite3TableAffinity(v, pTab, regNew);
113529     sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
113530         TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
113531
113532     /* The row-trigger may have deleted the row being updated. In this
113533     ** case, jump to the next row. No updates or AFTER triggers are 
113534     ** required. This behavior - what happens when the row being updated
113535     ** is deleted or renamed by a BEFORE trigger - is left undefined in the
113536     ** documentation.
113537     */
113538     if( pPk ){
113539       sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
113540       VdbeCoverage(v);
113541     }else{
113542       sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
113543       VdbeCoverage(v);
113544     }
113545
113546     /* If it did not delete it, the row-trigger may still have modified 
113547     ** some of the columns of the row being updated. Load the values for 
113548     ** all columns not modified by the update statement into their 
113549     ** registers in case this has happened.
113550     */
113551     for(i=0; i<pTab->nCol; i++){
113552       if( aXRef[i]<0 && i!=pTab->iPKey ){
113553         sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
113554       }
113555     }
113556   }
113557
113558   if( !isView ){
113559     int j1 = 0;           /* Address of jump instruction */
113560     int bReplace = 0;     /* True if REPLACE conflict resolution might happen */
113561
113562     /* Do constraint checks. */
113563     assert( regOldRowid>0 );
113564     sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
113565         regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace);
113566
113567     /* Do FK constraint checks. */
113568     if( hasFK ){
113569       sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
113570     }
113571
113572     /* Delete the index entries associated with the current record.  */
113573     if( bReplace || chngKey ){
113574       if( pPk ){
113575         j1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
113576       }else{
113577         j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
113578       }
113579       VdbeCoverageNeverTaken(v);
113580     }
113581     sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx);
113582   
113583     /* If changing the record number, delete the old record.  */
113584     if( hasFK || chngKey || pPk!=0 ){
113585       sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
113586     }
113587     if( bReplace || chngKey ){
113588       sqlite3VdbeJumpHere(v, j1);
113589     }
113590
113591     if( hasFK ){
113592       sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
113593     }
113594   
113595     /* Insert the new index entries and the new record. */
113596     sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
113597                              regNewRowid, aRegIdx, 1, 0, 0);
113598
113599     /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
113600     ** handle rows (possibly in other tables) that refer via a foreign key
113601     ** to the row just updated. */ 
113602     if( hasFK ){
113603       sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
113604     }
113605   }
113606
113607   /* Increment the row counter 
113608   */
113609   if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
113610     sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
113611   }
113612
113613   sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges, 
113614       TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
113615
113616   /* Repeat the above with the next record to be updated, until
113617   ** all record selected by the WHERE clause have been updated.
113618   */
113619   if( okOnePass ){
113620     /* Nothing to do at end-of-loop for a single-pass */
113621   }else if( pPk ){
113622     sqlite3VdbeResolveLabel(v, labelContinue);
113623     sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
113624   }else{
113625     sqlite3VdbeAddOp2(v, OP_Goto, 0, labelContinue);
113626   }
113627   sqlite3VdbeResolveLabel(v, labelBreak);
113628
113629   /* Close all tables */
113630   for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
113631     assert( aRegIdx );
113632     if( aToOpen[i+1] ){
113633       sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
113634     }
113635   }
113636   if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
113637
113638   /* Update the sqlite_sequence table by storing the content of the
113639   ** maximum rowid counter values recorded while inserting into
113640   ** autoincrement tables.
113641   */
113642   if( pParse->nested==0 && pParse->pTriggerTab==0 ){
113643     sqlite3AutoincrementEnd(pParse);
113644   }
113645
113646   /*
113647   ** Return the number of rows that were changed. If this routine is 
113648   ** generating code because of a call to sqlite3NestedParse(), do not
113649   ** invoke the callback function.
113650   */
113651   if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
113652     sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
113653     sqlite3VdbeSetNumCols(v, 1);
113654     sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
113655   }
113656
113657 update_cleanup:
113658   sqlite3AuthContextPop(&sContext);
113659   sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
113660   sqlite3SrcListDelete(db, pTabList);
113661   sqlite3ExprListDelete(db, pChanges);
113662   sqlite3ExprDelete(db, pWhere);
113663   return;
113664 }
113665 /* Make sure "isView" and other macros defined above are undefined. Otherwise
113666 ** they may interfere with compilation of other functions in this file
113667 ** (or in another file, if this file becomes part of the amalgamation).  */
113668 #ifdef isView
113669  #undef isView
113670 #endif
113671 #ifdef pTrigger
113672  #undef pTrigger
113673 #endif
113674
113675 #ifndef SQLITE_OMIT_VIRTUALTABLE
113676 /*
113677 ** Generate code for an UPDATE of a virtual table.
113678 **
113679 ** The strategy is that we create an ephemeral table that contains
113680 ** for each row to be changed:
113681 **
113682 **   (A)  The original rowid of that row.
113683 **   (B)  The revised rowid for the row. (note1)
113684 **   (C)  The content of every column in the row.
113685 **
113686 ** Then we loop over this ephemeral table and for each row in
113687 ** the ephemeral table call VUpdate.
113688 **
113689 ** When finished, drop the ephemeral table.
113690 **
113691 ** (note1) Actually, if we know in advance that (A) is always the same
113692 ** as (B) we only store (A), then duplicate (A) when pulling
113693 ** it out of the ephemeral table before calling VUpdate.
113694 */
113695 static void updateVirtualTable(
113696   Parse *pParse,       /* The parsing context */
113697   SrcList *pSrc,       /* The virtual table to be modified */
113698   Table *pTab,         /* The virtual table */
113699   ExprList *pChanges,  /* The columns to change in the UPDATE statement */
113700   Expr *pRowid,        /* Expression used to recompute the rowid */
113701   int *aXRef,          /* Mapping from columns of pTab to entries in pChanges */
113702   Expr *pWhere,        /* WHERE clause of the UPDATE statement */
113703   int onError          /* ON CONFLICT strategy */
113704 ){
113705   Vdbe *v = pParse->pVdbe;  /* Virtual machine under construction */
113706   ExprList *pEList = 0;     /* The result set of the SELECT statement */
113707   Select *pSelect = 0;      /* The SELECT statement */
113708   Expr *pExpr;              /* Temporary expression */
113709   int ephemTab;             /* Table holding the result of the SELECT */
113710   int i;                    /* Loop counter */
113711   int addr;                 /* Address of top of loop */
113712   int iReg;                 /* First register in set passed to OP_VUpdate */
113713   sqlite3 *db = pParse->db; /* Database connection */
113714   const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
113715   SelectDest dest;
113716
113717   /* Construct the SELECT statement that will find the new values for
113718   ** all updated rows. 
113719   */
113720   pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
113721   if( pRowid ){
113722     pEList = sqlite3ExprListAppend(pParse, pEList,
113723                                    sqlite3ExprDup(db, pRowid, 0));
113724   }
113725   assert( pTab->iPKey<0 );
113726   for(i=0; i<pTab->nCol; i++){
113727     if( aXRef[i]>=0 ){
113728       pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
113729     }else{
113730       pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
113731     }
113732     pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
113733   }
113734   pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
113735   
113736   /* Create the ephemeral table into which the update results will
113737   ** be stored.
113738   */
113739   assert( v );
113740   ephemTab = pParse->nTab++;
113741   sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
113742   sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
113743
113744   /* fill the ephemeral table 
113745   */
113746   sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
113747   sqlite3Select(pParse, pSelect, &dest);
113748
113749   /* Generate code to scan the ephemeral table and call VUpdate. */
113750   iReg = ++pParse->nMem;
113751   pParse->nMem += pTab->nCol+1;
113752   addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0); VdbeCoverage(v);
113753   sqlite3VdbeAddOp3(v, OP_Column,  ephemTab, 0, iReg);
113754   sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
113755   for(i=0; i<pTab->nCol; i++){
113756     sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
113757   }
113758   sqlite3VtabMakeWritable(pParse, pTab);
113759   sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
113760   sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
113761   sqlite3MayAbort(pParse);
113762   sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
113763   sqlite3VdbeJumpHere(v, addr);
113764   sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
113765
113766   /* Cleanup */
113767   sqlite3SelectDelete(db, pSelect);  
113768 }
113769 #endif /* SQLITE_OMIT_VIRTUALTABLE */
113770
113771 /************** End of update.c **********************************************/
113772 /************** Begin file vacuum.c ******************************************/
113773 /*
113774 ** 2003 April 6
113775 **
113776 ** The author disclaims copyright to this source code.  In place of
113777 ** a legal notice, here is a blessing:
113778 **
113779 **    May you do good and not evil.
113780 **    May you find forgiveness for yourself and forgive others.
113781 **    May you share freely, never taking more than you give.
113782 **
113783 *************************************************************************
113784 ** This file contains code used to implement the VACUUM command.
113785 **
113786 ** Most of the code in this file may be omitted by defining the
113787 ** SQLITE_OMIT_VACUUM macro.
113788 */
113789
113790 #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
113791 /*
113792 ** Finalize a prepared statement.  If there was an error, store the
113793 ** text of the error message in *pzErrMsg.  Return the result code.
113794 */
113795 static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
113796   int rc;
113797   rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
113798   if( rc ){
113799     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
113800   }
113801   return rc;
113802 }
113803
113804 /*
113805 ** Execute zSql on database db. Return an error code.
113806 */
113807 static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
113808   sqlite3_stmt *pStmt;
113809   VVA_ONLY( int rc; )
113810   if( !zSql ){
113811     return SQLITE_NOMEM;
113812   }
113813   if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
113814     sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
113815     return sqlite3_errcode(db);
113816   }
113817   VVA_ONLY( rc = ) sqlite3_step(pStmt);
113818   assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
113819   return vacuumFinalize(db, pStmt, pzErrMsg);
113820 }
113821
113822 /*
113823 ** Execute zSql on database db. The statement returns exactly
113824 ** one column. Execute this as SQL on the same database.
113825 */
113826 static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
113827   sqlite3_stmt *pStmt;
113828   int rc;
113829
113830   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
113831   if( rc!=SQLITE_OK ) return rc;
113832
113833   while( SQLITE_ROW==sqlite3_step(pStmt) ){
113834     rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
113835     if( rc!=SQLITE_OK ){
113836       vacuumFinalize(db, pStmt, pzErrMsg);
113837       return rc;
113838     }
113839   }
113840
113841   return vacuumFinalize(db, pStmt, pzErrMsg);
113842 }
113843
113844 /*
113845 ** The VACUUM command is used to clean up the database,
113846 ** collapse free space, etc.  It is modelled after the VACUUM command
113847 ** in PostgreSQL.  The VACUUM command works as follows:
113848 **
113849 **   (1)  Create a new transient database file
113850 **   (2)  Copy all content from the database being vacuumed into
113851 **        the new transient database file
113852 **   (3)  Copy content from the transient database back into the
113853 **        original database.
113854 **
113855 ** The transient database requires temporary disk space approximately
113856 ** equal to the size of the original database.  The copy operation of
113857 ** step (3) requires additional temporary disk space approximately equal
113858 ** to the size of the original database for the rollback journal.
113859 ** Hence, temporary disk space that is approximately 2x the size of the
113860 ** original database is required.  Every page of the database is written
113861 ** approximately 3 times:  Once for step (2) and twice for step (3).
113862 ** Two writes per page are required in step (3) because the original
113863 ** database content must be written into the rollback journal prior to
113864 ** overwriting the database with the vacuumed content.
113865 **
113866 ** Only 1x temporary space and only 1x writes would be required if
113867 ** the copy of step (3) were replaced by deleting the original database
113868 ** and renaming the transient database as the original.  But that will
113869 ** not work if other processes are attached to the original database.
113870 ** And a power loss in between deleting the original and renaming the
113871 ** transient would cause the database file to appear to be deleted
113872 ** following reboot.
113873 */
113874 SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
113875   Vdbe *v = sqlite3GetVdbe(pParse);
113876   if( v ){
113877     sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
113878     sqlite3VdbeUsesBtree(v, 0);
113879   }
113880   return;
113881 }
113882
113883 /*
113884 ** This routine implements the OP_Vacuum opcode of the VDBE.
113885 */
113886 SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
113887   int rc = SQLITE_OK;     /* Return code from service routines */
113888   Btree *pMain;           /* The database being vacuumed */
113889   Btree *pTemp;           /* The temporary database we vacuum into */
113890   char *zSql = 0;         /* SQL statements */
113891   int saved_flags;        /* Saved value of the db->flags */
113892   int saved_nChange;      /* Saved value of db->nChange */
113893   int saved_nTotalChange; /* Saved value of db->nTotalChange */
113894   void (*saved_xTrace)(void*,const char*);  /* Saved db->xTrace */
113895   Db *pDb = 0;            /* Database to detach at end of vacuum */
113896   int isMemDb;            /* True if vacuuming a :memory: database */
113897   int nRes;               /* Bytes of reserved space at the end of each page */
113898   int nDb;                /* Number of attached databases */
113899
113900   if( !db->autoCommit ){
113901     sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
113902     return SQLITE_ERROR;
113903   }
113904   if( db->nVdbeActive>1 ){
113905     sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
113906     return SQLITE_ERROR;
113907   }
113908
113909   /* Save the current value of the database flags so that it can be 
113910   ** restored before returning. Then set the writable-schema flag, and
113911   ** disable CHECK and foreign key constraints.  */
113912   saved_flags = db->flags;
113913   saved_nChange = db->nChange;
113914   saved_nTotalChange = db->nTotalChange;
113915   saved_xTrace = db->xTrace;
113916   db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
113917   db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
113918   db->xTrace = 0;
113919
113920   pMain = db->aDb[0].pBt;
113921   isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
113922
113923   /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
113924   ** can be set to 'off' for this file, as it is not recovered if a crash
113925   ** occurs anyway. The integrity of the database is maintained by a
113926   ** (possibly synchronous) transaction opened on the main database before
113927   ** sqlite3BtreeCopyFile() is called.
113928   **
113929   ** An optimisation would be to use a non-journaled pager.
113930   ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
113931   ** that actually made the VACUUM run slower.  Very little journalling
113932   ** actually occurs when doing a vacuum since the vacuum_db is initially
113933   ** empty.  Only the journal header is written.  Apparently it takes more
113934   ** time to parse and run the PRAGMA to turn journalling off than it does
113935   ** to write the journal header file.
113936   */
113937   nDb = db->nDb;
113938   if( sqlite3TempInMemory(db) ){
113939     zSql = "ATTACH ':memory:' AS vacuum_db;";
113940   }else{
113941     zSql = "ATTACH '' AS vacuum_db;";
113942   }
113943   rc = execSql(db, pzErrMsg, zSql);
113944   if( db->nDb>nDb ){
113945     pDb = &db->aDb[db->nDb-1];
113946     assert( strcmp(pDb->zName,"vacuum_db")==0 );
113947   }
113948   if( rc!=SQLITE_OK ) goto end_of_vacuum;
113949   pTemp = db->aDb[db->nDb-1].pBt;
113950
113951   /* The call to execSql() to attach the temp database has left the file
113952   ** locked (as there was more than one active statement when the transaction
113953   ** to read the schema was concluded. Unlock it here so that this doesn't
113954   ** cause problems for the call to BtreeSetPageSize() below.  */
113955   sqlite3BtreeCommit(pTemp);
113956
113957   nRes = sqlite3BtreeGetOptimalReserve(pMain);
113958
113959   /* A VACUUM cannot change the pagesize of an encrypted database. */
113960 #ifdef SQLITE_HAS_CODEC
113961   if( db->nextPagesize ){
113962     extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
113963     int nKey;
113964     char *zKey;
113965     sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
113966     if( nKey ) db->nextPagesize = 0;
113967   }
113968 #endif
113969
113970   rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
113971   if( rc!=SQLITE_OK ) goto end_of_vacuum;
113972
113973   /* Begin a transaction and take an exclusive lock on the main database
113974   ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
113975   ** to ensure that we do not try to change the page-size on a WAL database.
113976   */
113977   rc = execSql(db, pzErrMsg, "BEGIN;");
113978   if( rc!=SQLITE_OK ) goto end_of_vacuum;
113979   rc = sqlite3BtreeBeginTrans(pMain, 2);
113980   if( rc!=SQLITE_OK ) goto end_of_vacuum;
113981
113982   /* Do not attempt to change the page size for a WAL database */
113983   if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
113984                                                ==PAGER_JOURNALMODE_WAL ){
113985     db->nextPagesize = 0;
113986   }
113987
113988   if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
113989    || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
113990    || NEVER(db->mallocFailed)
113991   ){
113992     rc = SQLITE_NOMEM;
113993     goto end_of_vacuum;
113994   }
113995
113996 #ifndef SQLITE_OMIT_AUTOVACUUM
113997   sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
113998                                            sqlite3BtreeGetAutoVacuum(pMain));
113999 #endif
114000
114001   /* Query the schema of the main database. Create a mirror schema
114002   ** in the temporary database.
114003   */
114004   rc = execExecSql(db, pzErrMsg,
114005       "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
114006       "  FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
114007       "   AND coalesce(rootpage,1)>0"
114008   );
114009   if( rc!=SQLITE_OK ) goto end_of_vacuum;
114010   rc = execExecSql(db, pzErrMsg,
114011       "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
114012       "  FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
114013   if( rc!=SQLITE_OK ) goto end_of_vacuum;
114014   rc = execExecSql(db, pzErrMsg,
114015       "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
114016       "  FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
114017   if( rc!=SQLITE_OK ) goto end_of_vacuum;
114018
114019   /* Loop through the tables in the main database. For each, do
114020   ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
114021   ** the contents to the temporary database.
114022   */
114023   rc = execExecSql(db, pzErrMsg,
114024       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
114025       "|| ' SELECT * FROM main.' || quote(name) || ';'"
114026       "FROM main.sqlite_master "
114027       "WHERE type = 'table' AND name!='sqlite_sequence' "
114028       "  AND coalesce(rootpage,1)>0"
114029   );
114030   if( rc!=SQLITE_OK ) goto end_of_vacuum;
114031
114032   /* Copy over the sequence table
114033   */
114034   rc = execExecSql(db, pzErrMsg,
114035       "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
114036       "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
114037   );
114038   if( rc!=SQLITE_OK ) goto end_of_vacuum;
114039   rc = execExecSql(db, pzErrMsg,
114040       "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
114041       "|| ' SELECT * FROM main.' || quote(name) || ';' "
114042       "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
114043   );
114044   if( rc!=SQLITE_OK ) goto end_of_vacuum;
114045
114046
114047   /* Copy the triggers, views, and virtual tables from the main database
114048   ** over to the temporary database.  None of these objects has any
114049   ** associated storage, so all we have to do is copy their entries
114050   ** from the SQLITE_MASTER table.
114051   */
114052   rc = execSql(db, pzErrMsg,
114053       "INSERT INTO vacuum_db.sqlite_master "
114054       "  SELECT type, name, tbl_name, rootpage, sql"
114055       "    FROM main.sqlite_master"
114056       "   WHERE type='view' OR type='trigger'"
114057       "      OR (type='table' AND rootpage=0)"
114058   );
114059   if( rc ) goto end_of_vacuum;
114060
114061   /* At this point, there is a write transaction open on both the 
114062   ** vacuum database and the main database. Assuming no error occurs,
114063   ** both transactions are closed by this block - the main database
114064   ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
114065   ** call to sqlite3BtreeCommit().
114066   */
114067   {
114068     u32 meta;
114069     int i;
114070
114071     /* This array determines which meta meta values are preserved in the
114072     ** vacuum.  Even entries are the meta value number and odd entries
114073     ** are an increment to apply to the meta value after the vacuum.
114074     ** The increment is used to increase the schema cookie so that other
114075     ** connections to the same database will know to reread the schema.
114076     */
114077     static const unsigned char aCopy[] = {
114078        BTREE_SCHEMA_VERSION,     1,  /* Add one to the old schema cookie */
114079        BTREE_DEFAULT_CACHE_SIZE, 0,  /* Preserve the default page cache size */
114080        BTREE_TEXT_ENCODING,      0,  /* Preserve the text encoding */
114081        BTREE_USER_VERSION,       0,  /* Preserve the user version */
114082        BTREE_APPLICATION_ID,     0,  /* Preserve the application id */
114083     };
114084
114085     assert( 1==sqlite3BtreeIsInTrans(pTemp) );
114086     assert( 1==sqlite3BtreeIsInTrans(pMain) );
114087
114088     /* Copy Btree meta values */
114089     for(i=0; i<ArraySize(aCopy); i+=2){
114090       /* GetMeta() and UpdateMeta() cannot fail in this context because
114091       ** we already have page 1 loaded into cache and marked dirty. */
114092       sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
114093       rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
114094       if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
114095     }
114096
114097     rc = sqlite3BtreeCopyFile(pMain, pTemp);
114098     if( rc!=SQLITE_OK ) goto end_of_vacuum;
114099     rc = sqlite3BtreeCommit(pTemp);
114100     if( rc!=SQLITE_OK ) goto end_of_vacuum;
114101 #ifndef SQLITE_OMIT_AUTOVACUUM
114102     sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
114103 #endif
114104   }
114105
114106   assert( rc==SQLITE_OK );
114107   rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
114108
114109 end_of_vacuum:
114110   /* Restore the original value of db->flags */
114111   db->flags = saved_flags;
114112   db->nChange = saved_nChange;
114113   db->nTotalChange = saved_nTotalChange;
114114   db->xTrace = saved_xTrace;
114115   sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
114116
114117   /* Currently there is an SQL level transaction open on the vacuum
114118   ** database. No locks are held on any other files (since the main file
114119   ** was committed at the btree level). So it safe to end the transaction
114120   ** by manually setting the autoCommit flag to true and detaching the
114121   ** vacuum database. The vacuum_db journal file is deleted when the pager
114122   ** is closed by the DETACH.
114123   */
114124   db->autoCommit = 1;
114125
114126   if( pDb ){
114127     sqlite3BtreeClose(pDb->pBt);
114128     pDb->pBt = 0;
114129     pDb->pSchema = 0;
114130   }
114131
114132   /* This both clears the schemas and reduces the size of the db->aDb[]
114133   ** array. */ 
114134   sqlite3ResetAllSchemasOfConnection(db);
114135
114136   return rc;
114137 }
114138
114139 #endif  /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
114140
114141 /************** End of vacuum.c **********************************************/
114142 /************** Begin file vtab.c ********************************************/
114143 /*
114144 ** 2006 June 10
114145 **
114146 ** The author disclaims copyright to this source code.  In place of
114147 ** a legal notice, here is a blessing:
114148 **
114149 **    May you do good and not evil.
114150 **    May you find forgiveness for yourself and forgive others.
114151 **    May you share freely, never taking more than you give.
114152 **
114153 *************************************************************************
114154 ** This file contains code used to help implement virtual tables.
114155 */
114156 #ifndef SQLITE_OMIT_VIRTUALTABLE
114157
114158 /*
114159 ** Before a virtual table xCreate() or xConnect() method is invoked, the
114160 ** sqlite3.pVtabCtx member variable is set to point to an instance of
114161 ** this struct allocated on the stack. It is used by the implementation of 
114162 ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
114163 ** are invoked only from within xCreate and xConnect methods.
114164 */
114165 struct VtabCtx {
114166   VTable *pVTable;    /* The virtual table being constructed */
114167   Table *pTab;        /* The Table object to which the virtual table belongs */
114168 };
114169
114170 /*
114171 ** The actual function that does the work of creating a new module.
114172 ** This function implements the sqlite3_create_module() and
114173 ** sqlite3_create_module_v2() interfaces.
114174 */
114175 static int createModule(
114176   sqlite3 *db,                    /* Database in which module is registered */
114177   const char *zName,              /* Name assigned to this module */
114178   const sqlite3_module *pModule,  /* The definition of the module */
114179   void *pAux,                     /* Context pointer for xCreate/xConnect */
114180   void (*xDestroy)(void *)        /* Module destructor function */
114181 ){
114182   int rc = SQLITE_OK;
114183   int nName;
114184
114185   sqlite3_mutex_enter(db->mutex);
114186   nName = sqlite3Strlen30(zName);
114187   if( sqlite3HashFind(&db->aModule, zName) ){
114188     rc = SQLITE_MISUSE_BKPT;
114189   }else{
114190     Module *pMod;
114191     pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
114192     if( pMod ){
114193       Module *pDel;
114194       char *zCopy = (char *)(&pMod[1]);
114195       memcpy(zCopy, zName, nName+1);
114196       pMod->zName = zCopy;
114197       pMod->pModule = pModule;
114198       pMod->pAux = pAux;
114199       pMod->xDestroy = xDestroy;
114200       pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
114201       assert( pDel==0 || pDel==pMod );
114202       if( pDel ){
114203         db->mallocFailed = 1;
114204         sqlite3DbFree(db, pDel);
114205       }
114206     }
114207   }
114208   rc = sqlite3ApiExit(db, rc);
114209   if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
114210
114211   sqlite3_mutex_leave(db->mutex);
114212   return rc;
114213 }
114214
114215
114216 /*
114217 ** External API function used to create a new virtual-table module.
114218 */
114219 SQLITE_API int SQLITE_STDCALL sqlite3_create_module(
114220   sqlite3 *db,                    /* Database in which module is registered */
114221   const char *zName,              /* Name assigned to this module */
114222   const sqlite3_module *pModule,  /* The definition of the module */
114223   void *pAux                      /* Context pointer for xCreate/xConnect */
114224 ){
114225 #ifdef SQLITE_ENABLE_API_ARMOR
114226   if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
114227 #endif
114228   return createModule(db, zName, pModule, pAux, 0);
114229 }
114230
114231 /*
114232 ** External API function used to create a new virtual-table module.
114233 */
114234 SQLITE_API int SQLITE_STDCALL sqlite3_create_module_v2(
114235   sqlite3 *db,                    /* Database in which module is registered */
114236   const char *zName,              /* Name assigned to this module */
114237   const sqlite3_module *pModule,  /* The definition of the module */
114238   void *pAux,                     /* Context pointer for xCreate/xConnect */
114239   void (*xDestroy)(void *)        /* Module destructor function */
114240 ){
114241 #ifdef SQLITE_ENABLE_API_ARMOR
114242   if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
114243 #endif
114244   return createModule(db, zName, pModule, pAux, xDestroy);
114245 }
114246
114247 /*
114248 ** Lock the virtual table so that it cannot be disconnected.
114249 ** Locks nest.  Every lock should have a corresponding unlock.
114250 ** If an unlock is omitted, resources leaks will occur.  
114251 **
114252 ** If a disconnect is attempted while a virtual table is locked,
114253 ** the disconnect is deferred until all locks have been removed.
114254 */
114255 SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
114256   pVTab->nRef++;
114257 }
114258
114259
114260 /*
114261 ** pTab is a pointer to a Table structure representing a virtual-table.
114262 ** Return a pointer to the VTable object used by connection db to access 
114263 ** this virtual-table, if one has been created, or NULL otherwise.
114264 */
114265 SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
114266   VTable *pVtab;
114267   assert( IsVirtual(pTab) );
114268   for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
114269   return pVtab;
114270 }
114271
114272 /*
114273 ** Decrement the ref-count on a virtual table object. When the ref-count
114274 ** reaches zero, call the xDisconnect() method to delete the object.
114275 */
114276 SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
114277   sqlite3 *db = pVTab->db;
114278
114279   assert( db );
114280   assert( pVTab->nRef>0 );
114281   assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
114282
114283   pVTab->nRef--;
114284   if( pVTab->nRef==0 ){
114285     sqlite3_vtab *p = pVTab->pVtab;
114286     if( p ){
114287       p->pModule->xDisconnect(p);
114288     }
114289     sqlite3DbFree(db, pVTab);
114290   }
114291 }
114292
114293 /*
114294 ** Table p is a virtual table. This function moves all elements in the
114295 ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
114296 ** database connections to be disconnected at the next opportunity. 
114297 ** Except, if argument db is not NULL, then the entry associated with
114298 ** connection db is left in the p->pVTable list.
114299 */
114300 static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
114301   VTable *pRet = 0;
114302   VTable *pVTable = p->pVTable;
114303   p->pVTable = 0;
114304
114305   /* Assert that the mutex (if any) associated with the BtShared database 
114306   ** that contains table p is held by the caller. See header comments 
114307   ** above function sqlite3VtabUnlockList() for an explanation of why
114308   ** this makes it safe to access the sqlite3.pDisconnect list of any
114309   ** database connection that may have an entry in the p->pVTable list.
114310   */
114311   assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
114312
114313   while( pVTable ){
114314     sqlite3 *db2 = pVTable->db;
114315     VTable *pNext = pVTable->pNext;
114316     assert( db2 );
114317     if( db2==db ){
114318       pRet = pVTable;
114319       p->pVTable = pRet;
114320       pRet->pNext = 0;
114321     }else{
114322       pVTable->pNext = db2->pDisconnect;
114323       db2->pDisconnect = pVTable;
114324     }
114325     pVTable = pNext;
114326   }
114327
114328   assert( !db || pRet );
114329   return pRet;
114330 }
114331
114332 /*
114333 ** Table *p is a virtual table. This function removes the VTable object
114334 ** for table *p associated with database connection db from the linked
114335 ** list in p->pVTab. It also decrements the VTable ref count. This is
114336 ** used when closing database connection db to free all of its VTable
114337 ** objects without disturbing the rest of the Schema object (which may
114338 ** be being used by other shared-cache connections).
114339 */
114340 SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
114341   VTable **ppVTab;
114342
114343   assert( IsVirtual(p) );
114344   assert( sqlite3BtreeHoldsAllMutexes(db) );
114345   assert( sqlite3_mutex_held(db->mutex) );
114346
114347   for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
114348     if( (*ppVTab)->db==db  ){
114349       VTable *pVTab = *ppVTab;
114350       *ppVTab = pVTab->pNext;
114351       sqlite3VtabUnlock(pVTab);
114352       break;
114353     }
114354   }
114355 }
114356
114357
114358 /*
114359 ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
114360 **
114361 ** This function may only be called when the mutexes associated with all
114362 ** shared b-tree databases opened using connection db are held by the 
114363 ** caller. This is done to protect the sqlite3.pDisconnect list. The
114364 ** sqlite3.pDisconnect list is accessed only as follows:
114365 **
114366 **   1) By this function. In this case, all BtShared mutexes and the mutex
114367 **      associated with the database handle itself must be held.
114368 **
114369 **   2) By function vtabDisconnectAll(), when it adds a VTable entry to
114370 **      the sqlite3.pDisconnect list. In this case either the BtShared mutex
114371 **      associated with the database the virtual table is stored in is held
114372 **      or, if the virtual table is stored in a non-sharable database, then
114373 **      the database handle mutex is held.
114374 **
114375 ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously 
114376 ** by multiple threads. It is thread-safe.
114377 */
114378 SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
114379   VTable *p = db->pDisconnect;
114380   db->pDisconnect = 0;
114381
114382   assert( sqlite3BtreeHoldsAllMutexes(db) );
114383   assert( sqlite3_mutex_held(db->mutex) );
114384
114385   if( p ){
114386     sqlite3ExpirePreparedStatements(db);
114387     do {
114388       VTable *pNext = p->pNext;
114389       sqlite3VtabUnlock(p);
114390       p = pNext;
114391     }while( p );
114392   }
114393 }
114394
114395 /*
114396 ** Clear any and all virtual-table information from the Table record.
114397 ** This routine is called, for example, just before deleting the Table
114398 ** record.
114399 **
114400 ** Since it is a virtual-table, the Table structure contains a pointer
114401 ** to the head of a linked list of VTable structures. Each VTable 
114402 ** structure is associated with a single sqlite3* user of the schema.
114403 ** The reference count of the VTable structure associated with database 
114404 ** connection db is decremented immediately (which may lead to the 
114405 ** structure being xDisconnected and free). Any other VTable structures
114406 ** in the list are moved to the sqlite3.pDisconnect list of the associated 
114407 ** database connection.
114408 */
114409 SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
114410   if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
114411   if( p->azModuleArg ){
114412     int i;
114413     for(i=0; i<p->nModuleArg; i++){
114414       if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
114415     }
114416     sqlite3DbFree(db, p->azModuleArg);
114417   }
114418 }
114419
114420 /*
114421 ** Add a new module argument to pTable->azModuleArg[].
114422 ** The string is not copied - the pointer is stored.  The
114423 ** string will be freed automatically when the table is
114424 ** deleted.
114425 */
114426 static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
114427   int i = pTable->nModuleArg++;
114428   int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
114429   char **azModuleArg;
114430   azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
114431   if( azModuleArg==0 ){
114432     int j;
114433     for(j=0; j<i; j++){
114434       sqlite3DbFree(db, pTable->azModuleArg[j]);
114435     }
114436     sqlite3DbFree(db, zArg);
114437     sqlite3DbFree(db, pTable->azModuleArg);
114438     pTable->nModuleArg = 0;
114439   }else{
114440     azModuleArg[i] = zArg;
114441     azModuleArg[i+1] = 0;
114442   }
114443   pTable->azModuleArg = azModuleArg;
114444 }
114445
114446 /*
114447 ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
114448 ** statement.  The module name has been parsed, but the optional list
114449 ** of parameters that follow the module name are still pending.
114450 */
114451 SQLITE_PRIVATE void sqlite3VtabBeginParse(
114452   Parse *pParse,        /* Parsing context */
114453   Token *pName1,        /* Name of new table, or database name */
114454   Token *pName2,        /* Name of new table or NULL */
114455   Token *pModuleName,   /* Name of the module for the virtual table */
114456   int ifNotExists       /* No error if the table already exists */
114457 ){
114458   int iDb;              /* The database the table is being created in */
114459   Table *pTable;        /* The new virtual table */
114460   sqlite3 *db;          /* Database connection */
114461
114462   sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
114463   pTable = pParse->pNewTable;
114464   if( pTable==0 ) return;
114465   assert( 0==pTable->pIndex );
114466
114467   db = pParse->db;
114468   iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
114469   assert( iDb>=0 );
114470
114471   pTable->tabFlags |= TF_Virtual;
114472   pTable->nModuleArg = 0;
114473   addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
114474   addModuleArgument(db, pTable, 0);
114475   addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
114476   assert( (pParse->sNameToken.z==pName2->z && pName2->z!=0)
114477        || (pParse->sNameToken.z==pName1->z && pName2->z==0)
114478   );
114479   pParse->sNameToken.n = (int)(
114480       &pModuleName->z[pModuleName->n] - pParse->sNameToken.z
114481   );
114482
114483 #ifndef SQLITE_OMIT_AUTHORIZATION
114484   /* Creating a virtual table invokes the authorization callback twice.
114485   ** The first invocation, to obtain permission to INSERT a row into the
114486   ** sqlite_master table, has already been made by sqlite3StartTable().
114487   ** The second call, to obtain permission to create the table, is made now.
114488   */
114489   if( pTable->azModuleArg ){
114490     sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName, 
114491             pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
114492   }
114493 #endif
114494 }
114495
114496 /*
114497 ** This routine takes the module argument that has been accumulating
114498 ** in pParse->zArg[] and appends it to the list of arguments on the
114499 ** virtual table currently under construction in pParse->pTable.
114500 */
114501 static void addArgumentToVtab(Parse *pParse){
114502   if( pParse->sArg.z && pParse->pNewTable ){
114503     const char *z = (const char*)pParse->sArg.z;
114504     int n = pParse->sArg.n;
114505     sqlite3 *db = pParse->db;
114506     addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
114507   }
114508 }
114509
114510 /*
114511 ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
114512 ** has been completely parsed.
114513 */
114514 SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
114515   Table *pTab = pParse->pNewTable;  /* The table being constructed */
114516   sqlite3 *db = pParse->db;         /* The database connection */
114517
114518   if( pTab==0 ) return;
114519   addArgumentToVtab(pParse);
114520   pParse->sArg.z = 0;
114521   if( pTab->nModuleArg<1 ) return;
114522   
114523   /* If the CREATE VIRTUAL TABLE statement is being entered for the
114524   ** first time (in other words if the virtual table is actually being
114525   ** created now instead of just being read out of sqlite_master) then
114526   ** do additional initialization work and store the statement text
114527   ** in the sqlite_master table.
114528   */
114529   if( !db->init.busy ){
114530     char *zStmt;
114531     char *zWhere;
114532     int iDb;
114533     int iReg;
114534     Vdbe *v;
114535
114536     /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
114537     if( pEnd ){
114538       pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
114539     }
114540     zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
114541
114542     /* A slot for the record has already been allocated in the 
114543     ** SQLITE_MASTER table.  We just need to update that slot with all
114544     ** the information we've collected.  
114545     **
114546     ** The VM register number pParse->regRowid holds the rowid of an
114547     ** entry in the sqlite_master table tht was created for this vtab
114548     ** by sqlite3StartTable().
114549     */
114550     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
114551     sqlite3NestedParse(pParse,
114552       "UPDATE %Q.%s "
114553          "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
114554        "WHERE rowid=#%d",
114555       db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
114556       pTab->zName,
114557       pTab->zName,
114558       zStmt,
114559       pParse->regRowid
114560     );
114561     sqlite3DbFree(db, zStmt);
114562     v = sqlite3GetVdbe(pParse);
114563     sqlite3ChangeCookie(pParse, iDb);
114564
114565     sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
114566     zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
114567     sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
114568
114569     iReg = ++pParse->nMem;
114570     sqlite3VdbeAddOp4(v, OP_String8, 0, iReg, 0, pTab->zName, 0);
114571     sqlite3VdbeAddOp2(v, OP_VCreate, iDb, iReg);
114572   }
114573
114574   /* If we are rereading the sqlite_master table create the in-memory
114575   ** record of the table. The xConnect() method is not called until
114576   ** the first time the virtual table is used in an SQL statement. This
114577   ** allows a schema that contains virtual tables to be loaded before
114578   ** the required virtual table implementations are registered.  */
114579   else {
114580     Table *pOld;
114581     Schema *pSchema = pTab->pSchema;
114582     const char *zName = pTab->zName;
114583     assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
114584     pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
114585     if( pOld ){
114586       db->mallocFailed = 1;
114587       assert( pTab==pOld );  /* Malloc must have failed inside HashInsert() */
114588       return;
114589     }
114590     pParse->pNewTable = 0;
114591   }
114592 }
114593
114594 /*
114595 ** The parser calls this routine when it sees the first token
114596 ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
114597 */
114598 SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
114599   addArgumentToVtab(pParse);
114600   pParse->sArg.z = 0;
114601   pParse->sArg.n = 0;
114602 }
114603
114604 /*
114605 ** The parser calls this routine for each token after the first token
114606 ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
114607 */
114608 SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
114609   Token *pArg = &pParse->sArg;
114610   if( pArg->z==0 ){
114611     pArg->z = p->z;
114612     pArg->n = p->n;
114613   }else{
114614     assert(pArg->z < p->z);
114615     pArg->n = (int)(&p->z[p->n] - pArg->z);
114616   }
114617 }
114618
114619 /*
114620 ** Invoke a virtual table constructor (either xCreate or xConnect). The
114621 ** pointer to the function to invoke is passed as the fourth parameter
114622 ** to this procedure.
114623 */
114624 static int vtabCallConstructor(
114625   sqlite3 *db, 
114626   Table *pTab,
114627   Module *pMod,
114628   int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
114629   char **pzErr
114630 ){
114631   VtabCtx sCtx, *pPriorCtx;
114632   VTable *pVTable;
114633   int rc;
114634   const char *const*azArg = (const char *const*)pTab->azModuleArg;
114635   int nArg = pTab->nModuleArg;
114636   char *zErr = 0;
114637   char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
114638   int iDb;
114639
114640   if( !zModuleName ){
114641     return SQLITE_NOMEM;
114642   }
114643
114644   pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
114645   if( !pVTable ){
114646     sqlite3DbFree(db, zModuleName);
114647     return SQLITE_NOMEM;
114648   }
114649   pVTable->db = db;
114650   pVTable->pMod = pMod;
114651
114652   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
114653   pTab->azModuleArg[1] = db->aDb[iDb].zName;
114654
114655   /* Invoke the virtual table constructor */
114656   assert( &db->pVtabCtx );
114657   assert( xConstruct );
114658   sCtx.pTab = pTab;
114659   sCtx.pVTable = pVTable;
114660   pPriorCtx = db->pVtabCtx;
114661   db->pVtabCtx = &sCtx;
114662   rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
114663   db->pVtabCtx = pPriorCtx;
114664   if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
114665
114666   if( SQLITE_OK!=rc ){
114667     if( zErr==0 ){
114668       *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
114669     }else {
114670       *pzErr = sqlite3MPrintf(db, "%s", zErr);
114671       sqlite3_free(zErr);
114672     }
114673     sqlite3DbFree(db, pVTable);
114674   }else if( ALWAYS(pVTable->pVtab) ){
114675     /* Justification of ALWAYS():  A correct vtab constructor must allocate
114676     ** the sqlite3_vtab object if successful.  */
114677     memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
114678     pVTable->pVtab->pModule = pMod->pModule;
114679     pVTable->nRef = 1;
114680     if( sCtx.pTab ){
114681       const char *zFormat = "vtable constructor did not declare schema: %s";
114682       *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
114683       sqlite3VtabUnlock(pVTable);
114684       rc = SQLITE_ERROR;
114685     }else{
114686       int iCol;
114687       /* If everything went according to plan, link the new VTable structure
114688       ** into the linked list headed by pTab->pVTable. Then loop through the 
114689       ** columns of the table to see if any of them contain the token "hidden".
114690       ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
114691       ** the type string.  */
114692       pVTable->pNext = pTab->pVTable;
114693       pTab->pVTable = pVTable;
114694
114695       for(iCol=0; iCol<pTab->nCol; iCol++){
114696         char *zType = pTab->aCol[iCol].zType;
114697         int nType;
114698         int i = 0;
114699         if( !zType ) continue;
114700         nType = sqlite3Strlen30(zType);
114701         if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
114702           for(i=0; i<nType; i++){
114703             if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
114704              && (zType[i+7]=='\0' || zType[i+7]==' ')
114705             ){
114706               i++;
114707               break;
114708             }
114709           }
114710         }
114711         if( i<nType ){
114712           int j;
114713           int nDel = 6 + (zType[i+6] ? 1 : 0);
114714           for(j=i; (j+nDel)<=nType; j++){
114715             zType[j] = zType[j+nDel];
114716           }
114717           if( zType[i]=='\0' && i>0 ){
114718             assert(zType[i-1]==' ');
114719             zType[i-1] = '\0';
114720           }
114721           pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
114722         }
114723       }
114724     }
114725   }
114726
114727   sqlite3DbFree(db, zModuleName);
114728   return rc;
114729 }
114730
114731 /*
114732 ** This function is invoked by the parser to call the xConnect() method
114733 ** of the virtual table pTab. If an error occurs, an error code is returned 
114734 ** and an error left in pParse.
114735 **
114736 ** This call is a no-op if table pTab is not a virtual table.
114737 */
114738 SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
114739   sqlite3 *db = pParse->db;
114740   const char *zMod;
114741   Module *pMod;
114742   int rc;
114743
114744   assert( pTab );
114745   if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
114746     return SQLITE_OK;
114747   }
114748
114749   /* Locate the required virtual table module */
114750   zMod = pTab->azModuleArg[0];
114751   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
114752
114753   if( !pMod ){
114754     const char *zModule = pTab->azModuleArg[0];
114755     sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
114756     rc = SQLITE_ERROR;
114757   }else{
114758     char *zErr = 0;
114759     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
114760     if( rc!=SQLITE_OK ){
114761       sqlite3ErrorMsg(pParse, "%s", zErr);
114762     }
114763     sqlite3DbFree(db, zErr);
114764   }
114765
114766   return rc;
114767 }
114768 /*
114769 ** Grow the db->aVTrans[] array so that there is room for at least one
114770 ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
114771 */
114772 static int growVTrans(sqlite3 *db){
114773   const int ARRAY_INCR = 5;
114774
114775   /* Grow the sqlite3.aVTrans array if required */
114776   if( (db->nVTrans%ARRAY_INCR)==0 ){
114777     VTable **aVTrans;
114778     int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
114779     aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
114780     if( !aVTrans ){
114781       return SQLITE_NOMEM;
114782     }
114783     memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
114784     db->aVTrans = aVTrans;
114785   }
114786
114787   return SQLITE_OK;
114788 }
114789
114790 /*
114791 ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
114792 ** have already been reserved using growVTrans().
114793 */
114794 static void addToVTrans(sqlite3 *db, VTable *pVTab){
114795   /* Add pVtab to the end of sqlite3.aVTrans */
114796   db->aVTrans[db->nVTrans++] = pVTab;
114797   sqlite3VtabLock(pVTab);
114798 }
114799
114800 /*
114801 ** This function is invoked by the vdbe to call the xCreate method
114802 ** of the virtual table named zTab in database iDb. 
114803 **
114804 ** If an error occurs, *pzErr is set to point an an English language
114805 ** description of the error and an SQLITE_XXX error code is returned.
114806 ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
114807 */
114808 SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
114809   int rc = SQLITE_OK;
114810   Table *pTab;
114811   Module *pMod;
114812   const char *zMod;
114813
114814   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
114815   assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
114816
114817   /* Locate the required virtual table module */
114818   zMod = pTab->azModuleArg[0];
114819   pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
114820
114821   /* If the module has been registered and includes a Create method, 
114822   ** invoke it now. If the module has not been registered, return an 
114823   ** error. Otherwise, do nothing.
114824   */
114825   if( !pMod ){
114826     *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
114827     rc = SQLITE_ERROR;
114828   }else{
114829     rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
114830   }
114831
114832   /* Justification of ALWAYS():  The xConstructor method is required to
114833   ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
114834   if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
114835     rc = growVTrans(db);
114836     if( rc==SQLITE_OK ){
114837       addToVTrans(db, sqlite3GetVTable(db, pTab));
114838     }
114839   }
114840
114841   return rc;
114842 }
114843
114844 /*
114845 ** This function is used to set the schema of a virtual table.  It is only
114846 ** valid to call this function from within the xCreate() or xConnect() of a
114847 ** virtual table module.
114848 */
114849 SQLITE_API int SQLITE_STDCALL sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
114850   Parse *pParse;
114851
114852   int rc = SQLITE_OK;
114853   Table *pTab;
114854   char *zErr = 0;
114855
114856 #ifdef SQLITE_ENABLE_API_ARMOR
114857   if( !sqlite3SafetyCheckOk(db) || zCreateTable==0 ){
114858     return SQLITE_MISUSE_BKPT;
114859   }
114860 #endif
114861   sqlite3_mutex_enter(db->mutex);
114862   if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
114863     sqlite3Error(db, SQLITE_MISUSE);
114864     sqlite3_mutex_leave(db->mutex);
114865     return SQLITE_MISUSE_BKPT;
114866   }
114867   assert( (pTab->tabFlags & TF_Virtual)!=0 );
114868
114869   pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
114870   if( pParse==0 ){
114871     rc = SQLITE_NOMEM;
114872   }else{
114873     pParse->declareVtab = 1;
114874     pParse->db = db;
114875     pParse->nQueryLoop = 1;
114876   
114877     if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr) 
114878      && pParse->pNewTable
114879      && !db->mallocFailed
114880      && !pParse->pNewTable->pSelect
114881      && (pParse->pNewTable->tabFlags & TF_Virtual)==0
114882     ){
114883       if( !pTab->aCol ){
114884         pTab->aCol = pParse->pNewTable->aCol;
114885         pTab->nCol = pParse->pNewTable->nCol;
114886         pParse->pNewTable->nCol = 0;
114887         pParse->pNewTable->aCol = 0;
114888       }
114889       db->pVtabCtx->pTab = 0;
114890     }else{
114891       sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
114892       sqlite3DbFree(db, zErr);
114893       rc = SQLITE_ERROR;
114894     }
114895     pParse->declareVtab = 0;
114896   
114897     if( pParse->pVdbe ){
114898       sqlite3VdbeFinalize(pParse->pVdbe);
114899     }
114900     sqlite3DeleteTable(db, pParse->pNewTable);
114901     sqlite3ParserReset(pParse);
114902     sqlite3StackFree(db, pParse);
114903   }
114904
114905   assert( (rc&0xff)==rc );
114906   rc = sqlite3ApiExit(db, rc);
114907   sqlite3_mutex_leave(db->mutex);
114908   return rc;
114909 }
114910
114911 /*
114912 ** This function is invoked by the vdbe to call the xDestroy method
114913 ** of the virtual table named zTab in database iDb. This occurs
114914 ** when a DROP TABLE is mentioned.
114915 **
114916 ** This call is a no-op if zTab is not a virtual table.
114917 */
114918 SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
114919   int rc = SQLITE_OK;
114920   Table *pTab;
114921
114922   pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
114923   if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
114924     VTable *p;
114925     for(p=pTab->pVTable; p; p=p->pNext){
114926       assert( p->pVtab );
114927       if( p->pVtab->nRef>0 ){
114928         return SQLITE_LOCKED;
114929       }
114930     }
114931     p = vtabDisconnectAll(db, pTab);
114932     rc = p->pMod->pModule->xDestroy(p->pVtab);
114933     /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
114934     if( rc==SQLITE_OK ){
114935       assert( pTab->pVTable==p && p->pNext==0 );
114936       p->pVtab = 0;
114937       pTab->pVTable = 0;
114938       sqlite3VtabUnlock(p);
114939     }
114940   }
114941
114942   return rc;
114943 }
114944
114945 /*
114946 ** This function invokes either the xRollback or xCommit method
114947 ** of each of the virtual tables in the sqlite3.aVTrans array. The method
114948 ** called is identified by the second argument, "offset", which is
114949 ** the offset of the method to call in the sqlite3_module structure.
114950 **
114951 ** The array is cleared after invoking the callbacks. 
114952 */
114953 static void callFinaliser(sqlite3 *db, int offset){
114954   int i;
114955   if( db->aVTrans ){
114956     for(i=0; i<db->nVTrans; i++){
114957       VTable *pVTab = db->aVTrans[i];
114958       sqlite3_vtab *p = pVTab->pVtab;
114959       if( p ){
114960         int (*x)(sqlite3_vtab *);
114961         x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
114962         if( x ) x(p);
114963       }
114964       pVTab->iSavepoint = 0;
114965       sqlite3VtabUnlock(pVTab);
114966     }
114967     sqlite3DbFree(db, db->aVTrans);
114968     db->nVTrans = 0;
114969     db->aVTrans = 0;
114970   }
114971 }
114972
114973 /*
114974 ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
114975 ** array. Return the error code for the first error that occurs, or
114976 ** SQLITE_OK if all xSync operations are successful.
114977 **
114978 ** If an error message is available, leave it in p->zErrMsg.
114979 */
114980 SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
114981   int i;
114982   int rc = SQLITE_OK;
114983   VTable **aVTrans = db->aVTrans;
114984
114985   db->aVTrans = 0;
114986   for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
114987     int (*x)(sqlite3_vtab *);
114988     sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
114989     if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
114990       rc = x(pVtab);
114991       sqlite3VtabImportErrmsg(p, pVtab);
114992     }
114993   }
114994   db->aVTrans = aVTrans;
114995   return rc;
114996 }
114997
114998 /*
114999 ** Invoke the xRollback method of all virtual tables in the 
115000 ** sqlite3.aVTrans array. Then clear the array itself.
115001 */
115002 SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
115003   callFinaliser(db, offsetof(sqlite3_module,xRollback));
115004   return SQLITE_OK;
115005 }
115006
115007 /*
115008 ** Invoke the xCommit method of all virtual tables in the 
115009 ** sqlite3.aVTrans array. Then clear the array itself.
115010 */
115011 SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
115012   callFinaliser(db, offsetof(sqlite3_module,xCommit));
115013   return SQLITE_OK;
115014 }
115015
115016 /*
115017 ** If the virtual table pVtab supports the transaction interface
115018 ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
115019 ** not currently open, invoke the xBegin method now.
115020 **
115021 ** If the xBegin call is successful, place the sqlite3_vtab pointer
115022 ** in the sqlite3.aVTrans array.
115023 */
115024 SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
115025   int rc = SQLITE_OK;
115026   const sqlite3_module *pModule;
115027
115028   /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
115029   ** than zero, then this function is being called from within a
115030   ** virtual module xSync() callback. It is illegal to write to 
115031   ** virtual module tables in this case, so return SQLITE_LOCKED.
115032   */
115033   if( sqlite3VtabInSync(db) ){
115034     return SQLITE_LOCKED;
115035   }
115036   if( !pVTab ){
115037     return SQLITE_OK;
115038   } 
115039   pModule = pVTab->pVtab->pModule;
115040
115041   if( pModule->xBegin ){
115042     int i;
115043
115044     /* If pVtab is already in the aVTrans array, return early */
115045     for(i=0; i<db->nVTrans; i++){
115046       if( db->aVTrans[i]==pVTab ){
115047         return SQLITE_OK;
115048       }
115049     }
115050
115051     /* Invoke the xBegin method. If successful, add the vtab to the 
115052     ** sqlite3.aVTrans[] array. */
115053     rc = growVTrans(db);
115054     if( rc==SQLITE_OK ){
115055       rc = pModule->xBegin(pVTab->pVtab);
115056       if( rc==SQLITE_OK ){
115057         addToVTrans(db, pVTab);
115058       }
115059     }
115060   }
115061   return rc;
115062 }
115063
115064 /*
115065 ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
115066 ** virtual tables that currently have an open transaction. Pass iSavepoint
115067 ** as the second argument to the virtual table method invoked.
115068 **
115069 ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
115070 ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is 
115071 ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
115072 ** an open transaction is invoked.
115073 **
115074 ** If any virtual table method returns an error code other than SQLITE_OK, 
115075 ** processing is abandoned and the error returned to the caller of this
115076 ** function immediately. If all calls to virtual table methods are successful,
115077 ** SQLITE_OK is returned.
115078 */
115079 SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
115080   int rc = SQLITE_OK;
115081
115082   assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
115083   assert( iSavepoint>=0 );
115084   if( db->aVTrans ){
115085     int i;
115086     for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
115087       VTable *pVTab = db->aVTrans[i];
115088       const sqlite3_module *pMod = pVTab->pMod->pModule;
115089       if( pVTab->pVtab && pMod->iVersion>=2 ){
115090         int (*xMethod)(sqlite3_vtab *, int);
115091         switch( op ){
115092           case SAVEPOINT_BEGIN:
115093             xMethod = pMod->xSavepoint;
115094             pVTab->iSavepoint = iSavepoint+1;
115095             break;
115096           case SAVEPOINT_ROLLBACK:
115097             xMethod = pMod->xRollbackTo;
115098             break;
115099           default:
115100             xMethod = pMod->xRelease;
115101             break;
115102         }
115103         if( xMethod && pVTab->iSavepoint>iSavepoint ){
115104           rc = xMethod(pVTab->pVtab, iSavepoint);
115105         }
115106       }
115107     }
115108   }
115109   return rc;
115110 }
115111
115112 /*
115113 ** The first parameter (pDef) is a function implementation.  The
115114 ** second parameter (pExpr) is the first argument to this function.
115115 ** If pExpr is a column in a virtual table, then let the virtual
115116 ** table implementation have an opportunity to overload the function.
115117 **
115118 ** This routine is used to allow virtual table implementations to
115119 ** overload MATCH, LIKE, GLOB, and REGEXP operators.
115120 **
115121 ** Return either the pDef argument (indicating no change) or a 
115122 ** new FuncDef structure that is marked as ephemeral using the
115123 ** SQLITE_FUNC_EPHEM flag.
115124 */
115125 SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
115126   sqlite3 *db,    /* Database connection for reporting malloc problems */
115127   FuncDef *pDef,  /* Function to possibly overload */
115128   int nArg,       /* Number of arguments to the function */
115129   Expr *pExpr     /* First argument to the function */
115130 ){
115131   Table *pTab;
115132   sqlite3_vtab *pVtab;
115133   sqlite3_module *pMod;
115134   void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
115135   void *pArg = 0;
115136   FuncDef *pNew;
115137   int rc = 0;
115138   char *zLowerName;
115139   unsigned char *z;
115140
115141
115142   /* Check to see the left operand is a column in a virtual table */
115143   if( NEVER(pExpr==0) ) return pDef;
115144   if( pExpr->op!=TK_COLUMN ) return pDef;
115145   pTab = pExpr->pTab;
115146   if( NEVER(pTab==0) ) return pDef;
115147   if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
115148   pVtab = sqlite3GetVTable(db, pTab)->pVtab;
115149   assert( pVtab!=0 );
115150   assert( pVtab->pModule!=0 );
115151   pMod = (sqlite3_module *)pVtab->pModule;
115152   if( pMod->xFindFunction==0 ) return pDef;
115153  
115154   /* Call the xFindFunction method on the virtual table implementation
115155   ** to see if the implementation wants to overload this function 
115156   */
115157   zLowerName = sqlite3DbStrDup(db, pDef->zName);
115158   if( zLowerName ){
115159     for(z=(unsigned char*)zLowerName; *z; z++){
115160       *z = sqlite3UpperToLower[*z];
115161     }
115162     rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
115163     sqlite3DbFree(db, zLowerName);
115164   }
115165   if( rc==0 ){
115166     return pDef;
115167   }
115168
115169   /* Create a new ephemeral function definition for the overloaded
115170   ** function */
115171   pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
115172                              + sqlite3Strlen30(pDef->zName) + 1);
115173   if( pNew==0 ){
115174     return pDef;
115175   }
115176   *pNew = *pDef;
115177   pNew->zName = (char *)&pNew[1];
115178   memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
115179   pNew->xFunc = xFunc;
115180   pNew->pUserData = pArg;
115181   pNew->funcFlags |= SQLITE_FUNC_EPHEM;
115182   return pNew;
115183 }
115184
115185 /*
115186 ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
115187 ** array so that an OP_VBegin will get generated for it.  Add pTab to the
115188 ** array if it is missing.  If pTab is already in the array, this routine
115189 ** is a no-op.
115190 */
115191 SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
115192   Parse *pToplevel = sqlite3ParseToplevel(pParse);
115193   int i, n;
115194   Table **apVtabLock;
115195
115196   assert( IsVirtual(pTab) );
115197   for(i=0; i<pToplevel->nVtabLock; i++){
115198     if( pTab==pToplevel->apVtabLock[i] ) return;
115199   }
115200   n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
115201   apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
115202   if( apVtabLock ){
115203     pToplevel->apVtabLock = apVtabLock;
115204     pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
115205   }else{
115206     pToplevel->db->mallocFailed = 1;
115207   }
115208 }
115209
115210 /*
115211 ** Return the ON CONFLICT resolution mode in effect for the virtual
115212 ** table update operation currently in progress.
115213 **
115214 ** The results of this routine are undefined unless it is called from
115215 ** within an xUpdate method.
115216 */
115217 SQLITE_API int SQLITE_STDCALL sqlite3_vtab_on_conflict(sqlite3 *db){
115218   static const unsigned char aMap[] = { 
115219     SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE 
115220   };
115221 #ifdef SQLITE_ENABLE_API_ARMOR
115222   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
115223 #endif
115224   assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
115225   assert( OE_Ignore==4 && OE_Replace==5 );
115226   assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
115227   return (int)aMap[db->vtabOnConflict-1];
115228 }
115229
115230 /*
115231 ** Call from within the xCreate() or xConnect() methods to provide 
115232 ** the SQLite core with additional information about the behavior
115233 ** of the virtual table being implemented.
115234 */
115235 SQLITE_API int SQLITE_CDECL sqlite3_vtab_config(sqlite3 *db, int op, ...){
115236   va_list ap;
115237   int rc = SQLITE_OK;
115238
115239 #ifdef SQLITE_ENABLE_API_ARMOR
115240   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
115241 #endif
115242   sqlite3_mutex_enter(db->mutex);
115243   va_start(ap, op);
115244   switch( op ){
115245     case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
115246       VtabCtx *p = db->pVtabCtx;
115247       if( !p ){
115248         rc = SQLITE_MISUSE_BKPT;
115249       }else{
115250         assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
115251         p->pVTable->bConstraint = (u8)va_arg(ap, int);
115252       }
115253       break;
115254     }
115255     default:
115256       rc = SQLITE_MISUSE_BKPT;
115257       break;
115258   }
115259   va_end(ap);
115260
115261   if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
115262   sqlite3_mutex_leave(db->mutex);
115263   return rc;
115264 }
115265
115266 #endif /* SQLITE_OMIT_VIRTUALTABLE */
115267
115268 /************** End of vtab.c ************************************************/
115269 /************** Begin file where.c *******************************************/
115270 /*
115271 ** 2001 September 15
115272 **
115273 ** The author disclaims copyright to this source code.  In place of
115274 ** a legal notice, here is a blessing:
115275 **
115276 **    May you do good and not evil.
115277 **    May you find forgiveness for yourself and forgive others.
115278 **    May you share freely, never taking more than you give.
115279 **
115280 *************************************************************************
115281 ** This module contains C code that generates VDBE code used to process
115282 ** the WHERE clause of SQL statements.  This module is responsible for
115283 ** generating the code that loops through a table looking for applicable
115284 ** rows.  Indices are selected and used to speed the search when doing
115285 ** so is applicable.  Because this module is responsible for selecting
115286 ** indices, you might also think of this module as the "query optimizer".
115287 */
115288 /************** Include whereInt.h in the middle of where.c ******************/
115289 /************** Begin file whereInt.h ****************************************/
115290 /*
115291 ** 2013-11-12
115292 **
115293 ** The author disclaims copyright to this source code.  In place of
115294 ** a legal notice, here is a blessing:
115295 **
115296 **    May you do good and not evil.
115297 **    May you find forgiveness for yourself and forgive others.
115298 **    May you share freely, never taking more than you give.
115299 **
115300 *************************************************************************
115301 **
115302 ** This file contains structure and macro definitions for the query
115303 ** planner logic in "where.c".  These definitions are broken out into
115304 ** a separate source file for easier editing.
115305 */
115306
115307 /*
115308 ** Trace output macros
115309 */
115310 #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
115311 /***/ int sqlite3WhereTrace = 0;
115312 #endif
115313 #if defined(SQLITE_DEBUG) \
115314     && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
115315 # define WHERETRACE(K,X)  if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
115316 # define WHERETRACE_ENABLED 1
115317 #else
115318 # define WHERETRACE(K,X)
115319 #endif
115320
115321 /* Forward references
115322 */
115323 typedef struct WhereClause WhereClause;
115324 typedef struct WhereMaskSet WhereMaskSet;
115325 typedef struct WhereOrInfo WhereOrInfo;
115326 typedef struct WhereAndInfo WhereAndInfo;
115327 typedef struct WhereLevel WhereLevel;
115328 typedef struct WhereLoop WhereLoop;
115329 typedef struct WherePath WherePath;
115330 typedef struct WhereTerm WhereTerm;
115331 typedef struct WhereLoopBuilder WhereLoopBuilder;
115332 typedef struct WhereScan WhereScan;
115333 typedef struct WhereOrCost WhereOrCost;
115334 typedef struct WhereOrSet WhereOrSet;
115335
115336 /*
115337 ** This object contains information needed to implement a single nested
115338 ** loop in WHERE clause.
115339 **
115340 ** Contrast this object with WhereLoop.  This object describes the
115341 ** implementation of the loop.  WhereLoop describes the algorithm.
115342 ** This object contains a pointer to the WhereLoop algorithm as one of
115343 ** its elements.
115344 **
115345 ** The WhereInfo object contains a single instance of this object for
115346 ** each term in the FROM clause (which is to say, for each of the
115347 ** nested loops as implemented).  The order of WhereLevel objects determines
115348 ** the loop nested order, with WhereInfo.a[0] being the outer loop and
115349 ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
115350 */
115351 struct WhereLevel {
115352   int iLeftJoin;        /* Memory cell used to implement LEFT OUTER JOIN */
115353   int iTabCur;          /* The VDBE cursor used to access the table */
115354   int iIdxCur;          /* The VDBE cursor used to access pIdx */
115355   int addrBrk;          /* Jump here to break out of the loop */
115356   int addrNxt;          /* Jump here to start the next IN combination */
115357   int addrSkip;         /* Jump here for next iteration of skip-scan */
115358   int addrCont;         /* Jump here to continue with the next loop cycle */
115359   int addrFirst;        /* First instruction of interior of the loop */
115360   int addrBody;         /* Beginning of the body of this loop */
115361   int iLikeRepCntr;     /* LIKE range processing counter register */
115362   int addrLikeRep;      /* LIKE range processing address */
115363   u8 iFrom;             /* Which entry in the FROM clause */
115364   u8 op, p3, p5;        /* Opcode, P3 & P5 of the opcode that ends the loop */
115365   int p1, p2;           /* Operands of the opcode used to ends the loop */
115366   union {               /* Information that depends on pWLoop->wsFlags */
115367     struct {
115368       int nIn;              /* Number of entries in aInLoop[] */
115369       struct InLoop {
115370         int iCur;              /* The VDBE cursor used by this IN operator */
115371         int addrInTop;         /* Top of the IN loop */
115372         u8 eEndLoopOp;         /* IN Loop terminator. OP_Next or OP_Prev */
115373       } *aInLoop;           /* Information about each nested IN operator */
115374     } in;                 /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
115375     Index *pCovidx;       /* Possible covering index for WHERE_MULTI_OR */
115376   } u;
115377   struct WhereLoop *pWLoop;  /* The selected WhereLoop object */
115378   Bitmask notReady;          /* FROM entries not usable at this level */
115379 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
115380   int addrVisit;        /* Address at which row is visited */
115381 #endif
115382 };
115383
115384 /*
115385 ** Each instance of this object represents an algorithm for evaluating one
115386 ** term of a join.  Every term of the FROM clause will have at least
115387 ** one corresponding WhereLoop object (unless INDEXED BY constraints
115388 ** prevent a query solution - which is an error) and many terms of the
115389 ** FROM clause will have multiple WhereLoop objects, each describing a
115390 ** potential way of implementing that FROM-clause term, together with
115391 ** dependencies and cost estimates for using the chosen algorithm.
115392 **
115393 ** Query planning consists of building up a collection of these WhereLoop
115394 ** objects, then computing a particular sequence of WhereLoop objects, with
115395 ** one WhereLoop object per FROM clause term, that satisfy all dependencies
115396 ** and that minimize the overall cost.
115397 */
115398 struct WhereLoop {
115399   Bitmask prereq;       /* Bitmask of other loops that must run first */
115400   Bitmask maskSelf;     /* Bitmask identifying table iTab */
115401 #ifdef SQLITE_DEBUG
115402   char cId;             /* Symbolic ID of this loop for debugging use */
115403 #endif
115404   u8 iTab;              /* Position in FROM clause of table for this loop */
115405   u8 iSortIdx;          /* Sorting index number.  0==None */
115406   LogEst rSetup;        /* One-time setup cost (ex: create transient index) */
115407   LogEst rRun;          /* Cost of running each loop */
115408   LogEst nOut;          /* Estimated number of output rows */
115409   union {
115410     struct {               /* Information for internal btree tables */
115411       u16 nEq;               /* Number of equality constraints */
115412       Index *pIndex;         /* Index used, or NULL */
115413     } btree;
115414     struct {               /* Information for virtual tables */
115415       int idxNum;            /* Index number */
115416       u8 needFree;           /* True if sqlite3_free(idxStr) is needed */
115417       i8 isOrdered;          /* True if satisfies ORDER BY */
115418       u16 omitMask;          /* Terms that may be omitted */
115419       char *idxStr;          /* Index identifier string */
115420     } vtab;
115421   } u;
115422   u32 wsFlags;          /* WHERE_* flags describing the plan */
115423   u16 nLTerm;           /* Number of entries in aLTerm[] */
115424   u16 nSkip;            /* Number of NULL aLTerm[] entries */
115425   /**** whereLoopXfer() copies fields above ***********************/
115426 # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
115427   u16 nLSlot;           /* Number of slots allocated for aLTerm[] */
115428   WhereTerm **aLTerm;   /* WhereTerms used */
115429   WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
115430   WhereTerm *aLTermSpace[3];  /* Initial aLTerm[] space */
115431 };
115432
115433 /* This object holds the prerequisites and the cost of running a
115434 ** subquery on one operand of an OR operator in the WHERE clause.
115435 ** See WhereOrSet for additional information 
115436 */
115437 struct WhereOrCost {
115438   Bitmask prereq;     /* Prerequisites */
115439   LogEst rRun;        /* Cost of running this subquery */
115440   LogEst nOut;        /* Number of outputs for this subquery */
115441 };
115442
115443 /* The WhereOrSet object holds a set of possible WhereOrCosts that
115444 ** correspond to the subquery(s) of OR-clause processing.  Only the
115445 ** best N_OR_COST elements are retained.
115446 */
115447 #define N_OR_COST 3
115448 struct WhereOrSet {
115449   u16 n;                      /* Number of valid a[] entries */
115450   WhereOrCost a[N_OR_COST];   /* Set of best costs */
115451 };
115452
115453
115454 /* Forward declaration of methods */
115455 static int whereLoopResize(sqlite3*, WhereLoop*, int);
115456
115457 /*
115458 ** Each instance of this object holds a sequence of WhereLoop objects
115459 ** that implement some or all of a query plan.
115460 **
115461 ** Think of each WhereLoop object as a node in a graph with arcs
115462 ** showing dependencies and costs for travelling between nodes.  (That is
115463 ** not a completely accurate description because WhereLoop costs are a
115464 ** vector, not a scalar, and because dependencies are many-to-one, not
115465 ** one-to-one as are graph nodes.  But it is a useful visualization aid.)
115466 ** Then a WherePath object is a path through the graph that visits some
115467 ** or all of the WhereLoop objects once.
115468 **
115469 ** The "solver" works by creating the N best WherePath objects of length
115470 ** 1.  Then using those as a basis to compute the N best WherePath objects
115471 ** of length 2.  And so forth until the length of WherePaths equals the
115472 ** number of nodes in the FROM clause.  The best (lowest cost) WherePath
115473 ** at the end is the chosen query plan.
115474 */
115475 struct WherePath {
115476   Bitmask maskLoop;     /* Bitmask of all WhereLoop objects in this path */
115477   Bitmask revLoop;      /* aLoop[]s that should be reversed for ORDER BY */
115478   LogEst nRow;          /* Estimated number of rows generated by this path */
115479   LogEst rCost;         /* Total cost of this path */
115480   LogEst rUnsorted;     /* Total cost of this path ignoring sorting costs */
115481   i8 isOrdered;         /* No. of ORDER BY terms satisfied. -1 for unknown */
115482   WhereLoop **aLoop;    /* Array of WhereLoop objects implementing this path */
115483 };
115484
115485 /*
115486 ** The query generator uses an array of instances of this structure to
115487 ** help it analyze the subexpressions of the WHERE clause.  Each WHERE
115488 ** clause subexpression is separated from the others by AND operators,
115489 ** usually, or sometimes subexpressions separated by OR.
115490 **
115491 ** All WhereTerms are collected into a single WhereClause structure.  
115492 ** The following identity holds:
115493 **
115494 **        WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
115495 **
115496 ** When a term is of the form:
115497 **
115498 **              X <op> <expr>
115499 **
115500 ** where X is a column name and <op> is one of certain operators,
115501 ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
115502 ** cursor number and column number for X.  WhereTerm.eOperator records
115503 ** the <op> using a bitmask encoding defined by WO_xxx below.  The
115504 ** use of a bitmask encoding for the operator allows us to search
115505 ** quickly for terms that match any of several different operators.
115506 **
115507 ** A WhereTerm might also be two or more subterms connected by OR:
115508 **
115509 **         (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
115510 **
115511 ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
115512 ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
115513 ** is collected about the OR clause.
115514 **
115515 ** If a term in the WHERE clause does not match either of the two previous
115516 ** categories, then eOperator==0.  The WhereTerm.pExpr field is still set
115517 ** to the original subexpression content and wtFlags is set up appropriately
115518 ** but no other fields in the WhereTerm object are meaningful.
115519 **
115520 ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
115521 ** but they do so indirectly.  A single WhereMaskSet structure translates
115522 ** cursor number into bits and the translated bit is stored in the prereq
115523 ** fields.  The translation is used in order to maximize the number of
115524 ** bits that will fit in a Bitmask.  The VDBE cursor numbers might be
115525 ** spread out over the non-negative integers.  For example, the cursor
115526 ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45.  The WhereMaskSet
115527 ** translates these sparse cursor numbers into consecutive integers
115528 ** beginning with 0 in order to make the best possible use of the available
115529 ** bits in the Bitmask.  So, in the example above, the cursor numbers
115530 ** would be mapped into integers 0 through 7.
115531 **
115532 ** The number of terms in a join is limited by the number of bits
115533 ** in prereqRight and prereqAll.  The default is 64 bits, hence SQLite
115534 ** is only able to process joins with 64 or fewer tables.
115535 */
115536 struct WhereTerm {
115537   Expr *pExpr;            /* Pointer to the subexpression that is this term */
115538   int iParent;            /* Disable pWC->a[iParent] when this term disabled */
115539   int leftCursor;         /* Cursor number of X in "X <op> <expr>" */
115540   union {
115541     int leftColumn;         /* Column number of X in "X <op> <expr>" */
115542     WhereOrInfo *pOrInfo;   /* Extra information if (eOperator & WO_OR)!=0 */
115543     WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
115544   } u;
115545   LogEst truthProb;       /* Probability of truth for this expression */
115546   u16 eOperator;          /* A WO_xx value describing <op> */
115547   u16 wtFlags;            /* TERM_xxx bit flags.  See below */
115548   u8 nChild;              /* Number of children that must disable us */
115549   WhereClause *pWC;       /* The clause this term is part of */
115550   Bitmask prereqRight;    /* Bitmask of tables used by pExpr->pRight */
115551   Bitmask prereqAll;      /* Bitmask of tables referenced by pExpr */
115552 };
115553
115554 /*
115555 ** Allowed values of WhereTerm.wtFlags
115556 */
115557 #define TERM_DYNAMIC    0x01   /* Need to call sqlite3ExprDelete(db, pExpr) */
115558 #define TERM_VIRTUAL    0x02   /* Added by the optimizer.  Do not code */
115559 #define TERM_CODED      0x04   /* This term is already coded */
115560 #define TERM_COPIED     0x08   /* Has a child */
115561 #define TERM_ORINFO     0x10   /* Need to free the WhereTerm.u.pOrInfo object */
115562 #define TERM_ANDINFO    0x20   /* Need to free the WhereTerm.u.pAndInfo obj */
115563 #define TERM_OR_OK      0x40   /* Used during OR-clause processing */
115564 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
115565 #  define TERM_VNULL    0x80   /* Manufactured x>NULL or x<=NULL term */
115566 #else
115567 #  define TERM_VNULL    0x00   /* Disabled if not using stat3 */
115568 #endif
115569 #define TERM_LIKEOPT    0x100  /* Virtual terms from the LIKE optimization */
115570 #define TERM_LIKECOND   0x200  /* Conditionally this LIKE operator term */
115571 #define TERM_LIKE       0x400  /* The original LIKE operator */
115572
115573 /*
115574 ** An instance of the WhereScan object is used as an iterator for locating
115575 ** terms in the WHERE clause that are useful to the query planner.
115576 */
115577 struct WhereScan {
115578   WhereClause *pOrigWC;      /* Original, innermost WhereClause */
115579   WhereClause *pWC;          /* WhereClause currently being scanned */
115580   char *zCollName;           /* Required collating sequence, if not NULL */
115581   char idxaff;               /* Must match this affinity, if zCollName!=NULL */
115582   unsigned char nEquiv;      /* Number of entries in aEquiv[] */
115583   unsigned char iEquiv;      /* Next unused slot in aEquiv[] */
115584   u32 opMask;                /* Acceptable operators */
115585   int k;                     /* Resume scanning at this->pWC->a[this->k] */
115586   int aEquiv[22];            /* Cursor,Column pairs for equivalence classes */
115587 };
115588
115589 /*
115590 ** An instance of the following structure holds all information about a
115591 ** WHERE clause.  Mostly this is a container for one or more WhereTerms.
115592 **
115593 ** Explanation of pOuter:  For a WHERE clause of the form
115594 **
115595 **           a AND ((b AND c) OR (d AND e)) AND f
115596 **
115597 ** There are separate WhereClause objects for the whole clause and for
115598 ** the subclauses "(b AND c)" and "(d AND e)".  The pOuter field of the
115599 ** subclauses points to the WhereClause object for the whole clause.
115600 */
115601 struct WhereClause {
115602   WhereInfo *pWInfo;       /* WHERE clause processing context */
115603   WhereClause *pOuter;     /* Outer conjunction */
115604   u8 op;                   /* Split operator.  TK_AND or TK_OR */
115605   int nTerm;               /* Number of terms */
115606   int nSlot;               /* Number of entries in a[] */
115607   WhereTerm *a;            /* Each a[] describes a term of the WHERE cluase */
115608 #if defined(SQLITE_SMALL_STACK)
115609   WhereTerm aStatic[1];    /* Initial static space for a[] */
115610 #else
115611   WhereTerm aStatic[8];    /* Initial static space for a[] */
115612 #endif
115613 };
115614
115615 /*
115616 ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
115617 ** a dynamically allocated instance of the following structure.
115618 */
115619 struct WhereOrInfo {
115620   WhereClause wc;          /* Decomposition into subterms */
115621   Bitmask indexable;       /* Bitmask of all indexable tables in the clause */
115622 };
115623
115624 /*
115625 ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
115626 ** a dynamically allocated instance of the following structure.
115627 */
115628 struct WhereAndInfo {
115629   WhereClause wc;          /* The subexpression broken out */
115630 };
115631
115632 /*
115633 ** An instance of the following structure keeps track of a mapping
115634 ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
115635 **
115636 ** The VDBE cursor numbers are small integers contained in 
115637 ** SrcList_item.iCursor and Expr.iTable fields.  For any given WHERE 
115638 ** clause, the cursor numbers might not begin with 0 and they might
115639 ** contain gaps in the numbering sequence.  But we want to make maximum
115640 ** use of the bits in our bitmasks.  This structure provides a mapping
115641 ** from the sparse cursor numbers into consecutive integers beginning
115642 ** with 0.
115643 **
115644 ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
115645 ** corresponds VDBE cursor number B.  The A-th bit of a bitmask is 1<<A.
115646 **
115647 ** For example, if the WHERE clause expression used these VDBE
115648 ** cursors:  4, 5, 8, 29, 57, 73.  Then the  WhereMaskSet structure
115649 ** would map those cursor numbers into bits 0 through 5.
115650 **
115651 ** Note that the mapping is not necessarily ordered.  In the example
115652 ** above, the mapping might go like this:  4->3, 5->1, 8->2, 29->0,
115653 ** 57->5, 73->4.  Or one of 719 other combinations might be used. It
115654 ** does not really matter.  What is important is that sparse cursor
115655 ** numbers all get mapped into bit numbers that begin with 0 and contain
115656 ** no gaps.
115657 */
115658 struct WhereMaskSet {
115659   int n;                        /* Number of assigned cursor values */
115660   int ix[BMS];                  /* Cursor assigned to each bit */
115661 };
115662
115663 /*
115664 ** This object is a convenience wrapper holding all information needed
115665 ** to construct WhereLoop objects for a particular query.
115666 */
115667 struct WhereLoopBuilder {
115668   WhereInfo *pWInfo;        /* Information about this WHERE */
115669   WhereClause *pWC;         /* WHERE clause terms */
115670   ExprList *pOrderBy;       /* ORDER BY clause */
115671   WhereLoop *pNew;          /* Template WhereLoop */
115672   WhereOrSet *pOrSet;       /* Record best loops here, if not NULL */
115673 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
115674   UnpackedRecord *pRec;     /* Probe for stat4 (if required) */
115675   int nRecValid;            /* Number of valid fields currently in pRec */
115676 #endif
115677 };
115678
115679 /*
115680 ** The WHERE clause processing routine has two halves.  The
115681 ** first part does the start of the WHERE loop and the second
115682 ** half does the tail of the WHERE loop.  An instance of
115683 ** this structure is returned by the first half and passed
115684 ** into the second half to give some continuity.
115685 **
115686 ** An instance of this object holds the complete state of the query
115687 ** planner.
115688 */
115689 struct WhereInfo {
115690   Parse *pParse;            /* Parsing and code generating context */
115691   SrcList *pTabList;        /* List of tables in the join */
115692   ExprList *pOrderBy;       /* The ORDER BY clause or NULL */
115693   ExprList *pResultSet;     /* Result set. DISTINCT operates on these */
115694   WhereLoop *pLoops;        /* List of all WhereLoop objects */
115695   Bitmask revMask;          /* Mask of ORDER BY terms that need reversing */
115696   LogEst nRowOut;           /* Estimated number of output rows */
115697   u16 wctrlFlags;           /* Flags originally passed to sqlite3WhereBegin() */
115698   i8 nOBSat;                /* Number of ORDER BY terms satisfied by indices */
115699   u8 sorted;                /* True if really sorted (not just grouped) */
115700   u8 okOnePass;             /* Ok to use one-pass algorithm for UPDATE/DELETE */
115701   u8 untestedTerms;         /* Not all WHERE terms resolved by outer loop */
115702   u8 eDistinct;             /* One of the WHERE_DISTINCT_* values below */
115703   u8 nLevel;                /* Number of nested loop */
115704   int iTop;                 /* The very beginning of the WHERE loop */
115705   int iContinue;            /* Jump here to continue with next record */
115706   int iBreak;               /* Jump here to break out of the loop */
115707   int savedNQueryLoop;      /* pParse->nQueryLoop outside the WHERE loop */
115708   int aiCurOnePass[2];      /* OP_OpenWrite cursors for the ONEPASS opt */
115709   WhereMaskSet sMaskSet;    /* Map cursor numbers to bitmasks */
115710   WhereClause sWC;          /* Decomposition of the WHERE clause */
115711   WhereLevel a[1];          /* Information about each nest loop in WHERE */
115712 };
115713
115714 /*
115715 ** Bitmasks for the operators on WhereTerm objects.  These are all
115716 ** operators that are of interest to the query planner.  An
115717 ** OR-ed combination of these values can be used when searching for
115718 ** particular WhereTerms within a WhereClause.
115719 */
115720 #define WO_IN     0x001
115721 #define WO_EQ     0x002
115722 #define WO_LT     (WO_EQ<<(TK_LT-TK_EQ))
115723 #define WO_LE     (WO_EQ<<(TK_LE-TK_EQ))
115724 #define WO_GT     (WO_EQ<<(TK_GT-TK_EQ))
115725 #define WO_GE     (WO_EQ<<(TK_GE-TK_EQ))
115726 #define WO_MATCH  0x040
115727 #define WO_ISNULL 0x080
115728 #define WO_OR     0x100       /* Two or more OR-connected terms */
115729 #define WO_AND    0x200       /* Two or more AND-connected terms */
115730 #define WO_EQUIV  0x400       /* Of the form A==B, both columns */
115731 #define WO_NOOP   0x800       /* This term does not restrict search space */
115732
115733 #define WO_ALL    0xfff       /* Mask of all possible WO_* values */
115734 #define WO_SINGLE 0x0ff       /* Mask of all non-compound WO_* values */
115735
115736 /*
115737 ** These are definitions of bits in the WhereLoop.wsFlags field.
115738 ** The particular combination of bits in each WhereLoop help to
115739 ** determine the algorithm that WhereLoop represents.
115740 */
115741 #define WHERE_COLUMN_EQ    0x00000001  /* x=EXPR */
115742 #define WHERE_COLUMN_RANGE 0x00000002  /* x<EXPR and/or x>EXPR */
115743 #define WHERE_COLUMN_IN    0x00000004  /* x IN (...) */
115744 #define WHERE_COLUMN_NULL  0x00000008  /* x IS NULL */
115745 #define WHERE_CONSTRAINT   0x0000000f  /* Any of the WHERE_COLUMN_xxx values */
115746 #define WHERE_TOP_LIMIT    0x00000010  /* x<EXPR or x<=EXPR constraint */
115747 #define WHERE_BTM_LIMIT    0x00000020  /* x>EXPR or x>=EXPR constraint */
115748 #define WHERE_BOTH_LIMIT   0x00000030  /* Both x>EXPR and x<EXPR */
115749 #define WHERE_IDX_ONLY     0x00000040  /* Use index only - omit table */
115750 #define WHERE_IPK          0x00000100  /* x is the INTEGER PRIMARY KEY */
115751 #define WHERE_INDEXED      0x00000200  /* WhereLoop.u.btree.pIndex is valid */
115752 #define WHERE_VIRTUALTABLE 0x00000400  /* WhereLoop.u.vtab is valid */
115753 #define WHERE_IN_ABLE      0x00000800  /* Able to support an IN operator */
115754 #define WHERE_ONEROW       0x00001000  /* Selects no more than one row */
115755 #define WHERE_MULTI_OR     0x00002000  /* OR using multiple indices */
115756 #define WHERE_AUTO_INDEX   0x00004000  /* Uses an ephemeral index */
115757 #define WHERE_SKIPSCAN     0x00008000  /* Uses the skip-scan algorithm */
115758 #define WHERE_UNQ_WANTED   0x00010000  /* WHERE_ONEROW would have been helpful*/
115759 #define WHERE_PARTIALIDX   0x00020000  /* The automatic index is partial */
115760
115761 /************** End of whereInt.h ********************************************/
115762 /************** Continuing where we left off in where.c **********************/
115763
115764 /*
115765 ** Return the estimated number of output rows from a WHERE clause
115766 */
115767 SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
115768   return sqlite3LogEstToInt(pWInfo->nRowOut);
115769 }
115770
115771 /*
115772 ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
115773 ** WHERE clause returns outputs for DISTINCT processing.
115774 */
115775 SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
115776   return pWInfo->eDistinct;
115777 }
115778
115779 /*
115780 ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
115781 ** Return FALSE if the output needs to be sorted.
115782 */
115783 SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
115784   return pWInfo->nOBSat;
115785 }
115786
115787 /*
115788 ** Return the VDBE address or label to jump to in order to continue
115789 ** immediately with the next row of a WHERE clause.
115790 */
115791 SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
115792   assert( pWInfo->iContinue!=0 );
115793   return pWInfo->iContinue;
115794 }
115795
115796 /*
115797 ** Return the VDBE address or label to jump to in order to break
115798 ** out of a WHERE loop.
115799 */
115800 SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
115801   return pWInfo->iBreak;
115802 }
115803
115804 /*
115805 ** Return TRUE if an UPDATE or DELETE statement can operate directly on
115806 ** the rowids returned by a WHERE clause.  Return FALSE if doing an
115807 ** UPDATE or DELETE might change subsequent WHERE clause results.
115808 **
115809 ** If the ONEPASS optimization is used (if this routine returns true)
115810 ** then also write the indices of open cursors used by ONEPASS
115811 ** into aiCur[0] and aiCur[1].  iaCur[0] gets the cursor of the data
115812 ** table and iaCur[1] gets the cursor used by an auxiliary index.
115813 ** Either value may be -1, indicating that cursor is not used.
115814 ** Any cursors returned will have been opened for writing.
115815 **
115816 ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
115817 ** unable to use the ONEPASS optimization.
115818 */
115819 SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
115820   memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
115821   return pWInfo->okOnePass;
115822 }
115823
115824 /*
115825 ** Move the content of pSrc into pDest
115826 */
115827 static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
115828   pDest->n = pSrc->n;
115829   memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
115830 }
115831
115832 /*
115833 ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
115834 **
115835 ** The new entry might overwrite an existing entry, or it might be
115836 ** appended, or it might be discarded.  Do whatever is the right thing
115837 ** so that pSet keeps the N_OR_COST best entries seen so far.
115838 */
115839 static int whereOrInsert(
115840   WhereOrSet *pSet,      /* The WhereOrSet to be updated */
115841   Bitmask prereq,        /* Prerequisites of the new entry */
115842   LogEst rRun,           /* Run-cost of the new entry */
115843   LogEst nOut            /* Number of outputs for the new entry */
115844 ){
115845   u16 i;
115846   WhereOrCost *p;
115847   for(i=pSet->n, p=pSet->a; i>0; i--, p++){
115848     if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
115849       goto whereOrInsert_done;
115850     }
115851     if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
115852       return 0;
115853     }
115854   }
115855   if( pSet->n<N_OR_COST ){
115856     p = &pSet->a[pSet->n++];
115857     p->nOut = nOut;
115858   }else{
115859     p = pSet->a;
115860     for(i=1; i<pSet->n; i++){
115861       if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
115862     }
115863     if( p->rRun<=rRun ) return 0;
115864   }
115865 whereOrInsert_done:
115866   p->prereq = prereq;
115867   p->rRun = rRun;
115868   if( p->nOut>nOut ) p->nOut = nOut;
115869   return 1;
115870 }
115871
115872 /*
115873 ** Initialize a preallocated WhereClause structure.
115874 */
115875 static void whereClauseInit(
115876   WhereClause *pWC,        /* The WhereClause to be initialized */
115877   WhereInfo *pWInfo        /* The WHERE processing context */
115878 ){
115879   pWC->pWInfo = pWInfo;
115880   pWC->pOuter = 0;
115881   pWC->nTerm = 0;
115882   pWC->nSlot = ArraySize(pWC->aStatic);
115883   pWC->a = pWC->aStatic;
115884 }
115885
115886 /* Forward reference */
115887 static void whereClauseClear(WhereClause*);
115888
115889 /*
115890 ** Deallocate all memory associated with a WhereOrInfo object.
115891 */
115892 static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
115893   whereClauseClear(&p->wc);
115894   sqlite3DbFree(db, p);
115895 }
115896
115897 /*
115898 ** Deallocate all memory associated with a WhereAndInfo object.
115899 */
115900 static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
115901   whereClauseClear(&p->wc);
115902   sqlite3DbFree(db, p);
115903 }
115904
115905 /*
115906 ** Deallocate a WhereClause structure.  The WhereClause structure
115907 ** itself is not freed.  This routine is the inverse of whereClauseInit().
115908 */
115909 static void whereClauseClear(WhereClause *pWC){
115910   int i;
115911   WhereTerm *a;
115912   sqlite3 *db = pWC->pWInfo->pParse->db;
115913   for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
115914     if( a->wtFlags & TERM_DYNAMIC ){
115915       sqlite3ExprDelete(db, a->pExpr);
115916     }
115917     if( a->wtFlags & TERM_ORINFO ){
115918       whereOrInfoDelete(db, a->u.pOrInfo);
115919     }else if( a->wtFlags & TERM_ANDINFO ){
115920       whereAndInfoDelete(db, a->u.pAndInfo);
115921     }
115922   }
115923   if( pWC->a!=pWC->aStatic ){
115924     sqlite3DbFree(db, pWC->a);
115925   }
115926 }
115927
115928 /*
115929 ** Add a single new WhereTerm entry to the WhereClause object pWC.
115930 ** The new WhereTerm object is constructed from Expr p and with wtFlags.
115931 ** The index in pWC->a[] of the new WhereTerm is returned on success.
115932 ** 0 is returned if the new WhereTerm could not be added due to a memory
115933 ** allocation error.  The memory allocation failure will be recorded in
115934 ** the db->mallocFailed flag so that higher-level functions can detect it.
115935 **
115936 ** This routine will increase the size of the pWC->a[] array as necessary.
115937 **
115938 ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
115939 ** for freeing the expression p is assumed by the WhereClause object pWC.
115940 ** This is true even if this routine fails to allocate a new WhereTerm.
115941 **
115942 ** WARNING:  This routine might reallocate the space used to store
115943 ** WhereTerms.  All pointers to WhereTerms should be invalidated after
115944 ** calling this routine.  Such pointers may be reinitialized by referencing
115945 ** the pWC->a[] array.
115946 */
115947 static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
115948   WhereTerm *pTerm;
115949   int idx;
115950   testcase( wtFlags & TERM_VIRTUAL );
115951   if( pWC->nTerm>=pWC->nSlot ){
115952     WhereTerm *pOld = pWC->a;
115953     sqlite3 *db = pWC->pWInfo->pParse->db;
115954     pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
115955     if( pWC->a==0 ){
115956       if( wtFlags & TERM_DYNAMIC ){
115957         sqlite3ExprDelete(db, p);
115958       }
115959       pWC->a = pOld;
115960       return 0;
115961     }
115962     memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
115963     if( pOld!=pWC->aStatic ){
115964       sqlite3DbFree(db, pOld);
115965     }
115966     pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
115967     memset(&pWC->a[pWC->nTerm], 0, sizeof(pWC->a[0])*(pWC->nSlot-pWC->nTerm));
115968   }
115969   pTerm = &pWC->a[idx = pWC->nTerm++];
115970   if( p && ExprHasProperty(p, EP_Unlikely) ){
115971     pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
115972   }else{
115973     pTerm->truthProb = 1;
115974   }
115975   pTerm->pExpr = sqlite3ExprSkipCollate(p);
115976   pTerm->wtFlags = wtFlags;
115977   pTerm->pWC = pWC;
115978   pTerm->iParent = -1;
115979   return idx;
115980 }
115981
115982 /*
115983 ** This routine identifies subexpressions in the WHERE clause where
115984 ** each subexpression is separated by the AND operator or some other
115985 ** operator specified in the op parameter.  The WhereClause structure
115986 ** is filled with pointers to subexpressions.  For example:
115987 **
115988 **    WHERE  a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
115989 **           \________/     \_______________/     \________________/
115990 **            slot[0]            slot[1]               slot[2]
115991 **
115992 ** The original WHERE clause in pExpr is unaltered.  All this routine
115993 ** does is make slot[] entries point to substructure within pExpr.
115994 **
115995 ** In the previous sentence and in the diagram, "slot[]" refers to
115996 ** the WhereClause.a[] array.  The slot[] array grows as needed to contain
115997 ** all terms of the WHERE clause.
115998 */
115999 static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
116000   pWC->op = op;
116001   if( pExpr==0 ) return;
116002   if( pExpr->op!=op ){
116003     whereClauseInsert(pWC, pExpr, 0);
116004   }else{
116005     whereSplit(pWC, pExpr->pLeft, op);
116006     whereSplit(pWC, pExpr->pRight, op);
116007   }
116008 }
116009
116010 /*
116011 ** Initialize a WhereMaskSet object
116012 */
116013 #define initMaskSet(P)  (P)->n=0
116014
116015 /*
116016 ** Return the bitmask for the given cursor number.  Return 0 if
116017 ** iCursor is not in the set.
116018 */
116019 static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
116020   int i;
116021   assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
116022   for(i=0; i<pMaskSet->n; i++){
116023     if( pMaskSet->ix[i]==iCursor ){
116024       return MASKBIT(i);
116025     }
116026   }
116027   return 0;
116028 }
116029
116030 /*
116031 ** Create a new mask for cursor iCursor.
116032 **
116033 ** There is one cursor per table in the FROM clause.  The number of
116034 ** tables in the FROM clause is limited by a test early in the
116035 ** sqlite3WhereBegin() routine.  So we know that the pMaskSet->ix[]
116036 ** array will never overflow.
116037 */
116038 static void createMask(WhereMaskSet *pMaskSet, int iCursor){
116039   assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
116040   pMaskSet->ix[pMaskSet->n++] = iCursor;
116041 }
116042
116043 /*
116044 ** These routines walk (recursively) an expression tree and generate
116045 ** a bitmask indicating which tables are used in that expression
116046 ** tree.
116047 */
116048 static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
116049 static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
116050 static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
116051   Bitmask mask = 0;
116052   if( p==0 ) return 0;
116053   if( p->op==TK_COLUMN ){
116054     mask = getMask(pMaskSet, p->iTable);
116055     return mask;
116056   }
116057   mask = exprTableUsage(pMaskSet, p->pRight);
116058   mask |= exprTableUsage(pMaskSet, p->pLeft);
116059   if( ExprHasProperty(p, EP_xIsSelect) ){
116060     mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
116061   }else{
116062     mask |= exprListTableUsage(pMaskSet, p->x.pList);
116063   }
116064   return mask;
116065 }
116066 static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
116067   int i;
116068   Bitmask mask = 0;
116069   if( pList ){
116070     for(i=0; i<pList->nExpr; i++){
116071       mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
116072     }
116073   }
116074   return mask;
116075 }
116076 static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
116077   Bitmask mask = 0;
116078   while( pS ){
116079     SrcList *pSrc = pS->pSrc;
116080     mask |= exprListTableUsage(pMaskSet, pS->pEList);
116081     mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
116082     mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
116083     mask |= exprTableUsage(pMaskSet, pS->pWhere);
116084     mask |= exprTableUsage(pMaskSet, pS->pHaving);
116085     if( ALWAYS(pSrc!=0) ){
116086       int i;
116087       for(i=0; i<pSrc->nSrc; i++){
116088         mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
116089         mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
116090       }
116091     }
116092     pS = pS->pPrior;
116093   }
116094   return mask;
116095 }
116096
116097 /*
116098 ** Return TRUE if the given operator is one of the operators that is
116099 ** allowed for an indexable WHERE clause term.  The allowed operators are
116100 ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
116101 */
116102 static int allowedOp(int op){
116103   assert( TK_GT>TK_EQ && TK_GT<TK_GE );
116104   assert( TK_LT>TK_EQ && TK_LT<TK_GE );
116105   assert( TK_LE>TK_EQ && TK_LE<TK_GE );
116106   assert( TK_GE==TK_EQ+4 );
116107   return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
116108 }
116109
116110 /*
116111 ** Commute a comparison operator.  Expressions of the form "X op Y"
116112 ** are converted into "Y op X".
116113 **
116114 ** If left/right precedence rules come into play when determining the
116115 ** collating sequence, then COLLATE operators are adjusted to ensure
116116 ** that the collating sequence does not change.  For example:
116117 ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
116118 ** the left hand side of a comparison overrides any collation sequence 
116119 ** attached to the right. For the same reason the EP_Collate flag
116120 ** is not commuted.
116121 */
116122 static void exprCommute(Parse *pParse, Expr *pExpr){
116123   u16 expRight = (pExpr->pRight->flags & EP_Collate);
116124   u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
116125   assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
116126   if( expRight==expLeft ){
116127     /* Either X and Y both have COLLATE operator or neither do */
116128     if( expRight ){
116129       /* Both X and Y have COLLATE operators.  Make sure X is always
116130       ** used by clearing the EP_Collate flag from Y. */
116131       pExpr->pRight->flags &= ~EP_Collate;
116132     }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
116133       /* Neither X nor Y have COLLATE operators, but X has a non-default
116134       ** collating sequence.  So add the EP_Collate marker on X to cause
116135       ** it to be searched first. */
116136       pExpr->pLeft->flags |= EP_Collate;
116137     }
116138   }
116139   SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
116140   if( pExpr->op>=TK_GT ){
116141     assert( TK_LT==TK_GT+2 );
116142     assert( TK_GE==TK_LE+2 );
116143     assert( TK_GT>TK_EQ );
116144     assert( TK_GT<TK_LE );
116145     assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
116146     pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
116147   }
116148 }
116149
116150 /*
116151 ** Translate from TK_xx operator to WO_xx bitmask.
116152 */
116153 static u16 operatorMask(int op){
116154   u16 c;
116155   assert( allowedOp(op) );
116156   if( op==TK_IN ){
116157     c = WO_IN;
116158   }else if( op==TK_ISNULL ){
116159     c = WO_ISNULL;
116160   }else{
116161     assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
116162     c = (u16)(WO_EQ<<(op-TK_EQ));
116163   }
116164   assert( op!=TK_ISNULL || c==WO_ISNULL );
116165   assert( op!=TK_IN || c==WO_IN );
116166   assert( op!=TK_EQ || c==WO_EQ );
116167   assert( op!=TK_LT || c==WO_LT );
116168   assert( op!=TK_LE || c==WO_LE );
116169   assert( op!=TK_GT || c==WO_GT );
116170   assert( op!=TK_GE || c==WO_GE );
116171   return c;
116172 }
116173
116174 /*
116175 ** Advance to the next WhereTerm that matches according to the criteria
116176 ** established when the pScan object was initialized by whereScanInit().
116177 ** Return NULL if there are no more matching WhereTerms.
116178 */
116179 static WhereTerm *whereScanNext(WhereScan *pScan){
116180   int iCur;            /* The cursor on the LHS of the term */
116181   int iColumn;         /* The column on the LHS of the term.  -1 for IPK */
116182   Expr *pX;            /* An expression being tested */
116183   WhereClause *pWC;    /* Shorthand for pScan->pWC */
116184   WhereTerm *pTerm;    /* The term being tested */
116185   int k = pScan->k;    /* Where to start scanning */
116186
116187   while( pScan->iEquiv<=pScan->nEquiv ){
116188     iCur = pScan->aEquiv[pScan->iEquiv-2];
116189     iColumn = pScan->aEquiv[pScan->iEquiv-1];
116190     while( (pWC = pScan->pWC)!=0 ){
116191       for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
116192         if( pTerm->leftCursor==iCur
116193          && pTerm->u.leftColumn==iColumn
116194          && (pScan->iEquiv<=2 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
116195         ){
116196           if( (pTerm->eOperator & WO_EQUIV)!=0
116197            && pScan->nEquiv<ArraySize(pScan->aEquiv)
116198           ){
116199             int j;
116200             pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
116201             assert( pX->op==TK_COLUMN );
116202             for(j=0; j<pScan->nEquiv; j+=2){
116203               if( pScan->aEquiv[j]==pX->iTable
116204                && pScan->aEquiv[j+1]==pX->iColumn ){
116205                   break;
116206               }
116207             }
116208             if( j==pScan->nEquiv ){
116209               pScan->aEquiv[j] = pX->iTable;
116210               pScan->aEquiv[j+1] = pX->iColumn;
116211               pScan->nEquiv += 2;
116212             }
116213           }
116214           if( (pTerm->eOperator & pScan->opMask)!=0 ){
116215             /* Verify the affinity and collating sequence match */
116216             if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
116217               CollSeq *pColl;
116218               Parse *pParse = pWC->pWInfo->pParse;
116219               pX = pTerm->pExpr;
116220               if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
116221                 continue;
116222               }
116223               assert(pX->pLeft);
116224               pColl = sqlite3BinaryCompareCollSeq(pParse,
116225                                                   pX->pLeft, pX->pRight);
116226               if( pColl==0 ) pColl = pParse->db->pDfltColl;
116227               if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
116228                 continue;
116229               }
116230             }
116231             if( (pTerm->eOperator & WO_EQ)!=0
116232              && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
116233              && pX->iTable==pScan->aEquiv[0]
116234              && pX->iColumn==pScan->aEquiv[1]
116235             ){
116236               continue;
116237             }
116238             pScan->k = k+1;
116239             return pTerm;
116240           }
116241         }
116242       }
116243       pScan->pWC = pScan->pWC->pOuter;
116244       k = 0;
116245     }
116246     pScan->pWC = pScan->pOrigWC;
116247     k = 0;
116248     pScan->iEquiv += 2;
116249   }
116250   return 0;
116251 }
116252
116253 /*
116254 ** Initialize a WHERE clause scanner object.  Return a pointer to the
116255 ** first match.  Return NULL if there are no matches.
116256 **
116257 ** The scanner will be searching the WHERE clause pWC.  It will look
116258 ** for terms of the form "X <op> <expr>" where X is column iColumn of table
116259 ** iCur.  The <op> must be one of the operators described by opMask.
116260 **
116261 ** If the search is for X and the WHERE clause contains terms of the
116262 ** form X=Y then this routine might also return terms of the form
116263 ** "Y <op> <expr>".  The number of levels of transitivity is limited,
116264 ** but is enough to handle most commonly occurring SQL statements.
116265 **
116266 ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
116267 ** index pIdx.
116268 */
116269 static WhereTerm *whereScanInit(
116270   WhereScan *pScan,       /* The WhereScan object being initialized */
116271   WhereClause *pWC,       /* The WHERE clause to be scanned */
116272   int iCur,               /* Cursor to scan for */
116273   int iColumn,            /* Column to scan for */
116274   u32 opMask,             /* Operator(s) to scan for */
116275   Index *pIdx             /* Must be compatible with this index */
116276 ){
116277   int j;
116278
116279   /* memset(pScan, 0, sizeof(*pScan)); */
116280   pScan->pOrigWC = pWC;
116281   pScan->pWC = pWC;
116282   if( pIdx && iColumn>=0 ){
116283     pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
116284     for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
116285       if( NEVER(j>pIdx->nColumn) ) return 0;
116286     }
116287     pScan->zCollName = pIdx->azColl[j];
116288   }else{
116289     pScan->idxaff = 0;
116290     pScan->zCollName = 0;
116291   }
116292   pScan->opMask = opMask;
116293   pScan->k = 0;
116294   pScan->aEquiv[0] = iCur;
116295   pScan->aEquiv[1] = iColumn;
116296   pScan->nEquiv = 2;
116297   pScan->iEquiv = 2;
116298   return whereScanNext(pScan);
116299 }
116300
116301 /*
116302 ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
116303 ** where X is a reference to the iColumn of table iCur and <op> is one of
116304 ** the WO_xx operator codes specified by the op parameter.
116305 ** Return a pointer to the term.  Return 0 if not found.
116306 **
116307 ** The term returned might by Y=<expr> if there is another constraint in
116308 ** the WHERE clause that specifies that X=Y.  Any such constraints will be
116309 ** identified by the WO_EQUIV bit in the pTerm->eOperator field.  The
116310 ** aEquiv[] array holds X and all its equivalents, with each SQL variable
116311 ** taking up two slots in aEquiv[].  The first slot is for the cursor number
116312 ** and the second is for the column number.  There are 22 slots in aEquiv[]
116313 ** so that means we can look for X plus up to 10 other equivalent values.
116314 ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
116315 ** and ... and A9=A10 and A10=<expr>.
116316 **
116317 ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
116318 ** then try for the one with no dependencies on <expr> - in other words where
116319 ** <expr> is a constant expression of some kind.  Only return entries of
116320 ** the form "X <op> Y" where Y is a column in another table if no terms of
116321 ** the form "X <op> <const-expr>" exist.   If no terms with a constant RHS
116322 ** exist, try to return a term that does not use WO_EQUIV.
116323 */
116324 static WhereTerm *findTerm(
116325   WhereClause *pWC,     /* The WHERE clause to be searched */
116326   int iCur,             /* Cursor number of LHS */
116327   int iColumn,          /* Column number of LHS */
116328   Bitmask notReady,     /* RHS must not overlap with this mask */
116329   u32 op,               /* Mask of WO_xx values describing operator */
116330   Index *pIdx           /* Must be compatible with this index, if not NULL */
116331 ){
116332   WhereTerm *pResult = 0;
116333   WhereTerm *p;
116334   WhereScan scan;
116335
116336   p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
116337   while( p ){
116338     if( (p->prereqRight & notReady)==0 ){
116339       if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
116340         return p;
116341       }
116342       if( pResult==0 ) pResult = p;
116343     }
116344     p = whereScanNext(&scan);
116345   }
116346   return pResult;
116347 }
116348
116349 /* Forward reference */
116350 static void exprAnalyze(SrcList*, WhereClause*, int);
116351
116352 /*
116353 ** Call exprAnalyze on all terms in a WHERE clause.  
116354 */
116355 static void exprAnalyzeAll(
116356   SrcList *pTabList,       /* the FROM clause */
116357   WhereClause *pWC         /* the WHERE clause to be analyzed */
116358 ){
116359   int i;
116360   for(i=pWC->nTerm-1; i>=0; i--){
116361     exprAnalyze(pTabList, pWC, i);
116362   }
116363 }
116364
116365 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
116366 /*
116367 ** Check to see if the given expression is a LIKE or GLOB operator that
116368 ** can be optimized using inequality constraints.  Return TRUE if it is
116369 ** so and false if not.
116370 **
116371 ** In order for the operator to be optimizible, the RHS must be a string
116372 ** literal that does not begin with a wildcard.  The LHS must be a column
116373 ** that may only be NULL, a string, or a BLOB, never a number. (This means
116374 ** that virtual tables cannot participate in the LIKE optimization.)  If the
116375 ** collating sequence for the column on the LHS must be appropriate for
116376 ** the operator.
116377 */
116378 static int isLikeOrGlob(
116379   Parse *pParse,    /* Parsing and code generating context */
116380   Expr *pExpr,      /* Test this expression */
116381   Expr **ppPrefix,  /* Pointer to TK_STRING expression with pattern prefix */
116382   int *pisComplete, /* True if the only wildcard is % in the last character */
116383   int *pnoCase      /* True if uppercase is equivalent to lowercase */
116384 ){
116385   const char *z = 0;         /* String on RHS of LIKE operator */
116386   Expr *pRight, *pLeft;      /* Right and left size of LIKE operator */
116387   ExprList *pList;           /* List of operands to the LIKE operator */
116388   int c;                     /* One character in z[] */
116389   int cnt;                   /* Number of non-wildcard prefix characters */
116390   char wc[3];                /* Wildcard characters */
116391   sqlite3 *db = pParse->db;  /* Database connection */
116392   sqlite3_value *pVal = 0;
116393   int op;                    /* Opcode of pRight */
116394
116395   if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
116396     return 0;
116397   }
116398 #ifdef SQLITE_EBCDIC
116399   if( *pnoCase ) return 0;
116400 #endif
116401   pList = pExpr->x.pList;
116402   pLeft = pList->a[1].pExpr;
116403   if( pLeft->op!=TK_COLUMN 
116404    || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT 
116405    || IsVirtual(pLeft->pTab)  /* Value might be numeric */
116406   ){
116407     /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
116408     ** be the name of an indexed column with TEXT affinity. */
116409     return 0;
116410   }
116411   assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
116412
116413   pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
116414   op = pRight->op;
116415   if( op==TK_VARIABLE ){
116416     Vdbe *pReprepare = pParse->pReprepare;
116417     int iCol = pRight->iColumn;
116418     pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
116419     if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
116420       z = (char *)sqlite3_value_text(pVal);
116421     }
116422     sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
116423     assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
116424   }else if( op==TK_STRING ){
116425     z = pRight->u.zToken;
116426   }
116427   if( z ){
116428     cnt = 0;
116429     while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
116430       cnt++;
116431     }
116432     if( cnt!=0 && 255!=(u8)z[cnt-1] ){
116433       Expr *pPrefix;
116434       *pisComplete = c==wc[0] && z[cnt+1]==0;
116435       pPrefix = sqlite3Expr(db, TK_STRING, z);
116436       if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
116437       *ppPrefix = pPrefix;
116438       if( op==TK_VARIABLE ){
116439         Vdbe *v = pParse->pVdbe;
116440         sqlite3VdbeSetVarmask(v, pRight->iColumn);
116441         if( *pisComplete && pRight->u.zToken[1] ){
116442           /* If the rhs of the LIKE expression is a variable, and the current
116443           ** value of the variable means there is no need to invoke the LIKE
116444           ** function, then no OP_Variable will be added to the program.
116445           ** This causes problems for the sqlite3_bind_parameter_name()
116446           ** API. To work around them, add a dummy OP_Variable here.
116447           */ 
116448           int r1 = sqlite3GetTempReg(pParse);
116449           sqlite3ExprCodeTarget(pParse, pRight, r1);
116450           sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
116451           sqlite3ReleaseTempReg(pParse, r1);
116452         }
116453       }
116454     }else{
116455       z = 0;
116456     }
116457   }
116458
116459   sqlite3ValueFree(pVal);
116460   return (z!=0);
116461 }
116462 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
116463
116464
116465 #ifndef SQLITE_OMIT_VIRTUALTABLE
116466 /*
116467 ** Check to see if the given expression is of the form
116468 **
116469 **         column MATCH expr
116470 **
116471 ** If it is then return TRUE.  If not, return FALSE.
116472 */
116473 static int isMatchOfColumn(
116474   Expr *pExpr      /* Test this expression */
116475 ){
116476   ExprList *pList;
116477
116478   if( pExpr->op!=TK_FUNCTION ){
116479     return 0;
116480   }
116481   if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
116482     return 0;
116483   }
116484   pList = pExpr->x.pList;
116485   if( pList->nExpr!=2 ){
116486     return 0;
116487   }
116488   if( pList->a[1].pExpr->op != TK_COLUMN ){
116489     return 0;
116490   }
116491   return 1;
116492 }
116493 #endif /* SQLITE_OMIT_VIRTUALTABLE */
116494
116495 /*
116496 ** If the pBase expression originated in the ON or USING clause of
116497 ** a join, then transfer the appropriate markings over to derived.
116498 */
116499 static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
116500   if( pDerived ){
116501     pDerived->flags |= pBase->flags & EP_FromJoin;
116502     pDerived->iRightJoinTable = pBase->iRightJoinTable;
116503   }
116504 }
116505
116506 /*
116507 ** Mark term iChild as being a child of term iParent
116508 */
116509 static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
116510   pWC->a[iChild].iParent = iParent;
116511   pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
116512   pWC->a[iParent].nChild++;
116513 }
116514
116515 /*
116516 ** Return the N-th AND-connected subterm of pTerm.  Or if pTerm is not
116517 ** a conjunction, then return just pTerm when N==0.  If N is exceeds
116518 ** the number of available subterms, return NULL.
116519 */
116520 static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
116521   if( pTerm->eOperator!=WO_AND ){
116522     return N==0 ? pTerm : 0;
116523   }
116524   if( N<pTerm->u.pAndInfo->wc.nTerm ){
116525     return &pTerm->u.pAndInfo->wc.a[N];
116526   }
116527   return 0;
116528 }
116529
116530 /*
116531 ** Subterms pOne and pTwo are contained within WHERE clause pWC.  The
116532 ** two subterms are in disjunction - they are OR-ed together.
116533 **
116534 ** If these two terms are both of the form:  "A op B" with the same
116535 ** A and B values but different operators and if the operators are
116536 ** compatible (if one is = and the other is <, for example) then
116537 ** add a new virtual AND term to pWC that is the combination of the
116538 ** two.
116539 **
116540 ** Some examples:
116541 **
116542 **    x<y OR x=y    -->     x<=y
116543 **    x=y OR x=y    -->     x=y
116544 **    x<=y OR x<y   -->     x<=y
116545 **
116546 ** The following is NOT generated:
116547 **
116548 **    x<y OR x>y    -->     x!=y     
116549 */
116550 static void whereCombineDisjuncts(
116551   SrcList *pSrc,         /* the FROM clause */
116552   WhereClause *pWC,      /* The complete WHERE clause */
116553   WhereTerm *pOne,       /* First disjunct */
116554   WhereTerm *pTwo        /* Second disjunct */
116555 ){
116556   u16 eOp = pOne->eOperator | pTwo->eOperator;
116557   sqlite3 *db;           /* Database connection (for malloc) */
116558   Expr *pNew;            /* New virtual expression */
116559   int op;                /* Operator for the combined expression */
116560   int idxNew;            /* Index in pWC of the next virtual term */
116561
116562   if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
116563   if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
116564   if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
116565    && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
116566   assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
116567   assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
116568   if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
116569   if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return;
116570   /* If we reach this point, it means the two subterms can be combined */
116571   if( (eOp & (eOp-1))!=0 ){
116572     if( eOp & (WO_LT|WO_LE) ){
116573       eOp = WO_LE;
116574     }else{
116575       assert( eOp & (WO_GT|WO_GE) );
116576       eOp = WO_GE;
116577     }
116578   }
116579   db = pWC->pWInfo->pParse->db;
116580   pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
116581   if( pNew==0 ) return;
116582   for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
116583   pNew->op = op;
116584   idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
116585   exprAnalyze(pSrc, pWC, idxNew);
116586 }
116587
116588 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
116589 /*
116590 ** Analyze a term that consists of two or more OR-connected
116591 ** subterms.  So in:
116592 **
116593 **     ... WHERE  (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
116594 **                          ^^^^^^^^^^^^^^^^^^^^
116595 **
116596 ** This routine analyzes terms such as the middle term in the above example.
116597 ** A WhereOrTerm object is computed and attached to the term under
116598 ** analysis, regardless of the outcome of the analysis.  Hence:
116599 **
116600 **     WhereTerm.wtFlags   |=  TERM_ORINFO
116601 **     WhereTerm.u.pOrInfo  =  a dynamically allocated WhereOrTerm object
116602 **
116603 ** The term being analyzed must have two or more of OR-connected subterms.
116604 ** A single subterm might be a set of AND-connected sub-subterms.
116605 ** Examples of terms under analysis:
116606 **
116607 **     (A)     t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
116608 **     (B)     x=expr1 OR expr2=x OR x=expr3
116609 **     (C)     t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
116610 **     (D)     x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
116611 **     (E)     (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
116612 **     (F)     x>A OR (x=A AND y>=B)
116613 **
116614 ** CASE 1:
116615 **
116616 ** If all subterms are of the form T.C=expr for some single column of C and
116617 ** a single table T (as shown in example B above) then create a new virtual
116618 ** term that is an equivalent IN expression.  In other words, if the term
116619 ** being analyzed is:
116620 **
116621 **      x = expr1  OR  expr2 = x  OR  x = expr3
116622 **
116623 ** then create a new virtual term like this:
116624 **
116625 **      x IN (expr1,expr2,expr3)
116626 **
116627 ** CASE 2:
116628 **
116629 ** If there are exactly two disjuncts one side has x>A and the other side
116630 ** has x=A (for the same x and A) then add a new virtual conjunct term to the
116631 ** WHERE clause of the form "x>=A".  Example:
116632 **
116633 **      x>A OR (x=A AND y>B)    adds:    x>=A
116634 **
116635 ** The added conjunct can sometimes be helpful in query planning.
116636 **
116637 ** CASE 3:
116638 **
116639 ** If all subterms are indexable by a single table T, then set
116640 **
116641 **     WhereTerm.eOperator              =  WO_OR
116642 **     WhereTerm.u.pOrInfo->indexable  |=  the cursor number for table T
116643 **
116644 ** A subterm is "indexable" if it is of the form
116645 ** "T.C <op> <expr>" where C is any column of table T and 
116646 ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
116647 ** A subterm is also indexable if it is an AND of two or more
116648 ** subsubterms at least one of which is indexable.  Indexable AND 
116649 ** subterms have their eOperator set to WO_AND and they have
116650 ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
116651 **
116652 ** From another point of view, "indexable" means that the subterm could
116653 ** potentially be used with an index if an appropriate index exists.
116654 ** This analysis does not consider whether or not the index exists; that
116655 ** is decided elsewhere.  This analysis only looks at whether subterms
116656 ** appropriate for indexing exist.
116657 **
116658 ** All examples A through E above satisfy case 2.  But if a term
116659 ** also satisfies case 1 (such as B) we know that the optimizer will
116660 ** always prefer case 1, so in that case we pretend that case 2 is not
116661 ** satisfied.
116662 **
116663 ** It might be the case that multiple tables are indexable.  For example,
116664 ** (E) above is indexable on tables P, Q, and R.
116665 **
116666 ** Terms that satisfy case 2 are candidates for lookup by using
116667 ** separate indices to find rowids for each subterm and composing
116668 ** the union of all rowids using a RowSet object.  This is similar
116669 ** to "bitmap indices" in other database engines.
116670 **
116671 ** OTHERWISE:
116672 **
116673 ** If neither case 1 nor case 2 apply, then leave the eOperator set to
116674 ** zero.  This term is not useful for search.
116675 */
116676 static void exprAnalyzeOrTerm(
116677   SrcList *pSrc,            /* the FROM clause */
116678   WhereClause *pWC,         /* the complete WHERE clause */
116679   int idxTerm               /* Index of the OR-term to be analyzed */
116680 ){
116681   WhereInfo *pWInfo = pWC->pWInfo;        /* WHERE clause processing context */
116682   Parse *pParse = pWInfo->pParse;         /* Parser context */
116683   sqlite3 *db = pParse->db;               /* Database connection */
116684   WhereTerm *pTerm = &pWC->a[idxTerm];    /* The term to be analyzed */
116685   Expr *pExpr = pTerm->pExpr;             /* The expression of the term */
116686   int i;                                  /* Loop counters */
116687   WhereClause *pOrWc;       /* Breakup of pTerm into subterms */
116688   WhereTerm *pOrTerm;       /* A Sub-term within the pOrWc */
116689   WhereOrInfo *pOrInfo;     /* Additional information associated with pTerm */
116690   Bitmask chngToIN;         /* Tables that might satisfy case 1 */
116691   Bitmask indexable;        /* Tables that are indexable, satisfying case 2 */
116692
116693   /*
116694   ** Break the OR clause into its separate subterms.  The subterms are
116695   ** stored in a WhereClause structure containing within the WhereOrInfo
116696   ** object that is attached to the original OR clause term.
116697   */
116698   assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
116699   assert( pExpr->op==TK_OR );
116700   pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
116701   if( pOrInfo==0 ) return;
116702   pTerm->wtFlags |= TERM_ORINFO;
116703   pOrWc = &pOrInfo->wc;
116704   whereClauseInit(pOrWc, pWInfo);
116705   whereSplit(pOrWc, pExpr, TK_OR);
116706   exprAnalyzeAll(pSrc, pOrWc);
116707   if( db->mallocFailed ) return;
116708   assert( pOrWc->nTerm>=2 );
116709
116710   /*
116711   ** Compute the set of tables that might satisfy cases 1 or 2.
116712   */
116713   indexable = ~(Bitmask)0;
116714   chngToIN = ~(Bitmask)0;
116715   for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
116716     if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
116717       WhereAndInfo *pAndInfo;
116718       assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
116719       chngToIN = 0;
116720       pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
116721       if( pAndInfo ){
116722         WhereClause *pAndWC;
116723         WhereTerm *pAndTerm;
116724         int j;
116725         Bitmask b = 0;
116726         pOrTerm->u.pAndInfo = pAndInfo;
116727         pOrTerm->wtFlags |= TERM_ANDINFO;
116728         pOrTerm->eOperator = WO_AND;
116729         pAndWC = &pAndInfo->wc;
116730         whereClauseInit(pAndWC, pWC->pWInfo);
116731         whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
116732         exprAnalyzeAll(pSrc, pAndWC);
116733         pAndWC->pOuter = pWC;
116734         testcase( db->mallocFailed );
116735         if( !db->mallocFailed ){
116736           for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
116737             assert( pAndTerm->pExpr );
116738             if( allowedOp(pAndTerm->pExpr->op) ){
116739               b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
116740             }
116741           }
116742         }
116743         indexable &= b;
116744       }
116745     }else if( pOrTerm->wtFlags & TERM_COPIED ){
116746       /* Skip this term for now.  We revisit it when we process the
116747       ** corresponding TERM_VIRTUAL term */
116748     }else{
116749       Bitmask b;
116750       b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
116751       if( pOrTerm->wtFlags & TERM_VIRTUAL ){
116752         WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
116753         b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
116754       }
116755       indexable &= b;
116756       if( (pOrTerm->eOperator & WO_EQ)==0 ){
116757         chngToIN = 0;
116758       }else{
116759         chngToIN &= b;
116760       }
116761     }
116762   }
116763
116764   /*
116765   ** Record the set of tables that satisfy case 3.  The set might be
116766   ** empty.
116767   */
116768   pOrInfo->indexable = indexable;
116769   pTerm->eOperator = indexable==0 ? 0 : WO_OR;
116770
116771   /* For a two-way OR, attempt to implementation case 2.
116772   */
116773   if( indexable && pOrWc->nTerm==2 ){
116774     int iOne = 0;
116775     WhereTerm *pOne;
116776     while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
116777       int iTwo = 0;
116778       WhereTerm *pTwo;
116779       while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
116780         whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
116781       }
116782     }
116783   }
116784
116785   /*
116786   ** chngToIN holds a set of tables that *might* satisfy case 1.  But
116787   ** we have to do some additional checking to see if case 1 really
116788   ** is satisfied.
116789   **
116790   ** chngToIN will hold either 0, 1, or 2 bits.  The 0-bit case means
116791   ** that there is no possibility of transforming the OR clause into an
116792   ** IN operator because one or more terms in the OR clause contain
116793   ** something other than == on a column in the single table.  The 1-bit
116794   ** case means that every term of the OR clause is of the form
116795   ** "table.column=expr" for some single table.  The one bit that is set
116796   ** will correspond to the common table.  We still need to check to make
116797   ** sure the same column is used on all terms.  The 2-bit case is when
116798   ** the all terms are of the form "table1.column=table2.column".  It
116799   ** might be possible to form an IN operator with either table1.column
116800   ** or table2.column as the LHS if either is common to every term of
116801   ** the OR clause.
116802   **
116803   ** Note that terms of the form "table.column1=table.column2" (the
116804   ** same table on both sizes of the ==) cannot be optimized.
116805   */
116806   if( chngToIN ){
116807     int okToChngToIN = 0;     /* True if the conversion to IN is valid */
116808     int iColumn = -1;         /* Column index on lhs of IN operator */
116809     int iCursor = -1;         /* Table cursor common to all terms */
116810     int j = 0;                /* Loop counter */
116811
116812     /* Search for a table and column that appears on one side or the
116813     ** other of the == operator in every subterm.  That table and column
116814     ** will be recorded in iCursor and iColumn.  There might not be any
116815     ** such table and column.  Set okToChngToIN if an appropriate table
116816     ** and column is found but leave okToChngToIN false if not found.
116817     */
116818     for(j=0; j<2 && !okToChngToIN; j++){
116819       pOrTerm = pOrWc->a;
116820       for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
116821         assert( pOrTerm->eOperator & WO_EQ );
116822         pOrTerm->wtFlags &= ~TERM_OR_OK;
116823         if( pOrTerm->leftCursor==iCursor ){
116824           /* This is the 2-bit case and we are on the second iteration and
116825           ** current term is from the first iteration.  So skip this term. */
116826           assert( j==1 );
116827           continue;
116828         }
116829         if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
116830           /* This term must be of the form t1.a==t2.b where t2 is in the
116831           ** chngToIN set but t1 is not.  This term will be either preceded
116832           ** or follwed by an inverted copy (t2.b==t1.a).  Skip this term 
116833           ** and use its inversion. */
116834           testcase( pOrTerm->wtFlags & TERM_COPIED );
116835           testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
116836           assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
116837           continue;
116838         }
116839         iColumn = pOrTerm->u.leftColumn;
116840         iCursor = pOrTerm->leftCursor;
116841         break;
116842       }
116843       if( i<0 ){
116844         /* No candidate table+column was found.  This can only occur
116845         ** on the second iteration */
116846         assert( j==1 );
116847         assert( IsPowerOfTwo(chngToIN) );
116848         assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
116849         break;
116850       }
116851       testcase( j==1 );
116852
116853       /* We have found a candidate table and column.  Check to see if that
116854       ** table and column is common to every term in the OR clause */
116855       okToChngToIN = 1;
116856       for(; i>=0 && okToChngToIN; i--, pOrTerm++){
116857         assert( pOrTerm->eOperator & WO_EQ );
116858         if( pOrTerm->leftCursor!=iCursor ){
116859           pOrTerm->wtFlags &= ~TERM_OR_OK;
116860         }else if( pOrTerm->u.leftColumn!=iColumn ){
116861           okToChngToIN = 0;
116862         }else{
116863           int affLeft, affRight;
116864           /* If the right-hand side is also a column, then the affinities
116865           ** of both right and left sides must be such that no type
116866           ** conversions are required on the right.  (Ticket #2249)
116867           */
116868           affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
116869           affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
116870           if( affRight!=0 && affRight!=affLeft ){
116871             okToChngToIN = 0;
116872           }else{
116873             pOrTerm->wtFlags |= TERM_OR_OK;
116874           }
116875         }
116876       }
116877     }
116878
116879     /* At this point, okToChngToIN is true if original pTerm satisfies
116880     ** case 1.  In that case, construct a new virtual term that is 
116881     ** pTerm converted into an IN operator.
116882     */
116883     if( okToChngToIN ){
116884       Expr *pDup;            /* A transient duplicate expression */
116885       ExprList *pList = 0;   /* The RHS of the IN operator */
116886       Expr *pLeft = 0;       /* The LHS of the IN operator */
116887       Expr *pNew;            /* The complete IN operator */
116888
116889       for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
116890         if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
116891         assert( pOrTerm->eOperator & WO_EQ );
116892         assert( pOrTerm->leftCursor==iCursor );
116893         assert( pOrTerm->u.leftColumn==iColumn );
116894         pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
116895         pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
116896         pLeft = pOrTerm->pExpr->pLeft;
116897       }
116898       assert( pLeft!=0 );
116899       pDup = sqlite3ExprDup(db, pLeft, 0);
116900       pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
116901       if( pNew ){
116902         int idxNew;
116903         transferJoinMarkings(pNew, pExpr);
116904         assert( !ExprHasProperty(pNew, EP_xIsSelect) );
116905         pNew->x.pList = pList;
116906         idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
116907         testcase( idxNew==0 );
116908         exprAnalyze(pSrc, pWC, idxNew);
116909         pTerm = &pWC->a[idxTerm];
116910         markTermAsChild(pWC, idxNew, idxTerm);
116911       }else{
116912         sqlite3ExprListDelete(db, pList);
116913       }
116914       pTerm->eOperator = WO_NOOP;  /* case 1 trumps case 3 */
116915     }
116916   }
116917 }
116918 #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
116919
116920 /*
116921 ** The input to this routine is an WhereTerm structure with only the
116922 ** "pExpr" field filled in.  The job of this routine is to analyze the
116923 ** subexpression and populate all the other fields of the WhereTerm
116924 ** structure.
116925 **
116926 ** If the expression is of the form "<expr> <op> X" it gets commuted
116927 ** to the standard form of "X <op> <expr>".
116928 **
116929 ** If the expression is of the form "X <op> Y" where both X and Y are
116930 ** columns, then the original expression is unchanged and a new virtual
116931 ** term of the form "Y <op> X" is added to the WHERE clause and
116932 ** analyzed separately.  The original term is marked with TERM_COPIED
116933 ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
116934 ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
116935 ** is a commuted copy of a prior term.)  The original term has nChild=1
116936 ** and the copy has idxParent set to the index of the original term.
116937 */
116938 static void exprAnalyze(
116939   SrcList *pSrc,            /* the FROM clause */
116940   WhereClause *pWC,         /* the WHERE clause */
116941   int idxTerm               /* Index of the term to be analyzed */
116942 ){
116943   WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
116944   WhereTerm *pTerm;                /* The term to be analyzed */
116945   WhereMaskSet *pMaskSet;          /* Set of table index masks */
116946   Expr *pExpr;                     /* The expression to be analyzed */
116947   Bitmask prereqLeft;              /* Prerequesites of the pExpr->pLeft */
116948   Bitmask prereqAll;               /* Prerequesites of pExpr */
116949   Bitmask extraRight = 0;          /* Extra dependencies on LEFT JOIN */
116950   Expr *pStr1 = 0;                 /* RHS of LIKE/GLOB operator */
116951   int isComplete = 0;              /* RHS of LIKE/GLOB ends with wildcard */
116952   int noCase = 0;                  /* uppercase equivalent to lowercase */
116953   int op;                          /* Top-level operator.  pExpr->op */
116954   Parse *pParse = pWInfo->pParse;  /* Parsing context */
116955   sqlite3 *db = pParse->db;        /* Database connection */
116956
116957   if( db->mallocFailed ){
116958     return;
116959   }
116960   pTerm = &pWC->a[idxTerm];
116961   pMaskSet = &pWInfo->sMaskSet;
116962   pExpr = pTerm->pExpr;
116963   assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
116964   prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
116965   op = pExpr->op;
116966   if( op==TK_IN ){
116967     assert( pExpr->pRight==0 );
116968     if( ExprHasProperty(pExpr, EP_xIsSelect) ){
116969       pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
116970     }else{
116971       pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
116972     }
116973   }else if( op==TK_ISNULL ){
116974     pTerm->prereqRight = 0;
116975   }else{
116976     pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
116977   }
116978   prereqAll = exprTableUsage(pMaskSet, pExpr);
116979   if( ExprHasProperty(pExpr, EP_FromJoin) ){
116980     Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
116981     prereqAll |= x;
116982     extraRight = x-1;  /* ON clause terms may not be used with an index
116983                        ** on left table of a LEFT JOIN.  Ticket #3015 */
116984   }
116985   pTerm->prereqAll = prereqAll;
116986   pTerm->leftCursor = -1;
116987   pTerm->iParent = -1;
116988   pTerm->eOperator = 0;
116989   if( allowedOp(op) ){
116990     Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
116991     Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
116992     u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
116993     if( pLeft->op==TK_COLUMN ){
116994       pTerm->leftCursor = pLeft->iTable;
116995       pTerm->u.leftColumn = pLeft->iColumn;
116996       pTerm->eOperator = operatorMask(op) & opMask;
116997     }
116998     if( pRight && pRight->op==TK_COLUMN ){
116999       WhereTerm *pNew;
117000       Expr *pDup;
117001       u16 eExtraOp = 0;        /* Extra bits for pNew->eOperator */
117002       if( pTerm->leftCursor>=0 ){
117003         int idxNew;
117004         pDup = sqlite3ExprDup(db, pExpr, 0);
117005         if( db->mallocFailed ){
117006           sqlite3ExprDelete(db, pDup);
117007           return;
117008         }
117009         idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
117010         if( idxNew==0 ) return;
117011         pNew = &pWC->a[idxNew];
117012         markTermAsChild(pWC, idxNew, idxTerm);
117013         pTerm = &pWC->a[idxTerm];
117014         pTerm->wtFlags |= TERM_COPIED;
117015         if( pExpr->op==TK_EQ
117016          && !ExprHasProperty(pExpr, EP_FromJoin)
117017          && OptimizationEnabled(db, SQLITE_Transitive)
117018         ){
117019           pTerm->eOperator |= WO_EQUIV;
117020           eExtraOp = WO_EQUIV;
117021         }
117022       }else{
117023         pDup = pExpr;
117024         pNew = pTerm;
117025       }
117026       exprCommute(pParse, pDup);
117027       pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
117028       pNew->leftCursor = pLeft->iTable;
117029       pNew->u.leftColumn = pLeft->iColumn;
117030       testcase( (prereqLeft | extraRight) != prereqLeft );
117031       pNew->prereqRight = prereqLeft | extraRight;
117032       pNew->prereqAll = prereqAll;
117033       pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
117034     }
117035   }
117036
117037 #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
117038   /* If a term is the BETWEEN operator, create two new virtual terms
117039   ** that define the range that the BETWEEN implements.  For example:
117040   **
117041   **      a BETWEEN b AND c
117042   **
117043   ** is converted into:
117044   **
117045   **      (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
117046   **
117047   ** The two new terms are added onto the end of the WhereClause object.
117048   ** The new terms are "dynamic" and are children of the original BETWEEN
117049   ** term.  That means that if the BETWEEN term is coded, the children are
117050   ** skipped.  Or, if the children are satisfied by an index, the original
117051   ** BETWEEN term is skipped.
117052   */
117053   else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
117054     ExprList *pList = pExpr->x.pList;
117055     int i;
117056     static const u8 ops[] = {TK_GE, TK_LE};
117057     assert( pList!=0 );
117058     assert( pList->nExpr==2 );
117059     for(i=0; i<2; i++){
117060       Expr *pNewExpr;
117061       int idxNew;
117062       pNewExpr = sqlite3PExpr(pParse, ops[i], 
117063                              sqlite3ExprDup(db, pExpr->pLeft, 0),
117064                              sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
117065       transferJoinMarkings(pNewExpr, pExpr);
117066       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
117067       testcase( idxNew==0 );
117068       exprAnalyze(pSrc, pWC, idxNew);
117069       pTerm = &pWC->a[idxTerm];
117070       markTermAsChild(pWC, idxNew, idxTerm);
117071     }
117072   }
117073 #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
117074
117075 #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
117076   /* Analyze a term that is composed of two or more subterms connected by
117077   ** an OR operator.
117078   */
117079   else if( pExpr->op==TK_OR ){
117080     assert( pWC->op==TK_AND );
117081     exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
117082     pTerm = &pWC->a[idxTerm];
117083   }
117084 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
117085
117086 #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
117087   /* Add constraints to reduce the search space on a LIKE or GLOB
117088   ** operator.
117089   **
117090   ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
117091   **
117092   **          x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
117093   **
117094   ** The last character of the prefix "abc" is incremented to form the
117095   ** termination condition "abd".  If case is not significant (the default
117096   ** for LIKE) then the lower-bound is made all uppercase and the upper-
117097   ** bound is made all lowercase so that the bounds also work when comparing
117098   ** BLOBs.
117099   */
117100   if( pWC->op==TK_AND 
117101    && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
117102   ){
117103     Expr *pLeft;       /* LHS of LIKE/GLOB operator */
117104     Expr *pStr2;       /* Copy of pStr1 - RHS of LIKE/GLOB operator */
117105     Expr *pNewExpr1;
117106     Expr *pNewExpr2;
117107     int idxNew1;
117108     int idxNew2;
117109     const char *zCollSeqName;     /* Name of collating sequence */
117110     const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
117111
117112     pLeft = pExpr->x.pList->a[1].pExpr;
117113     pStr2 = sqlite3ExprDup(db, pStr1, 0);
117114
117115     /* Convert the lower bound to upper-case and the upper bound to
117116     ** lower-case (upper-case is less than lower-case in ASCII) so that
117117     ** the range constraints also work for BLOBs
117118     */
117119     if( noCase && !pParse->db->mallocFailed ){
117120       int i;
117121       char c;
117122       pTerm->wtFlags |= TERM_LIKE;
117123       for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
117124         pStr1->u.zToken[i] = sqlite3Toupper(c);
117125         pStr2->u.zToken[i] = sqlite3Tolower(c);
117126       }
117127     }
117128
117129     if( !db->mallocFailed ){
117130       u8 c, *pC;       /* Last character before the first wildcard */
117131       pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
117132       c = *pC;
117133       if( noCase ){
117134         /* The point is to increment the last character before the first
117135         ** wildcard.  But if we increment '@', that will push it into the
117136         ** alphabetic range where case conversions will mess up the 
117137         ** inequality.  To avoid this, make sure to also run the full
117138         ** LIKE on all candidate expressions by clearing the isComplete flag
117139         */
117140         if( c=='A'-1 ) isComplete = 0;
117141         c = sqlite3UpperToLower[c];
117142       }
117143       *pC = c + 1;
117144     }
117145     zCollSeqName = noCase ? "NOCASE" : "BINARY";
117146     pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
117147     pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
117148            sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
117149            pStr1, 0);
117150     transferJoinMarkings(pNewExpr1, pExpr);
117151     idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
117152     testcase( idxNew1==0 );
117153     exprAnalyze(pSrc, pWC, idxNew1);
117154     pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
117155     pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
117156            sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
117157            pStr2, 0);
117158     transferJoinMarkings(pNewExpr2, pExpr);
117159     idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
117160     testcase( idxNew2==0 );
117161     exprAnalyze(pSrc, pWC, idxNew2);
117162     pTerm = &pWC->a[idxTerm];
117163     if( isComplete ){
117164       markTermAsChild(pWC, idxNew1, idxTerm);
117165       markTermAsChild(pWC, idxNew2, idxTerm);
117166     }
117167   }
117168 #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
117169
117170 #ifndef SQLITE_OMIT_VIRTUALTABLE
117171   /* Add a WO_MATCH auxiliary term to the constraint set if the
117172   ** current expression is of the form:  column MATCH expr.
117173   ** This information is used by the xBestIndex methods of
117174   ** virtual tables.  The native query optimizer does not attempt
117175   ** to do anything with MATCH functions.
117176   */
117177   if( isMatchOfColumn(pExpr) ){
117178     int idxNew;
117179     Expr *pRight, *pLeft;
117180     WhereTerm *pNewTerm;
117181     Bitmask prereqColumn, prereqExpr;
117182
117183     pRight = pExpr->x.pList->a[0].pExpr;
117184     pLeft = pExpr->x.pList->a[1].pExpr;
117185     prereqExpr = exprTableUsage(pMaskSet, pRight);
117186     prereqColumn = exprTableUsage(pMaskSet, pLeft);
117187     if( (prereqExpr & prereqColumn)==0 ){
117188       Expr *pNewExpr;
117189       pNewExpr = sqlite3PExpr(pParse, TK_MATCH, 
117190                               0, sqlite3ExprDup(db, pRight, 0), 0);
117191       idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
117192       testcase( idxNew==0 );
117193       pNewTerm = &pWC->a[idxNew];
117194       pNewTerm->prereqRight = prereqExpr;
117195       pNewTerm->leftCursor = pLeft->iTable;
117196       pNewTerm->u.leftColumn = pLeft->iColumn;
117197       pNewTerm->eOperator = WO_MATCH;
117198       markTermAsChild(pWC, idxNew, idxTerm);
117199       pTerm = &pWC->a[idxTerm];
117200       pTerm->wtFlags |= TERM_COPIED;
117201       pNewTerm->prereqAll = pTerm->prereqAll;
117202     }
117203   }
117204 #endif /* SQLITE_OMIT_VIRTUALTABLE */
117205
117206 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
117207   /* When sqlite_stat3 histogram data is available an operator of the
117208   ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
117209   ** as "x>NULL" if x is not an INTEGER PRIMARY KEY.  So construct a
117210   ** virtual term of that form.
117211   **
117212   ** Note that the virtual term must be tagged with TERM_VNULL.  This
117213   ** TERM_VNULL tag will suppress the not-null check at the beginning
117214   ** of the loop.  Without the TERM_VNULL flag, the not-null check at
117215   ** the start of the loop will prevent any results from being returned.
117216   */
117217   if( pExpr->op==TK_NOTNULL
117218    && pExpr->pLeft->op==TK_COLUMN
117219    && pExpr->pLeft->iColumn>=0
117220    && OptimizationEnabled(db, SQLITE_Stat34)
117221   ){
117222     Expr *pNewExpr;
117223     Expr *pLeft = pExpr->pLeft;
117224     int idxNew;
117225     WhereTerm *pNewTerm;
117226
117227     pNewExpr = sqlite3PExpr(pParse, TK_GT,
117228                             sqlite3ExprDup(db, pLeft, 0),
117229                             sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
117230
117231     idxNew = whereClauseInsert(pWC, pNewExpr,
117232                               TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
117233     if( idxNew ){
117234       pNewTerm = &pWC->a[idxNew];
117235       pNewTerm->prereqRight = 0;
117236       pNewTerm->leftCursor = pLeft->iTable;
117237       pNewTerm->u.leftColumn = pLeft->iColumn;
117238       pNewTerm->eOperator = WO_GT;
117239       markTermAsChild(pWC, idxNew, idxTerm);
117240       pTerm = &pWC->a[idxTerm];
117241       pTerm->wtFlags |= TERM_COPIED;
117242       pNewTerm->prereqAll = pTerm->prereqAll;
117243     }
117244   }
117245 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
117246
117247   /* Prevent ON clause terms of a LEFT JOIN from being used to drive
117248   ** an index for tables to the left of the join.
117249   */
117250   pTerm->prereqRight |= extraRight;
117251 }
117252
117253 /*
117254 ** This function searches pList for an entry that matches the iCol-th column
117255 ** of index pIdx.
117256 **
117257 ** If such an expression is found, its index in pList->a[] is returned. If
117258 ** no expression is found, -1 is returned.
117259 */
117260 static int findIndexCol(
117261   Parse *pParse,                  /* Parse context */
117262   ExprList *pList,                /* Expression list to search */
117263   int iBase,                      /* Cursor for table associated with pIdx */
117264   Index *pIdx,                    /* Index to match column of */
117265   int iCol                        /* Column of index to match */
117266 ){
117267   int i;
117268   const char *zColl = pIdx->azColl[iCol];
117269
117270   for(i=0; i<pList->nExpr; i++){
117271     Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
117272     if( p->op==TK_COLUMN
117273      && p->iColumn==pIdx->aiColumn[iCol]
117274      && p->iTable==iBase
117275     ){
117276       CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
117277       if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
117278         return i;
117279       }
117280     }
117281   }
117282
117283   return -1;
117284 }
117285
117286 /*
117287 ** Return true if the DISTINCT expression-list passed as the third argument
117288 ** is redundant.
117289 **
117290 ** A DISTINCT list is redundant if the database contains some subset of
117291 ** columns that are unique and non-null.
117292 */
117293 static int isDistinctRedundant(
117294   Parse *pParse,            /* Parsing context */
117295   SrcList *pTabList,        /* The FROM clause */
117296   WhereClause *pWC,         /* The WHERE clause */
117297   ExprList *pDistinct       /* The result set that needs to be DISTINCT */
117298 ){
117299   Table *pTab;
117300   Index *pIdx;
117301   int i;                          
117302   int iBase;
117303
117304   /* If there is more than one table or sub-select in the FROM clause of
117305   ** this query, then it will not be possible to show that the DISTINCT 
117306   ** clause is redundant. */
117307   if( pTabList->nSrc!=1 ) return 0;
117308   iBase = pTabList->a[0].iCursor;
117309   pTab = pTabList->a[0].pTab;
117310
117311   /* If any of the expressions is an IPK column on table iBase, then return 
117312   ** true. Note: The (p->iTable==iBase) part of this test may be false if the
117313   ** current SELECT is a correlated sub-query.
117314   */
117315   for(i=0; i<pDistinct->nExpr; i++){
117316     Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
117317     if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
117318   }
117319
117320   /* Loop through all indices on the table, checking each to see if it makes
117321   ** the DISTINCT qualifier redundant. It does so if:
117322   **
117323   **   1. The index is itself UNIQUE, and
117324   **
117325   **   2. All of the columns in the index are either part of the pDistinct
117326   **      list, or else the WHERE clause contains a term of the form "col=X",
117327   **      where X is a constant value. The collation sequences of the
117328   **      comparison and select-list expressions must match those of the index.
117329   **
117330   **   3. All of those index columns for which the WHERE clause does not
117331   **      contain a "col=X" term are subject to a NOT NULL constraint.
117332   */
117333   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
117334     if( !IsUniqueIndex(pIdx) ) continue;
117335     for(i=0; i<pIdx->nKeyCol; i++){
117336       i16 iCol = pIdx->aiColumn[i];
117337       if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
117338         int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
117339         if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
117340           break;
117341         }
117342       }
117343     }
117344     if( i==pIdx->nKeyCol ){
117345       /* This index implies that the DISTINCT qualifier is redundant. */
117346       return 1;
117347     }
117348   }
117349
117350   return 0;
117351 }
117352
117353
117354 /*
117355 ** Estimate the logarithm of the input value to base 2.
117356 */
117357 static LogEst estLog(LogEst N){
117358   return N<=10 ? 0 : sqlite3LogEst(N) - 33;
117359 }
117360
117361 /*
117362 ** Two routines for printing the content of an sqlite3_index_info
117363 ** structure.  Used for testing and debugging only.  If neither
117364 ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
117365 ** are no-ops.
117366 */
117367 #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
117368 static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
117369   int i;
117370   if( !sqlite3WhereTrace ) return;
117371   for(i=0; i<p->nConstraint; i++){
117372     sqlite3DebugPrintf("  constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
117373        i,
117374        p->aConstraint[i].iColumn,
117375        p->aConstraint[i].iTermOffset,
117376        p->aConstraint[i].op,
117377        p->aConstraint[i].usable);
117378   }
117379   for(i=0; i<p->nOrderBy; i++){
117380     sqlite3DebugPrintf("  orderby[%d]: col=%d desc=%d\n",
117381        i,
117382        p->aOrderBy[i].iColumn,
117383        p->aOrderBy[i].desc);
117384   }
117385 }
117386 static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
117387   int i;
117388   if( !sqlite3WhereTrace ) return;
117389   for(i=0; i<p->nConstraint; i++){
117390     sqlite3DebugPrintf("  usage[%d]: argvIdx=%d omit=%d\n",
117391        i,
117392        p->aConstraintUsage[i].argvIndex,
117393        p->aConstraintUsage[i].omit);
117394   }
117395   sqlite3DebugPrintf("  idxNum=%d\n", p->idxNum);
117396   sqlite3DebugPrintf("  idxStr=%s\n", p->idxStr);
117397   sqlite3DebugPrintf("  orderByConsumed=%d\n", p->orderByConsumed);
117398   sqlite3DebugPrintf("  estimatedCost=%g\n", p->estimatedCost);
117399   sqlite3DebugPrintf("  estimatedRows=%lld\n", p->estimatedRows);
117400 }
117401 #else
117402 #define TRACE_IDX_INPUTS(A)
117403 #define TRACE_IDX_OUTPUTS(A)
117404 #endif
117405
117406 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
117407 /*
117408 ** Return TRUE if the WHERE clause term pTerm is of a form where it
117409 ** could be used with an index to access pSrc, assuming an appropriate
117410 ** index existed.
117411 */
117412 static int termCanDriveIndex(
117413   WhereTerm *pTerm,              /* WHERE clause term to check */
117414   struct SrcList_item *pSrc,     /* Table we are trying to access */
117415   Bitmask notReady               /* Tables in outer loops of the join */
117416 ){
117417   char aff;
117418   if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
117419   if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
117420   if( (pTerm->prereqRight & notReady)!=0 ) return 0;
117421   if( pTerm->u.leftColumn<0 ) return 0;
117422   aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
117423   if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
117424   return 1;
117425 }
117426 #endif
117427
117428
117429 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
117430 /*
117431 ** Generate code to construct the Index object for an automatic index
117432 ** and to set up the WhereLevel object pLevel so that the code generator
117433 ** makes use of the automatic index.
117434 */
117435 static void constructAutomaticIndex(
117436   Parse *pParse,              /* The parsing context */
117437   WhereClause *pWC,           /* The WHERE clause */
117438   struct SrcList_item *pSrc,  /* The FROM clause term to get the next index */
117439   Bitmask notReady,           /* Mask of cursors that are not available */
117440   WhereLevel *pLevel          /* Write new index here */
117441 ){
117442   int nKeyCol;                /* Number of columns in the constructed index */
117443   WhereTerm *pTerm;           /* A single term of the WHERE clause */
117444   WhereTerm *pWCEnd;          /* End of pWC->a[] */
117445   Index *pIdx;                /* Object describing the transient index */
117446   Vdbe *v;                    /* Prepared statement under construction */
117447   int addrInit;               /* Address of the initialization bypass jump */
117448   Table *pTable;              /* The table being indexed */
117449   int addrTop;                /* Top of the index fill loop */
117450   int regRecord;              /* Register holding an index record */
117451   int n;                      /* Column counter */
117452   int i;                      /* Loop counter */
117453   int mxBitCol;               /* Maximum column in pSrc->colUsed */
117454   CollSeq *pColl;             /* Collating sequence to on a column */
117455   WhereLoop *pLoop;           /* The Loop object */
117456   char *zNotUsed;             /* Extra space on the end of pIdx */
117457   Bitmask idxCols;            /* Bitmap of columns used for indexing */
117458   Bitmask extraCols;          /* Bitmap of additional columns */
117459   u8 sentWarning = 0;         /* True if a warnning has been issued */
117460   Expr *pPartial = 0;         /* Partial Index Expression */
117461   int iContinue = 0;          /* Jump here to skip excluded rows */
117462
117463   /* Generate code to skip over the creation and initialization of the
117464   ** transient index on 2nd and subsequent iterations of the loop. */
117465   v = pParse->pVdbe;
117466   assert( v!=0 );
117467   addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
117468
117469   /* Count the number of columns that will be added to the index
117470   ** and used to match WHERE clause constraints */
117471   nKeyCol = 0;
117472   pTable = pSrc->pTab;
117473   pWCEnd = &pWC->a[pWC->nTerm];
117474   pLoop = pLevel->pWLoop;
117475   idxCols = 0;
117476   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
117477     Expr *pExpr = pTerm->pExpr;
117478     assert( !ExprHasProperty(pExpr, EP_FromJoin)    /* prereq always non-zero */
117479          || pExpr->iRightJoinTable!=pSrc->iCursor   /*   for the right-hand   */
117480          || pLoop->prereq!=0 );                     /*   table of a LEFT JOIN */
117481     if( pLoop->prereq==0
117482      && (pTerm->wtFlags & TERM_VIRTUAL)==0
117483      && !ExprHasProperty(pExpr, EP_FromJoin)
117484      && sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor) ){
117485       pPartial = sqlite3ExprAnd(pParse->db, pPartial,
117486                                 sqlite3ExprDup(pParse->db, pExpr, 0));
117487     }
117488     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
117489       int iCol = pTerm->u.leftColumn;
117490       Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
117491       testcase( iCol==BMS );
117492       testcase( iCol==BMS-1 );
117493       if( !sentWarning ){
117494         sqlite3_log(SQLITE_WARNING_AUTOINDEX,
117495             "automatic index on %s(%s)", pTable->zName,
117496             pTable->aCol[iCol].zName);
117497         sentWarning = 1;
117498       }
117499       if( (idxCols & cMask)==0 ){
117500         if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ){
117501           goto end_auto_index_create;
117502         }
117503         pLoop->aLTerm[nKeyCol++] = pTerm;
117504         idxCols |= cMask;
117505       }
117506     }
117507   }
117508   assert( nKeyCol>0 );
117509   pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
117510   pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
117511                      | WHERE_AUTO_INDEX;
117512
117513   /* Count the number of additional columns needed to create a
117514   ** covering index.  A "covering index" is an index that contains all
117515   ** columns that are needed by the query.  With a covering index, the
117516   ** original table never needs to be accessed.  Automatic indices must
117517   ** be a covering index because the index will not be updated if the
117518   ** original table changes and the index and table cannot both be used
117519   ** if they go out of sync.
117520   */
117521   extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
117522   mxBitCol = MIN(BMS-1,pTable->nCol);
117523   testcase( pTable->nCol==BMS-1 );
117524   testcase( pTable->nCol==BMS-2 );
117525   for(i=0; i<mxBitCol; i++){
117526     if( extraCols & MASKBIT(i) ) nKeyCol++;
117527   }
117528   if( pSrc->colUsed & MASKBIT(BMS-1) ){
117529     nKeyCol += pTable->nCol - BMS + 1;
117530   }
117531
117532   /* Construct the Index object to describe this index */
117533   pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
117534   if( pIdx==0 ) goto end_auto_index_create;
117535   pLoop->u.btree.pIndex = pIdx;
117536   pIdx->zName = "auto-index";
117537   pIdx->pTable = pTable;
117538   n = 0;
117539   idxCols = 0;
117540   for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
117541     if( termCanDriveIndex(pTerm, pSrc, notReady) ){
117542       int iCol = pTerm->u.leftColumn;
117543       Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
117544       testcase( iCol==BMS-1 );
117545       testcase( iCol==BMS );
117546       if( (idxCols & cMask)==0 ){
117547         Expr *pX = pTerm->pExpr;
117548         idxCols |= cMask;
117549         pIdx->aiColumn[n] = pTerm->u.leftColumn;
117550         pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
117551         pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
117552         n++;
117553       }
117554     }
117555   }
117556   assert( (u32)n==pLoop->u.btree.nEq );
117557
117558   /* Add additional columns needed to make the automatic index into
117559   ** a covering index */
117560   for(i=0; i<mxBitCol; i++){
117561     if( extraCols & MASKBIT(i) ){
117562       pIdx->aiColumn[n] = i;
117563       pIdx->azColl[n] = "BINARY";
117564       n++;
117565     }
117566   }
117567   if( pSrc->colUsed & MASKBIT(BMS-1) ){
117568     for(i=BMS-1; i<pTable->nCol; i++){
117569       pIdx->aiColumn[n] = i;
117570       pIdx->azColl[n] = "BINARY";
117571       n++;
117572     }
117573   }
117574   assert( n==nKeyCol );
117575   pIdx->aiColumn[n] = -1;
117576   pIdx->azColl[n] = "BINARY";
117577
117578   /* Create the automatic index */
117579   assert( pLevel->iIdxCur>=0 );
117580   pLevel->iIdxCur = pParse->nTab++;
117581   sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
117582   sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
117583   VdbeComment((v, "for %s", pTable->zName));
117584
117585   /* Fill the automatic index with content */
117586   sqlite3ExprCachePush(pParse);
117587   addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
117588   if( pPartial ){
117589     iContinue = sqlite3VdbeMakeLabel(v);
117590     sqlite3ExprIfFalse(pParse, pPartial, iContinue, SQLITE_JUMPIFNULL);
117591     pLoop->wsFlags |= WHERE_PARTIALIDX;
117592   }
117593   regRecord = sqlite3GetTempReg(pParse);
117594   sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
117595   sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
117596   sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
117597   if( pPartial ) sqlite3VdbeResolveLabel(v, iContinue);
117598   sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
117599   sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
117600   sqlite3VdbeJumpHere(v, addrTop);
117601   sqlite3ReleaseTempReg(pParse, regRecord);
117602   sqlite3ExprCachePop(pParse);
117603   
117604   /* Jump here when skipping the initialization */
117605   sqlite3VdbeJumpHere(v, addrInit);
117606
117607 end_auto_index_create:
117608   sqlite3ExprDelete(pParse->db, pPartial);
117609 }
117610 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
117611
117612 #ifndef SQLITE_OMIT_VIRTUALTABLE
117613 /*
117614 ** Allocate and populate an sqlite3_index_info structure. It is the 
117615 ** responsibility of the caller to eventually release the structure
117616 ** by passing the pointer returned by this function to sqlite3_free().
117617 */
117618 static sqlite3_index_info *allocateIndexInfo(
117619   Parse *pParse,
117620   WhereClause *pWC,
117621   struct SrcList_item *pSrc,
117622   ExprList *pOrderBy
117623 ){
117624   int i, j;
117625   int nTerm;
117626   struct sqlite3_index_constraint *pIdxCons;
117627   struct sqlite3_index_orderby *pIdxOrderBy;
117628   struct sqlite3_index_constraint_usage *pUsage;
117629   WhereTerm *pTerm;
117630   int nOrderBy;
117631   sqlite3_index_info *pIdxInfo;
117632
117633   /* Count the number of possible WHERE clause constraints referring
117634   ** to this virtual table */
117635   for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
117636     if( pTerm->leftCursor != pSrc->iCursor ) continue;
117637     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
117638     testcase( pTerm->eOperator & WO_IN );
117639     testcase( pTerm->eOperator & WO_ISNULL );
117640     testcase( pTerm->eOperator & WO_ALL );
117641     if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
117642     if( pTerm->wtFlags & TERM_VNULL ) continue;
117643     nTerm++;
117644   }
117645
117646   /* If the ORDER BY clause contains only columns in the current 
117647   ** virtual table then allocate space for the aOrderBy part of
117648   ** the sqlite3_index_info structure.
117649   */
117650   nOrderBy = 0;
117651   if( pOrderBy ){
117652     int n = pOrderBy->nExpr;
117653     for(i=0; i<n; i++){
117654       Expr *pExpr = pOrderBy->a[i].pExpr;
117655       if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
117656     }
117657     if( i==n){
117658       nOrderBy = n;
117659     }
117660   }
117661
117662   /* Allocate the sqlite3_index_info structure
117663   */
117664   pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
117665                            + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
117666                            + sizeof(*pIdxOrderBy)*nOrderBy );
117667   if( pIdxInfo==0 ){
117668     sqlite3ErrorMsg(pParse, "out of memory");
117669     return 0;
117670   }
117671
117672   /* Initialize the structure.  The sqlite3_index_info structure contains
117673   ** many fields that are declared "const" to prevent xBestIndex from
117674   ** changing them.  We have to do some funky casting in order to
117675   ** initialize those fields.
117676   */
117677   pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
117678   pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
117679   pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
117680   *(int*)&pIdxInfo->nConstraint = nTerm;
117681   *(int*)&pIdxInfo->nOrderBy = nOrderBy;
117682   *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
117683   *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
117684   *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
117685                                                                    pUsage;
117686
117687   for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
117688     u8 op;
117689     if( pTerm->leftCursor != pSrc->iCursor ) continue;
117690     assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
117691     testcase( pTerm->eOperator & WO_IN );
117692     testcase( pTerm->eOperator & WO_ISNULL );
117693     testcase( pTerm->eOperator & WO_ALL );
117694     if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
117695     if( pTerm->wtFlags & TERM_VNULL ) continue;
117696     pIdxCons[j].iColumn = pTerm->u.leftColumn;
117697     pIdxCons[j].iTermOffset = i;
117698     op = (u8)pTerm->eOperator & WO_ALL;
117699     if( op==WO_IN ) op = WO_EQ;
117700     pIdxCons[j].op = op;
117701     /* The direct assignment in the previous line is possible only because
117702     ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical.  The
117703     ** following asserts verify this fact. */
117704     assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
117705     assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
117706     assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
117707     assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
117708     assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
117709     assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
117710     assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
117711     j++;
117712   }
117713   for(i=0; i<nOrderBy; i++){
117714     Expr *pExpr = pOrderBy->a[i].pExpr;
117715     pIdxOrderBy[i].iColumn = pExpr->iColumn;
117716     pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
117717   }
117718
117719   return pIdxInfo;
117720 }
117721
117722 /*
117723 ** The table object reference passed as the second argument to this function
117724 ** must represent a virtual table. This function invokes the xBestIndex()
117725 ** method of the virtual table with the sqlite3_index_info object that
117726 ** comes in as the 3rd argument to this function.
117727 **
117728 ** If an error occurs, pParse is populated with an error message and a
117729 ** non-zero value is returned. Otherwise, 0 is returned and the output
117730 ** part of the sqlite3_index_info structure is left populated.
117731 **
117732 ** Whether or not an error is returned, it is the responsibility of the
117733 ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
117734 ** that this is required.
117735 */
117736 static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
117737   sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
117738   int i;
117739   int rc;
117740
117741   TRACE_IDX_INPUTS(p);
117742   rc = pVtab->pModule->xBestIndex(pVtab, p);
117743   TRACE_IDX_OUTPUTS(p);
117744
117745   if( rc!=SQLITE_OK ){
117746     if( rc==SQLITE_NOMEM ){
117747       pParse->db->mallocFailed = 1;
117748     }else if( !pVtab->zErrMsg ){
117749       sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
117750     }else{
117751       sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
117752     }
117753   }
117754   sqlite3_free(pVtab->zErrMsg);
117755   pVtab->zErrMsg = 0;
117756
117757   for(i=0; i<p->nConstraint; i++){
117758     if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
117759       sqlite3ErrorMsg(pParse, 
117760           "table %s: xBestIndex returned an invalid plan", pTab->zName);
117761     }
117762   }
117763
117764   return pParse->nErr;
117765 }
117766 #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
117767
117768 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
117769 /*
117770 ** Estimate the location of a particular key among all keys in an
117771 ** index.  Store the results in aStat as follows:
117772 **
117773 **    aStat[0]      Est. number of rows less than pRec
117774 **    aStat[1]      Est. number of rows equal to pRec
117775 **
117776 ** Return the index of the sample that is the smallest sample that
117777 ** is greater than or equal to pRec. Note that this index is not an index
117778 ** into the aSample[] array - it is an index into a virtual set of samples
117779 ** based on the contents of aSample[] and the number of fields in record 
117780 ** pRec. 
117781 */
117782 static int whereKeyStats(
117783   Parse *pParse,              /* Database connection */
117784   Index *pIdx,                /* Index to consider domain of */
117785   UnpackedRecord *pRec,       /* Vector of values to consider */
117786   int roundUp,                /* Round up if true.  Round down if false */
117787   tRowcnt *aStat              /* OUT: stats written here */
117788 ){
117789   IndexSample *aSample = pIdx->aSample;
117790   int iCol;                   /* Index of required stats in anEq[] etc. */
117791   int i;                      /* Index of first sample >= pRec */
117792   int iSample;                /* Smallest sample larger than or equal to pRec */
117793   int iMin = 0;               /* Smallest sample not yet tested */
117794   int iTest;                  /* Next sample to test */
117795   int res;                    /* Result of comparison operation */
117796   int nField;                 /* Number of fields in pRec */
117797   tRowcnt iLower = 0;         /* anLt[] + anEq[] of largest sample pRec is > */
117798
117799 #ifndef SQLITE_DEBUG
117800   UNUSED_PARAMETER( pParse );
117801 #endif
117802   assert( pRec!=0 );
117803   assert( pIdx->nSample>0 );
117804   assert( pRec->nField>0 && pRec->nField<=pIdx->nSampleCol );
117805
117806   /* Do a binary search to find the first sample greater than or equal
117807   ** to pRec. If pRec contains a single field, the set of samples to search
117808   ** is simply the aSample[] array. If the samples in aSample[] contain more
117809   ** than one fields, all fields following the first are ignored.
117810   **
117811   ** If pRec contains N fields, where N is more than one, then as well as the
117812   ** samples in aSample[] (truncated to N fields), the search also has to
117813   ** consider prefixes of those samples. For example, if the set of samples
117814   ** in aSample is:
117815   **
117816   **     aSample[0] = (a, 5) 
117817   **     aSample[1] = (a, 10) 
117818   **     aSample[2] = (b, 5) 
117819   **     aSample[3] = (c, 100) 
117820   **     aSample[4] = (c, 105)
117821   **
117822   ** Then the search space should ideally be the samples above and the 
117823   ** unique prefixes [a], [b] and [c]. But since that is hard to organize, 
117824   ** the code actually searches this set:
117825   **
117826   **     0: (a) 
117827   **     1: (a, 5) 
117828   **     2: (a, 10) 
117829   **     3: (a, 10) 
117830   **     4: (b) 
117831   **     5: (b, 5) 
117832   **     6: (c) 
117833   **     7: (c, 100) 
117834   **     8: (c, 105)
117835   **     9: (c, 105)
117836   **
117837   ** For each sample in the aSample[] array, N samples are present in the
117838   ** effective sample array. In the above, samples 0 and 1 are based on 
117839   ** sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
117840   **
117841   ** Often, sample i of each block of N effective samples has (i+1) fields.
117842   ** Except, each sample may be extended to ensure that it is greater than or
117843   ** equal to the previous sample in the array. For example, in the above, 
117844   ** sample 2 is the first sample of a block of N samples, so at first it 
117845   ** appears that it should be 1 field in size. However, that would make it 
117846   ** smaller than sample 1, so the binary search would not work. As a result, 
117847   ** it is extended to two fields. The duplicates that this creates do not 
117848   ** cause any problems.
117849   */
117850   nField = pRec->nField;
117851   iCol = 0;
117852   iSample = pIdx->nSample * nField;
117853   do{
117854     int iSamp;                    /* Index in aSample[] of test sample */
117855     int n;                        /* Number of fields in test sample */
117856
117857     iTest = (iMin+iSample)/2;
117858     iSamp = iTest / nField;
117859     if( iSamp>0 ){
117860       /* The proposed effective sample is a prefix of sample aSample[iSamp].
117861       ** Specifically, the shortest prefix of at least (1 + iTest%nField) 
117862       ** fields that is greater than the previous effective sample.  */
117863       for(n=(iTest % nField) + 1; n<nField; n++){
117864         if( aSample[iSamp-1].anLt[n-1]!=aSample[iSamp].anLt[n-1] ) break;
117865       }
117866     }else{
117867       n = iTest + 1;
117868     }
117869
117870     pRec->nField = n;
117871     res = sqlite3VdbeRecordCompare(aSample[iSamp].n, aSample[iSamp].p, pRec);
117872     if( res<0 ){
117873       iLower = aSample[iSamp].anLt[n-1] + aSample[iSamp].anEq[n-1];
117874       iMin = iTest+1;
117875     }else if( res==0 && n<nField ){
117876       iLower = aSample[iSamp].anLt[n-1];
117877       iMin = iTest+1;
117878       res = -1;
117879     }else{
117880       iSample = iTest;
117881       iCol = n-1;
117882     }
117883   }while( res && iMin<iSample );
117884   i = iSample / nField;
117885
117886 #ifdef SQLITE_DEBUG
117887   /* The following assert statements check that the binary search code
117888   ** above found the right answer. This block serves no purpose other
117889   ** than to invoke the asserts.  */
117890   if( pParse->db->mallocFailed==0 ){
117891     if( res==0 ){
117892       /* If (res==0) is true, then pRec must be equal to sample i. */
117893       assert( i<pIdx->nSample );
117894       assert( iCol==nField-1 );
117895       pRec->nField = nField;
117896       assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec) 
117897            || pParse->db->mallocFailed 
117898       );
117899     }else{
117900       /* Unless i==pIdx->nSample, indicating that pRec is larger than
117901       ** all samples in the aSample[] array, pRec must be smaller than the
117902       ** (iCol+1) field prefix of sample i.  */
117903       assert( i<=pIdx->nSample && i>=0 );
117904       pRec->nField = iCol+1;
117905       assert( i==pIdx->nSample 
117906            || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
117907            || pParse->db->mallocFailed );
117908
117909       /* if i==0 and iCol==0, then record pRec is smaller than all samples
117910       ** in the aSample[] array. Otherwise, if (iCol>0) then pRec must
117911       ** be greater than or equal to the (iCol) field prefix of sample i.
117912       ** If (i>0), then pRec must also be greater than sample (i-1).  */
117913       if( iCol>0 ){
117914         pRec->nField = iCol;
117915         assert( sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)<=0
117916              || pParse->db->mallocFailed );
117917       }
117918       if( i>0 ){
117919         pRec->nField = nField;
117920         assert( sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
117921              || pParse->db->mallocFailed );
117922       }
117923     }
117924   }
117925 #endif /* ifdef SQLITE_DEBUG */
117926
117927   if( res==0 ){
117928     /* Record pRec is equal to sample i */
117929     assert( iCol==nField-1 );
117930     aStat[0] = aSample[i].anLt[iCol];
117931     aStat[1] = aSample[i].anEq[iCol];
117932   }else{
117933     /* At this point, the (iCol+1) field prefix of aSample[i] is the first 
117934     ** sample that is greater than pRec. Or, if i==pIdx->nSample then pRec
117935     ** is larger than all samples in the array. */
117936     tRowcnt iUpper, iGap;
117937     if( i>=pIdx->nSample ){
117938       iUpper = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
117939     }else{
117940       iUpper = aSample[i].anLt[iCol];
117941     }
117942
117943     if( iLower>=iUpper ){
117944       iGap = 0;
117945     }else{
117946       iGap = iUpper - iLower;
117947     }
117948     if( roundUp ){
117949       iGap = (iGap*2)/3;
117950     }else{
117951       iGap = iGap/3;
117952     }
117953     aStat[0] = iLower + iGap;
117954     aStat[1] = pIdx->aAvgEq[iCol];
117955   }
117956
117957   /* Restore the pRec->nField value before returning.  */
117958   pRec->nField = nField;
117959   return i;
117960 }
117961 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
117962
117963 /*
117964 ** If it is not NULL, pTerm is a term that provides an upper or lower
117965 ** bound on a range scan. Without considering pTerm, it is estimated 
117966 ** that the scan will visit nNew rows. This function returns the number
117967 ** estimated to be visited after taking pTerm into account.
117968 **
117969 ** If the user explicitly specified a likelihood() value for this term,
117970 ** then the return value is the likelihood multiplied by the number of
117971 ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
117972 ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
117973 */
117974 static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
117975   LogEst nRet = nNew;
117976   if( pTerm ){
117977     if( pTerm->truthProb<=0 ){
117978       nRet += pTerm->truthProb;
117979     }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
117980       nRet -= 20;        assert( 20==sqlite3LogEst(4) );
117981     }
117982   }
117983   return nRet;
117984 }
117985
117986 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
117987 /* 
117988 ** This function is called to estimate the number of rows visited by a
117989 ** range-scan on a skip-scan index. For example:
117990 **
117991 **   CREATE INDEX i1 ON t1(a, b, c);
117992 **   SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
117993 **
117994 ** Value pLoop->nOut is currently set to the estimated number of rows 
117995 ** visited for scanning (a=? AND b=?). This function reduces that estimate 
117996 ** by some factor to account for the (c BETWEEN ? AND ?) expression based
117997 ** on the stat4 data for the index. this scan will be peformed multiple 
117998 ** times (once for each (a,b) combination that matches a=?) is dealt with 
117999 ** by the caller.
118000 **
118001 ** It does this by scanning through all stat4 samples, comparing values
118002 ** extracted from pLower and pUpper with the corresponding column in each
118003 ** sample. If L and U are the number of samples found to be less than or
118004 ** equal to the values extracted from pLower and pUpper respectively, and
118005 ** N is the total number of samples, the pLoop->nOut value is adjusted
118006 ** as follows:
118007 **
118008 **   nOut = nOut * ( min(U - L, 1) / N )
118009 **
118010 ** If pLower is NULL, or a value cannot be extracted from the term, L is
118011 ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
118012 ** U is set to N.
118013 **
118014 ** Normally, this function sets *pbDone to 1 before returning. However,
118015 ** if no value can be extracted from either pLower or pUpper (and so the
118016 ** estimate of the number of rows delivered remains unchanged), *pbDone
118017 ** is left as is.
118018 **
118019 ** If an error occurs, an SQLite error code is returned. Otherwise, 
118020 ** SQLITE_OK.
118021 */
118022 static int whereRangeSkipScanEst(
118023   Parse *pParse,       /* Parsing & code generating context */
118024   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
118025   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
118026   WhereLoop *pLoop,    /* Update the .nOut value of this loop */
118027   int *pbDone          /* Set to true if at least one expr. value extracted */
118028 ){
118029   Index *p = pLoop->u.btree.pIndex;
118030   int nEq = pLoop->u.btree.nEq;
118031   sqlite3 *db = pParse->db;
118032   int nLower = -1;
118033   int nUpper = p->nSample+1;
118034   int rc = SQLITE_OK;
118035   int iCol = p->aiColumn[nEq];
118036   u8 aff = iCol>=0 ? p->pTable->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
118037   CollSeq *pColl;
118038   
118039   sqlite3_value *p1 = 0;          /* Value extracted from pLower */
118040   sqlite3_value *p2 = 0;          /* Value extracted from pUpper */
118041   sqlite3_value *pVal = 0;        /* Value extracted from record */
118042
118043   pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
118044   if( pLower ){
118045     rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
118046     nLower = 0;
118047   }
118048   if( pUpper && rc==SQLITE_OK ){
118049     rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
118050     nUpper = p2 ? 0 : p->nSample;
118051   }
118052
118053   if( p1 || p2 ){
118054     int i;
118055     int nDiff;
118056     for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
118057       rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
118058       if( rc==SQLITE_OK && p1 ){
118059         int res = sqlite3MemCompare(p1, pVal, pColl);
118060         if( res>=0 ) nLower++;
118061       }
118062       if( rc==SQLITE_OK && p2 ){
118063         int res = sqlite3MemCompare(p2, pVal, pColl);
118064         if( res>=0 ) nUpper++;
118065       }
118066     }
118067     nDiff = (nUpper - nLower);
118068     if( nDiff<=0 ) nDiff = 1;
118069
118070     /* If there is both an upper and lower bound specified, and the 
118071     ** comparisons indicate that they are close together, use the fallback
118072     ** method (assume that the scan visits 1/64 of the rows) for estimating
118073     ** the number of rows visited. Otherwise, estimate the number of rows
118074     ** using the method described in the header comment for this function. */
118075     if( nDiff!=1 || pUpper==0 || pLower==0 ){
118076       int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
118077       pLoop->nOut -= nAdjust;
118078       *pbDone = 1;
118079       WHERETRACE(0x10, ("range skip-scan regions: %u..%u  adjust=%d est=%d\n",
118080                            nLower, nUpper, nAdjust*-1, pLoop->nOut));
118081     }
118082
118083   }else{
118084     assert( *pbDone==0 );
118085   }
118086
118087   sqlite3ValueFree(p1);
118088   sqlite3ValueFree(p2);
118089   sqlite3ValueFree(pVal);
118090
118091   return rc;
118092 }
118093 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
118094
118095 /*
118096 ** This function is used to estimate the number of rows that will be visited
118097 ** by scanning an index for a range of values. The range may have an upper
118098 ** bound, a lower bound, or both. The WHERE clause terms that set the upper
118099 ** and lower bounds are represented by pLower and pUpper respectively. For
118100 ** example, assuming that index p is on t1(a):
118101 **
118102 **   ... FROM t1 WHERE a > ? AND a < ? ...
118103 **                    |_____|   |_____|
118104 **                       |         |
118105 **                     pLower    pUpper
118106 **
118107 ** If either of the upper or lower bound is not present, then NULL is passed in
118108 ** place of the corresponding WhereTerm.
118109 **
118110 ** The value in (pBuilder->pNew->u.btree.nEq) is the number of the index
118111 ** column subject to the range constraint. Or, equivalently, the number of
118112 ** equality constraints optimized by the proposed index scan. For example,
118113 ** assuming index p is on t1(a, b), and the SQL query is:
118114 **
118115 **   ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
118116 **
118117 ** then nEq is set to 1 (as the range restricted column, b, is the second 
118118 ** left-most column of the index). Or, if the query is:
118119 **
118120 **   ... FROM t1 WHERE a > ? AND a < ? ...
118121 **
118122 ** then nEq is set to 0.
118123 **
118124 ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
118125 ** number of rows that the index scan is expected to visit without 
118126 ** considering the range constraints. If nEq is 0, then *pnOut is the number of 
118127 ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
118128 ** to account for the range constraints pLower and pUpper.
118129 ** 
118130 ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
118131 ** used, a single range inequality reduces the search space by a factor of 4. 
118132 ** and a pair of constraints (x>? AND x<?) reduces the expected number of
118133 ** rows visited by a factor of 64.
118134 */
118135 static int whereRangeScanEst(
118136   Parse *pParse,       /* Parsing & code generating context */
118137   WhereLoopBuilder *pBuilder,
118138   WhereTerm *pLower,   /* Lower bound on the range. ex: "x>123" Might be NULL */
118139   WhereTerm *pUpper,   /* Upper bound on the range. ex: "x<455" Might be NULL */
118140   WhereLoop *pLoop     /* Modify the .nOut and maybe .rRun fields */
118141 ){
118142   int rc = SQLITE_OK;
118143   int nOut = pLoop->nOut;
118144   LogEst nNew;
118145
118146 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
118147   Index *p = pLoop->u.btree.pIndex;
118148   int nEq = pLoop->u.btree.nEq;
118149
118150   if( p->nSample>0 && nEq<p->nSampleCol ){
118151     if( nEq==pBuilder->nRecValid ){
118152       UnpackedRecord *pRec = pBuilder->pRec;
118153       tRowcnt a[2];
118154       u8 aff;
118155
118156       /* Variable iLower will be set to the estimate of the number of rows in 
118157       ** the index that are less than the lower bound of the range query. The
118158       ** lower bound being the concatenation of $P and $L, where $P is the
118159       ** key-prefix formed by the nEq values matched against the nEq left-most
118160       ** columns of the index, and $L is the value in pLower.
118161       **
118162       ** Or, if pLower is NULL or $L cannot be extracted from it (because it
118163       ** is not a simple variable or literal value), the lower bound of the
118164       ** range is $P. Due to a quirk in the way whereKeyStats() works, even
118165       ** if $L is available, whereKeyStats() is called for both ($P) and 
118166       ** ($P:$L) and the larger of the two returned values is used.
118167       **
118168       ** Similarly, iUpper is to be set to the estimate of the number of rows
118169       ** less than the upper bound of the range query. Where the upper bound
118170       ** is either ($P) or ($P:$U). Again, even if $U is available, both values
118171       ** of iUpper are requested of whereKeyStats() and the smaller used.
118172       **
118173       ** The number of rows between the two bounds is then just iUpper-iLower.
118174       */
118175       tRowcnt iLower;     /* Rows less than the lower bound */
118176       tRowcnt iUpper;     /* Rows less than the upper bound */
118177       int iLwrIdx = -2;   /* aSample[] for the lower bound */
118178       int iUprIdx = -1;   /* aSample[] for the upper bound */
118179
118180       if( pRec ){
118181         testcase( pRec->nField!=pBuilder->nRecValid );
118182         pRec->nField = pBuilder->nRecValid;
118183       }
118184       if( nEq==p->nKeyCol ){
118185         aff = SQLITE_AFF_INTEGER;
118186       }else{
118187         aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
118188       }
118189       /* Determine iLower and iUpper using ($P) only. */
118190       if( nEq==0 ){
118191         iLower = 0;
118192         iUpper = p->nRowEst0;
118193       }else{
118194         /* Note: this call could be optimized away - since the same values must 
118195         ** have been requested when testing key $P in whereEqualScanEst().  */
118196         whereKeyStats(pParse, p, pRec, 0, a);
118197         iLower = a[0];
118198         iUpper = a[0] + a[1];
118199       }
118200
118201       assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
118202       assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
118203       assert( p->aSortOrder!=0 );
118204       if( p->aSortOrder[nEq] ){
118205         /* The roles of pLower and pUpper are swapped for a DESC index */
118206         SWAP(WhereTerm*, pLower, pUpper);
118207       }
118208
118209       /* If possible, improve on the iLower estimate using ($P:$L). */
118210       if( pLower ){
118211         int bOk;                    /* True if value is extracted from pExpr */
118212         Expr *pExpr = pLower->pExpr->pRight;
118213         rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
118214         if( rc==SQLITE_OK && bOk ){
118215           tRowcnt iNew;
118216           iLwrIdx = whereKeyStats(pParse, p, pRec, 0, a);
118217           iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
118218           if( iNew>iLower ) iLower = iNew;
118219           nOut--;
118220           pLower = 0;
118221         }
118222       }
118223
118224       /* If possible, improve on the iUpper estimate using ($P:$U). */
118225       if( pUpper ){
118226         int bOk;                    /* True if value is extracted from pExpr */
118227         Expr *pExpr = pUpper->pExpr->pRight;
118228         rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
118229         if( rc==SQLITE_OK && bOk ){
118230           tRowcnt iNew;
118231           iUprIdx = whereKeyStats(pParse, p, pRec, 1, a);
118232           iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
118233           if( iNew<iUpper ) iUpper = iNew;
118234           nOut--;
118235           pUpper = 0;
118236         }
118237       }
118238
118239       pBuilder->pRec = pRec;
118240       if( rc==SQLITE_OK ){
118241         if( iUpper>iLower ){
118242           nNew = sqlite3LogEst(iUpper - iLower);
118243           /* TUNING:  If both iUpper and iLower are derived from the same
118244           ** sample, then assume they are 4x more selective.  This brings
118245           ** the estimated selectivity more in line with what it would be
118246           ** if estimated without the use of STAT3/4 tables. */
118247           if( iLwrIdx==iUprIdx ) nNew -= 20;  assert( 20==sqlite3LogEst(4) );
118248         }else{
118249           nNew = 10;        assert( 10==sqlite3LogEst(2) );
118250         }
118251         if( nNew<nOut ){
118252           nOut = nNew;
118253         }
118254         WHERETRACE(0x10, ("STAT4 range scan: %u..%u  est=%d\n",
118255                            (u32)iLower, (u32)iUpper, nOut));
118256       }
118257     }else{
118258       int bDone = 0;
118259       rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
118260       if( bDone ) return rc;
118261     }
118262   }
118263 #else
118264   UNUSED_PARAMETER(pParse);
118265   UNUSED_PARAMETER(pBuilder);
118266   assert( pLower || pUpper );
118267 #endif
118268   assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
118269   nNew = whereRangeAdjust(pLower, nOut);
118270   nNew = whereRangeAdjust(pUpper, nNew);
118271
118272   /* TUNING: If there is both an upper and lower limit and neither limit
118273   ** has an application-defined likelihood(), assume the range is
118274   ** reduced by an additional 75%. This means that, by default, an open-ended
118275   ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
118276   ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
118277   ** match 1/64 of the index. */ 
118278   if( pLower && pLower->truthProb>0 && pUpper && pUpper->truthProb>0 ){
118279     nNew -= 20;
118280   }
118281
118282   nOut -= (pLower!=0) + (pUpper!=0);
118283   if( nNew<10 ) nNew = 10;
118284   if( nNew<nOut ) nOut = nNew;
118285 #if defined(WHERETRACE_ENABLED)
118286   if( pLoop->nOut>nOut ){
118287     WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
118288                     pLoop->nOut, nOut));
118289   }
118290 #endif
118291   pLoop->nOut = (LogEst)nOut;
118292   return rc;
118293 }
118294
118295 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
118296 /*
118297 ** Estimate the number of rows that will be returned based on
118298 ** an equality constraint x=VALUE and where that VALUE occurs in
118299 ** the histogram data.  This only works when x is the left-most
118300 ** column of an index and sqlite_stat3 histogram data is available
118301 ** for that index.  When pExpr==NULL that means the constraint is
118302 ** "x IS NULL" instead of "x=VALUE".
118303 **
118304 ** Write the estimated row count into *pnRow and return SQLITE_OK. 
118305 ** If unable to make an estimate, leave *pnRow unchanged and return
118306 ** non-zero.
118307 **
118308 ** This routine can fail if it is unable to load a collating sequence
118309 ** required for string comparison, or if unable to allocate memory
118310 ** for a UTF conversion required for comparison.  The error is stored
118311 ** in the pParse structure.
118312 */
118313 static int whereEqualScanEst(
118314   Parse *pParse,       /* Parsing & code generating context */
118315   WhereLoopBuilder *pBuilder,
118316   Expr *pExpr,         /* Expression for VALUE in the x=VALUE constraint */
118317   tRowcnt *pnRow       /* Write the revised row estimate here */
118318 ){
118319   Index *p = pBuilder->pNew->u.btree.pIndex;
118320   int nEq = pBuilder->pNew->u.btree.nEq;
118321   UnpackedRecord *pRec = pBuilder->pRec;
118322   u8 aff;                   /* Column affinity */
118323   int rc;                   /* Subfunction return code */
118324   tRowcnt a[2];             /* Statistics */
118325   int bOk;
118326
118327   assert( nEq>=1 );
118328   assert( nEq<=p->nColumn );
118329   assert( p->aSample!=0 );
118330   assert( p->nSample>0 );
118331   assert( pBuilder->nRecValid<nEq );
118332
118333   /* If values are not available for all fields of the index to the left
118334   ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
118335   if( pBuilder->nRecValid<(nEq-1) ){
118336     return SQLITE_NOTFOUND;
118337   }
118338
118339   /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
118340   ** below would return the same value.  */
118341   if( nEq>=p->nColumn ){
118342     *pnRow = 1;
118343     return SQLITE_OK;
118344   }
118345
118346   aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
118347   rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
118348   pBuilder->pRec = pRec;
118349   if( rc!=SQLITE_OK ) return rc;
118350   if( bOk==0 ) return SQLITE_NOTFOUND;
118351   pBuilder->nRecValid = nEq;
118352
118353   whereKeyStats(pParse, p, pRec, 0, a);
118354   WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
118355   *pnRow = a[1];
118356   
118357   return rc;
118358 }
118359 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
118360
118361 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
118362 /*
118363 ** Estimate the number of rows that will be returned based on
118364 ** an IN constraint where the right-hand side of the IN operator
118365 ** is a list of values.  Example:
118366 **
118367 **        WHERE x IN (1,2,3,4)
118368 **
118369 ** Write the estimated row count into *pnRow and return SQLITE_OK. 
118370 ** If unable to make an estimate, leave *pnRow unchanged and return
118371 ** non-zero.
118372 **
118373 ** This routine can fail if it is unable to load a collating sequence
118374 ** required for string comparison, or if unable to allocate memory
118375 ** for a UTF conversion required for comparison.  The error is stored
118376 ** in the pParse structure.
118377 */
118378 static int whereInScanEst(
118379   Parse *pParse,       /* Parsing & code generating context */
118380   WhereLoopBuilder *pBuilder,
118381   ExprList *pList,     /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
118382   tRowcnt *pnRow       /* Write the revised row estimate here */
118383 ){
118384   Index *p = pBuilder->pNew->u.btree.pIndex;
118385   i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
118386   int nRecValid = pBuilder->nRecValid;
118387   int rc = SQLITE_OK;     /* Subfunction return code */
118388   tRowcnt nEst;           /* Number of rows for a single term */
118389   tRowcnt nRowEst = 0;    /* New estimate of the number of rows */
118390   int i;                  /* Loop counter */
118391
118392   assert( p->aSample!=0 );
118393   for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
118394     nEst = nRow0;
118395     rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
118396     nRowEst += nEst;
118397     pBuilder->nRecValid = nRecValid;
118398   }
118399
118400   if( rc==SQLITE_OK ){
118401     if( nRowEst > nRow0 ) nRowEst = nRow0;
118402     *pnRow = nRowEst;
118403     WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
118404   }
118405   assert( pBuilder->nRecValid==nRecValid );
118406   return rc;
118407 }
118408 #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
118409
118410 /*
118411 ** Disable a term in the WHERE clause.  Except, do not disable the term
118412 ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
118413 ** or USING clause of that join.
118414 **
118415 ** Consider the term t2.z='ok' in the following queries:
118416 **
118417 **   (1)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
118418 **   (2)  SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
118419 **   (3)  SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
118420 **
118421 ** The t2.z='ok' is disabled in the in (2) because it originates
118422 ** in the ON clause.  The term is disabled in (3) because it is not part
118423 ** of a LEFT OUTER JOIN.  In (1), the term is not disabled.
118424 **
118425 ** Disabling a term causes that term to not be tested in the inner loop
118426 ** of the join.  Disabling is an optimization.  When terms are satisfied
118427 ** by indices, we disable them to prevent redundant tests in the inner
118428 ** loop.  We would get the correct results if nothing were ever disabled,
118429 ** but joins might run a little slower.  The trick is to disable as much
118430 ** as we can without disabling too much.  If we disabled in (1), we'd get
118431 ** the wrong answer.  See ticket #813.
118432 **
118433 ** If all the children of a term are disabled, then that term is also
118434 ** automatically disabled.  In this way, terms get disabled if derived
118435 ** virtual terms are tested first.  For example:
118436 **
118437 **      x GLOB 'abc*' AND x>='abc' AND x<'acd'
118438 **      \___________/     \______/     \_____/
118439 **         parent          child1       child2
118440 **
118441 ** Only the parent term was in the original WHERE clause.  The child1
118442 ** and child2 terms were added by the LIKE optimization.  If both of
118443 ** the virtual child terms are valid, then testing of the parent can be 
118444 ** skipped.
118445 **
118446 ** Usually the parent term is marked as TERM_CODED.  But if the parent
118447 ** term was originally TERM_LIKE, then the parent gets TERM_LIKECOND instead.
118448 ** The TERM_LIKECOND marking indicates that the term should be coded inside
118449 ** a conditional such that is only evaluated on the second pass of a
118450 ** LIKE-optimization loop, when scanning BLOBs instead of strings.
118451 */
118452 static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
118453   int nLoop = 0;
118454   while( pTerm
118455       && (pTerm->wtFlags & TERM_CODED)==0
118456       && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
118457       && (pLevel->notReady & pTerm->prereqAll)==0
118458   ){
118459     if( nLoop && (pTerm->wtFlags & TERM_LIKE)!=0 ){
118460       pTerm->wtFlags |= TERM_LIKECOND;
118461     }else{
118462       pTerm->wtFlags |= TERM_CODED;
118463     }
118464     if( pTerm->iParent<0 ) break;
118465     pTerm = &pTerm->pWC->a[pTerm->iParent];
118466     pTerm->nChild--;
118467     if( pTerm->nChild!=0 ) break;
118468     nLoop++;
118469   }
118470 }
118471
118472 /*
118473 ** Code an OP_Affinity opcode to apply the column affinity string zAff
118474 ** to the n registers starting at base. 
118475 **
118476 ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
118477 ** beginning and end of zAff are ignored.  If all entries in zAff are
118478 ** SQLITE_AFF_NONE, then no code gets generated.
118479 **
118480 ** This routine makes its own copy of zAff so that the caller is free
118481 ** to modify zAff after this routine returns.
118482 */
118483 static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
118484   Vdbe *v = pParse->pVdbe;
118485   if( zAff==0 ){
118486     assert( pParse->db->mallocFailed );
118487     return;
118488   }
118489   assert( v!=0 );
118490
118491   /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
118492   ** and end of the affinity string.
118493   */
118494   while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
118495     n--;
118496     base++;
118497     zAff++;
118498   }
118499   while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
118500     n--;
118501   }
118502
118503   /* Code the OP_Affinity opcode if there is anything left to do. */
118504   if( n>0 ){
118505     sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
118506     sqlite3VdbeChangeP4(v, -1, zAff, n);
118507     sqlite3ExprCacheAffinityChange(pParse, base, n);
118508   }
118509 }
118510
118511
118512 /*
118513 ** Generate code for a single equality term of the WHERE clause.  An equality
118514 ** term can be either X=expr or X IN (...).   pTerm is the term to be 
118515 ** coded.
118516 **
118517 ** The current value for the constraint is left in register iReg.
118518 **
118519 ** For a constraint of the form X=expr, the expression is evaluated and its
118520 ** result is left on the stack.  For constraints of the form X IN (...)
118521 ** this routine sets up a loop that will iterate over all values of X.
118522 */
118523 static int codeEqualityTerm(
118524   Parse *pParse,      /* The parsing context */
118525   WhereTerm *pTerm,   /* The term of the WHERE clause to be coded */
118526   WhereLevel *pLevel, /* The level of the FROM clause we are working on */
118527   int iEq,            /* Index of the equality term within this level */
118528   int bRev,           /* True for reverse-order IN operations */
118529   int iTarget         /* Attempt to leave results in this register */
118530 ){
118531   Expr *pX = pTerm->pExpr;
118532   Vdbe *v = pParse->pVdbe;
118533   int iReg;                  /* Register holding results */
118534
118535   assert( iTarget>0 );
118536   if( pX->op==TK_EQ ){
118537     iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
118538   }else if( pX->op==TK_ISNULL ){
118539     iReg = iTarget;
118540     sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
118541 #ifndef SQLITE_OMIT_SUBQUERY
118542   }else{
118543     int eType;
118544     int iTab;
118545     struct InLoop *pIn;
118546     WhereLoop *pLoop = pLevel->pWLoop;
118547
118548     if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
118549       && pLoop->u.btree.pIndex!=0
118550       && pLoop->u.btree.pIndex->aSortOrder[iEq]
118551     ){
118552       testcase( iEq==0 );
118553       testcase( bRev );
118554       bRev = !bRev;
118555     }
118556     assert( pX->op==TK_IN );
118557     iReg = iTarget;
118558     eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
118559     if( eType==IN_INDEX_INDEX_DESC ){
118560       testcase( bRev );
118561       bRev = !bRev;
118562     }
118563     iTab = pX->iTable;
118564     sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
118565     VdbeCoverageIf(v, bRev);
118566     VdbeCoverageIf(v, !bRev);
118567     assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
118568     pLoop->wsFlags |= WHERE_IN_ABLE;
118569     if( pLevel->u.in.nIn==0 ){
118570       pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
118571     }
118572     pLevel->u.in.nIn++;
118573     pLevel->u.in.aInLoop =
118574        sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
118575                               sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
118576     pIn = pLevel->u.in.aInLoop;
118577     if( pIn ){
118578       pIn += pLevel->u.in.nIn - 1;
118579       pIn->iCur = iTab;
118580       if( eType==IN_INDEX_ROWID ){
118581         pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
118582       }else{
118583         pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
118584       }
118585       pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
118586       sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
118587     }else{
118588       pLevel->u.in.nIn = 0;
118589     }
118590 #endif
118591   }
118592   disableTerm(pLevel, pTerm);
118593   return iReg;
118594 }
118595
118596 /*
118597 ** Generate code that will evaluate all == and IN constraints for an
118598 ** index scan.
118599 **
118600 ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
118601 ** Suppose the WHERE clause is this:  a==5 AND b IN (1,2,3) AND c>5 AND c<10
118602 ** The index has as many as three equality constraints, but in this
118603 ** example, the third "c" value is an inequality.  So only two 
118604 ** constraints are coded.  This routine will generate code to evaluate
118605 ** a==5 and b IN (1,2,3).  The current values for a and b will be stored
118606 ** in consecutive registers and the index of the first register is returned.
118607 **
118608 ** In the example above nEq==2.  But this subroutine works for any value
118609 ** of nEq including 0.  If nEq==0, this routine is nearly a no-op.
118610 ** The only thing it does is allocate the pLevel->iMem memory cell and
118611 ** compute the affinity string.
118612 **
118613 ** The nExtraReg parameter is 0 or 1.  It is 0 if all WHERE clause constraints
118614 ** are == or IN and are covered by the nEq.  nExtraReg is 1 if there is
118615 ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
118616 ** occurs after the nEq quality constraints.
118617 **
118618 ** This routine allocates a range of nEq+nExtraReg memory cells and returns
118619 ** the index of the first memory cell in that range. The code that
118620 ** calls this routine will use that memory range to store keys for
118621 ** start and termination conditions of the loop.
118622 ** key value of the loop.  If one or more IN operators appear, then
118623 ** this routine allocates an additional nEq memory cells for internal
118624 ** use.
118625 **
118626 ** Before returning, *pzAff is set to point to a buffer containing a
118627 ** copy of the column affinity string of the index allocated using
118628 ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
118629 ** with equality constraints that use NONE affinity are set to
118630 ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
118631 **
118632 **   CREATE TABLE t1(a TEXT PRIMARY KEY, b);
118633 **   SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
118634 **
118635 ** In the example above, the index on t1(a) has TEXT affinity. But since
118636 ** the right hand side of the equality constraint (t2.b) has NONE affinity,
118637 ** no conversion should be attempted before using a t2.b value as part of
118638 ** a key to search the index. Hence the first byte in the returned affinity
118639 ** string in this example would be set to SQLITE_AFF_NONE.
118640 */
118641 static int codeAllEqualityTerms(
118642   Parse *pParse,        /* Parsing context */
118643   WhereLevel *pLevel,   /* Which nested loop of the FROM we are coding */
118644   int bRev,             /* Reverse the order of IN operators */
118645   int nExtraReg,        /* Number of extra registers to allocate */
118646   char **pzAff          /* OUT: Set to point to affinity string */
118647 ){
118648   u16 nEq;                      /* The number of == or IN constraints to code */
118649   u16 nSkip;                    /* Number of left-most columns to skip */
118650   Vdbe *v = pParse->pVdbe;      /* The vm under construction */
118651   Index *pIdx;                  /* The index being used for this loop */
118652   WhereTerm *pTerm;             /* A single constraint term */
118653   WhereLoop *pLoop;             /* The WhereLoop object */
118654   int j;                        /* Loop counter */
118655   int regBase;                  /* Base register */
118656   int nReg;                     /* Number of registers to allocate */
118657   char *zAff;                   /* Affinity string to return */
118658
118659   /* This module is only called on query plans that use an index. */
118660   pLoop = pLevel->pWLoop;
118661   assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
118662   nEq = pLoop->u.btree.nEq;
118663   nSkip = pLoop->nSkip;
118664   pIdx = pLoop->u.btree.pIndex;
118665   assert( pIdx!=0 );
118666
118667   /* Figure out how many memory cells we will need then allocate them.
118668   */
118669   regBase = pParse->nMem + 1;
118670   nReg = pLoop->u.btree.nEq + nExtraReg;
118671   pParse->nMem += nReg;
118672
118673   zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
118674   if( !zAff ){
118675     pParse->db->mallocFailed = 1;
118676   }
118677
118678   if( nSkip ){
118679     int iIdxCur = pLevel->iIdxCur;
118680     sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
118681     VdbeCoverageIf(v, bRev==0);
118682     VdbeCoverageIf(v, bRev!=0);
118683     VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
118684     j = sqlite3VdbeAddOp0(v, OP_Goto);
118685     pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
118686                             iIdxCur, 0, regBase, nSkip);
118687     VdbeCoverageIf(v, bRev==0);
118688     VdbeCoverageIf(v, bRev!=0);
118689     sqlite3VdbeJumpHere(v, j);
118690     for(j=0; j<nSkip; j++){
118691       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
118692       assert( pIdx->aiColumn[j]>=0 );
118693       VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
118694     }
118695   }    
118696
118697   /* Evaluate the equality constraints
118698   */
118699   assert( zAff==0 || (int)strlen(zAff)>=nEq );
118700   for(j=nSkip; j<nEq; j++){
118701     int r1;
118702     pTerm = pLoop->aLTerm[j];
118703     assert( pTerm!=0 );
118704     /* The following testcase is true for indices with redundant columns. 
118705     ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
118706     testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
118707     testcase( pTerm->wtFlags & TERM_VIRTUAL );
118708     r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
118709     if( r1!=regBase+j ){
118710       if( nReg==1 ){
118711         sqlite3ReleaseTempReg(pParse, regBase);
118712         regBase = r1;
118713       }else{
118714         sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
118715       }
118716     }
118717     testcase( pTerm->eOperator & WO_ISNULL );
118718     testcase( pTerm->eOperator & WO_IN );
118719     if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
118720       Expr *pRight = pTerm->pExpr->pRight;
118721       if( sqlite3ExprCanBeNull(pRight) ){
118722         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
118723         VdbeCoverage(v);
118724       }
118725       if( zAff ){
118726         if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
118727           zAff[j] = SQLITE_AFF_NONE;
118728         }
118729         if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
118730           zAff[j] = SQLITE_AFF_NONE;
118731         }
118732       }
118733     }
118734   }
118735   *pzAff = zAff;
118736   return regBase;
118737 }
118738
118739 #ifndef SQLITE_OMIT_EXPLAIN
118740 /*
118741 ** This routine is a helper for explainIndexRange() below
118742 **
118743 ** pStr holds the text of an expression that we are building up one term
118744 ** at a time.  This routine adds a new term to the end of the expression.
118745 ** Terms are separated by AND so add the "AND" text for second and subsequent
118746 ** terms only.
118747 */
118748 static void explainAppendTerm(
118749   StrAccum *pStr,             /* The text expression being built */
118750   int iTerm,                  /* Index of this term.  First is zero */
118751   const char *zColumn,        /* Name of the column */
118752   const char *zOp             /* Name of the operator */
118753 ){
118754   if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
118755   sqlite3StrAccumAppendAll(pStr, zColumn);
118756   sqlite3StrAccumAppend(pStr, zOp, 1);
118757   sqlite3StrAccumAppend(pStr, "?", 1);
118758 }
118759
118760 /*
118761 ** Argument pLevel describes a strategy for scanning table pTab. This 
118762 ** function appends text to pStr that describes the subset of table
118763 ** rows scanned by the strategy in the form of an SQL expression.
118764 **
118765 ** For example, if the query:
118766 **
118767 **   SELECT * FROM t1 WHERE a=1 AND b>2;
118768 **
118769 ** is run and there is an index on (a, b), then this function returns a
118770 ** string similar to:
118771 **
118772 **   "a=? AND b>?"
118773 */
118774 static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop, Table *pTab){
118775   Index *pIndex = pLoop->u.btree.pIndex;
118776   u16 nEq = pLoop->u.btree.nEq;
118777   u16 nSkip = pLoop->nSkip;
118778   int i, j;
118779   Column *aCol = pTab->aCol;
118780   i16 *aiColumn = pIndex->aiColumn;
118781
118782   if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
118783   sqlite3StrAccumAppend(pStr, " (", 2);
118784   for(i=0; i<nEq; i++){
118785     char *z = aiColumn[i] < 0 ? "rowid" : aCol[aiColumn[i]].zName;
118786     if( i>=nSkip ){
118787       explainAppendTerm(pStr, i, z, "=");
118788     }else{
118789       if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
118790       sqlite3XPrintf(pStr, 0, "ANY(%s)", z);
118791     }
118792   }
118793
118794   j = i;
118795   if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
118796     char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
118797     explainAppendTerm(pStr, i++, z, ">");
118798   }
118799   if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
118800     char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
118801     explainAppendTerm(pStr, i, z, "<");
118802   }
118803   sqlite3StrAccumAppend(pStr, ")", 1);
118804 }
118805
118806 /*
118807 ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
118808 ** command, or if either SQLITE_DEBUG or SQLITE_ENABLE_STMT_SCANSTATUS was
118809 ** defined at compile-time. If it is not a no-op, a single OP_Explain opcode 
118810 ** is added to the output to describe the table scan strategy in pLevel.
118811 **
118812 ** If an OP_Explain opcode is added to the VM, its address is returned.
118813 ** Otherwise, if no OP_Explain is coded, zero is returned.
118814 */
118815 static int explainOneScan(
118816   Parse *pParse,                  /* Parse context */
118817   SrcList *pTabList,              /* Table list this loop refers to */
118818   WhereLevel *pLevel,             /* Scan to write OP_Explain opcode for */
118819   int iLevel,                     /* Value for "level" column of output */
118820   int iFrom,                      /* Value for "from" column of output */
118821   u16 wctrlFlags                  /* Flags passed to sqlite3WhereBegin() */
118822 ){
118823   int ret = 0;
118824 #if !defined(SQLITE_DEBUG) && !defined(SQLITE_ENABLE_STMT_SCANSTATUS)
118825   if( pParse->explain==2 )
118826 #endif
118827   {
118828     struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
118829     Vdbe *v = pParse->pVdbe;      /* VM being constructed */
118830     sqlite3 *db = pParse->db;     /* Database handle */
118831     int iId = pParse->iSelectId;  /* Select id (left-most output column) */
118832     int isSearch;                 /* True for a SEARCH. False for SCAN. */
118833     WhereLoop *pLoop;             /* The controlling WhereLoop object */
118834     u32 flags;                    /* Flags that describe this loop */
118835     char *zMsg;                   /* Text to add to EQP output */
118836     StrAccum str;                 /* EQP output string */
118837     char zBuf[100];               /* Initial space for EQP output string */
118838
118839     pLoop = pLevel->pWLoop;
118840     flags = pLoop->wsFlags;
118841     if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return 0;
118842
118843     isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
118844             || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
118845             || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
118846
118847     sqlite3StrAccumInit(&str, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
118848     str.db = db;
118849     sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
118850     if( pItem->pSelect ){
118851       sqlite3XPrintf(&str, 0, " SUBQUERY %d", pItem->iSelectId);
118852     }else{
118853       sqlite3XPrintf(&str, 0, " TABLE %s", pItem->zName);
118854     }
118855
118856     if( pItem->zAlias ){
118857       sqlite3XPrintf(&str, 0, " AS %s", pItem->zAlias);
118858     }
118859     if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
118860       const char *zFmt = 0;
118861       Index *pIdx;
118862
118863       assert( pLoop->u.btree.pIndex!=0 );
118864       pIdx = pLoop->u.btree.pIndex;
118865       assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
118866       if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
118867         if( isSearch ){
118868           zFmt = "PRIMARY KEY";
118869         }
118870       }else if( flags & WHERE_PARTIALIDX ){
118871         zFmt = "AUTOMATIC PARTIAL COVERING INDEX";
118872       }else if( flags & WHERE_AUTO_INDEX ){
118873         zFmt = "AUTOMATIC COVERING INDEX";
118874       }else if( flags & WHERE_IDX_ONLY ){
118875         zFmt = "COVERING INDEX %s";
118876       }else{
118877         zFmt = "INDEX %s";
118878       }
118879       if( zFmt ){
118880         sqlite3StrAccumAppend(&str, " USING ", 7);
118881         sqlite3XPrintf(&str, 0, zFmt, pIdx->zName);
118882         explainIndexRange(&str, pLoop, pItem->pTab);
118883       }
118884     }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
118885       const char *zRange;
118886       if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
118887         zRange = "(rowid=?)";
118888       }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
118889         zRange = "(rowid>? AND rowid<?)";
118890       }else if( flags&WHERE_BTM_LIMIT ){
118891         zRange = "(rowid>?)";
118892       }else{
118893         assert( flags&WHERE_TOP_LIMIT);
118894         zRange = "(rowid<?)";
118895       }
118896       sqlite3StrAccumAppendAll(&str, " USING INTEGER PRIMARY KEY ");
118897       sqlite3StrAccumAppendAll(&str, zRange);
118898     }
118899 #ifndef SQLITE_OMIT_VIRTUALTABLE
118900     else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
118901       sqlite3XPrintf(&str, 0, " VIRTUAL TABLE INDEX %d:%s",
118902                   pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
118903     }
118904 #endif
118905 #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
118906     if( pLoop->nOut>=10 ){
118907       sqlite3XPrintf(&str, 0, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
118908     }else{
118909       sqlite3StrAccumAppend(&str, " (~1 row)", 9);
118910     }
118911 #endif
118912     zMsg = sqlite3StrAccumFinish(&str);
118913     ret = sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg,P4_DYNAMIC);
118914   }
118915   return ret;
118916 }
118917 #else
118918 # define explainOneScan(u,v,w,x,y,z) 0
118919 #endif /* SQLITE_OMIT_EXPLAIN */
118920
118921 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
118922 /*
118923 ** Configure the VM passed as the first argument with an
118924 ** sqlite3_stmt_scanstatus() entry corresponding to the scan used to 
118925 ** implement level pLvl. Argument pSrclist is a pointer to the FROM 
118926 ** clause that the scan reads data from.
118927 **
118928 ** If argument addrExplain is not 0, it must be the address of an 
118929 ** OP_Explain instruction that describes the same loop.
118930 */
118931 static void addScanStatus(
118932   Vdbe *v,                        /* Vdbe to add scanstatus entry to */
118933   SrcList *pSrclist,              /* FROM clause pLvl reads data from */
118934   WhereLevel *pLvl,               /* Level to add scanstatus() entry for */
118935   int addrExplain                 /* Address of OP_Explain (or 0) */
118936 ){
118937   const char *zObj = 0;
118938   WhereLoop *pLoop = pLvl->pWLoop;
118939   if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0  &&  pLoop->u.btree.pIndex!=0 ){
118940     zObj = pLoop->u.btree.pIndex->zName;
118941   }else{
118942     zObj = pSrclist->a[pLvl->iFrom].zName;
118943   }
118944   sqlite3VdbeScanStatus(
118945       v, addrExplain, pLvl->addrBody, pLvl->addrVisit, pLoop->nOut, zObj
118946   );
118947 }
118948 #else
118949 # define addScanStatus(a, b, c, d) ((void)d)
118950 #endif
118951
118952 /*
118953 ** If the most recently coded instruction is a constant range contraint
118954 ** that originated from the LIKE optimization, then change the P3 to be
118955 ** pLoop->iLikeRepCntr and set P5.
118956 **
118957 ** The LIKE optimization trys to evaluate "x LIKE 'abc%'" as a range
118958 ** expression: "x>='ABC' AND x<'abd'".  But this requires that the range
118959 ** scan loop run twice, once for strings and a second time for BLOBs.
118960 ** The OP_String opcodes on the second pass convert the upper and lower
118961 ** bound string contants to blobs.  This routine makes the necessary changes
118962 ** to the OP_String opcodes for that to happen.
118963 */
118964 static void whereLikeOptimizationStringFixup(
118965   Vdbe *v,                /* prepared statement under construction */
118966   WhereLevel *pLevel,     /* The loop that contains the LIKE operator */
118967   WhereTerm *pTerm        /* The upper or lower bound just coded */
118968 ){
118969   if( pTerm->wtFlags & TERM_LIKEOPT ){
118970     VdbeOp *pOp;
118971     assert( pLevel->iLikeRepCntr>0 );
118972     pOp = sqlite3VdbeGetOp(v, -1);
118973     assert( pOp!=0 );
118974     assert( pOp->opcode==OP_String8 
118975             || pTerm->pWC->pWInfo->pParse->db->mallocFailed );
118976     pOp->p3 = pLevel->iLikeRepCntr;
118977     pOp->p5 = 1;
118978   }
118979 }
118980
118981 /*
118982 ** Generate code for the start of the iLevel-th loop in the WHERE clause
118983 ** implementation described by pWInfo.
118984 */
118985 static Bitmask codeOneLoopStart(
118986   WhereInfo *pWInfo,   /* Complete information about the WHERE clause */
118987   int iLevel,          /* Which level of pWInfo->a[] should be coded */
118988   Bitmask notReady     /* Which tables are currently available */
118989 ){
118990   int j, k;            /* Loop counters */
118991   int iCur;            /* The VDBE cursor for the table */
118992   int addrNxt;         /* Where to jump to continue with the next IN case */
118993   int omitTable;       /* True if we use the index only */
118994   int bRev;            /* True if we need to scan in reverse order */
118995   WhereLevel *pLevel;  /* The where level to be coded */
118996   WhereLoop *pLoop;    /* The WhereLoop object being coded */
118997   WhereClause *pWC;    /* Decomposition of the entire WHERE clause */
118998   WhereTerm *pTerm;               /* A WHERE clause term */
118999   Parse *pParse;                  /* Parsing context */
119000   sqlite3 *db;                    /* Database connection */
119001   Vdbe *v;                        /* The prepared stmt under constructions */
119002   struct SrcList_item *pTabItem;  /* FROM clause term being coded */
119003   int addrBrk;                    /* Jump here to break out of the loop */
119004   int addrCont;                   /* Jump here to continue with next cycle */
119005   int iRowidReg = 0;        /* Rowid is stored in this register, if not zero */
119006   int iReleaseReg = 0;      /* Temp register to free before returning */
119007
119008   pParse = pWInfo->pParse;
119009   v = pParse->pVdbe;
119010   pWC = &pWInfo->sWC;
119011   db = pParse->db;
119012   pLevel = &pWInfo->a[iLevel];
119013   pLoop = pLevel->pWLoop;
119014   pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
119015   iCur = pTabItem->iCursor;
119016   pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
119017   bRev = (pWInfo->revMask>>iLevel)&1;
119018   omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0 
119019            && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
119020   VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
119021
119022   /* Create labels for the "break" and "continue" instructions
119023   ** for the current loop.  Jump to addrBrk to break out of a loop.
119024   ** Jump to cont to go immediately to the next iteration of the
119025   ** loop.
119026   **
119027   ** When there is an IN operator, we also have a "addrNxt" label that
119028   ** means to continue with the next IN value combination.  When
119029   ** there are no IN operators in the constraints, the "addrNxt" label
119030   ** is the same as "addrBrk".
119031   */
119032   addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
119033   addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
119034
119035   /* If this is the right table of a LEFT OUTER JOIN, allocate and
119036   ** initialize a memory cell that records if this table matches any
119037   ** row of the left table of the join.
119038   */
119039   if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
119040     pLevel->iLeftJoin = ++pParse->nMem;
119041     sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
119042     VdbeComment((v, "init LEFT JOIN no-match flag"));
119043   }
119044
119045   /* Special case of a FROM clause subquery implemented as a co-routine */
119046   if( pTabItem->viaCoroutine ){
119047     int regYield = pTabItem->regReturn;
119048     sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
119049     pLevel->p2 =  sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
119050     VdbeCoverage(v);
119051     VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
119052     pLevel->op = OP_Goto;
119053   }else
119054
119055 #ifndef SQLITE_OMIT_VIRTUALTABLE
119056   if(  (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
119057     /* Case 1:  The table is a virtual-table.  Use the VFilter and VNext
119058     **          to access the data.
119059     */
119060     int iReg;   /* P3 Value for OP_VFilter */
119061     int addrNotFound;
119062     int nConstraint = pLoop->nLTerm;
119063
119064     sqlite3ExprCachePush(pParse);
119065     iReg = sqlite3GetTempRange(pParse, nConstraint+2);
119066     addrNotFound = pLevel->addrBrk;
119067     for(j=0; j<nConstraint; j++){
119068       int iTarget = iReg+j+2;
119069       pTerm = pLoop->aLTerm[j];
119070       if( pTerm==0 ) continue;
119071       if( pTerm->eOperator & WO_IN ){
119072         codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
119073         addrNotFound = pLevel->addrNxt;
119074       }else{
119075         sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
119076       }
119077     }
119078     sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
119079     sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
119080     sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
119081                       pLoop->u.vtab.idxStr,
119082                       pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
119083     VdbeCoverage(v);
119084     pLoop->u.vtab.needFree = 0;
119085     for(j=0; j<nConstraint && j<16; j++){
119086       if( (pLoop->u.vtab.omitMask>>j)&1 ){
119087         disableTerm(pLevel, pLoop->aLTerm[j]);
119088       }
119089     }
119090     pLevel->op = OP_VNext;
119091     pLevel->p1 = iCur;
119092     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
119093     sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
119094     sqlite3ExprCachePop(pParse);
119095   }else
119096 #endif /* SQLITE_OMIT_VIRTUALTABLE */
119097
119098   if( (pLoop->wsFlags & WHERE_IPK)!=0
119099    && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
119100   ){
119101     /* Case 2:  We can directly reference a single row using an
119102     **          equality comparison against the ROWID field.  Or
119103     **          we reference multiple rows using a "rowid IN (...)"
119104     **          construct.
119105     */
119106     assert( pLoop->u.btree.nEq==1 );
119107     pTerm = pLoop->aLTerm[0];
119108     assert( pTerm!=0 );
119109     assert( pTerm->pExpr!=0 );
119110     assert( omitTable==0 );
119111     testcase( pTerm->wtFlags & TERM_VIRTUAL );
119112     iReleaseReg = ++pParse->nMem;
119113     iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
119114     if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
119115     addrNxt = pLevel->addrNxt;
119116     sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
119117     sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
119118     VdbeCoverage(v);
119119     sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
119120     sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
119121     VdbeComment((v, "pk"));
119122     pLevel->op = OP_Noop;
119123   }else if( (pLoop->wsFlags & WHERE_IPK)!=0
119124          && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
119125   ){
119126     /* Case 3:  We have an inequality comparison against the ROWID field.
119127     */
119128     int testOp = OP_Noop;
119129     int start;
119130     int memEndValue = 0;
119131     WhereTerm *pStart, *pEnd;
119132
119133     assert( omitTable==0 );
119134     j = 0;
119135     pStart = pEnd = 0;
119136     if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
119137     if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
119138     assert( pStart!=0 || pEnd!=0 );
119139     if( bRev ){
119140       pTerm = pStart;
119141       pStart = pEnd;
119142       pEnd = pTerm;
119143     }
119144     if( pStart ){
119145       Expr *pX;             /* The expression that defines the start bound */
119146       int r1, rTemp;        /* Registers for holding the start boundary */
119147
119148       /* The following constant maps TK_xx codes into corresponding 
119149       ** seek opcodes.  It depends on a particular ordering of TK_xx
119150       */
119151       const u8 aMoveOp[] = {
119152            /* TK_GT */  OP_SeekGT,
119153            /* TK_LE */  OP_SeekLE,
119154            /* TK_LT */  OP_SeekLT,
119155            /* TK_GE */  OP_SeekGE
119156       };
119157       assert( TK_LE==TK_GT+1 );      /* Make sure the ordering.. */
119158       assert( TK_LT==TK_GT+2 );      /*  ... of the TK_xx values... */
119159       assert( TK_GE==TK_GT+3 );      /*  ... is correcct. */
119160
119161       assert( (pStart->wtFlags & TERM_VNULL)==0 );
119162       testcase( pStart->wtFlags & TERM_VIRTUAL );
119163       pX = pStart->pExpr;
119164       assert( pX!=0 );
119165       testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
119166       r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
119167       sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
119168       VdbeComment((v, "pk"));
119169       VdbeCoverageIf(v, pX->op==TK_GT);
119170       VdbeCoverageIf(v, pX->op==TK_LE);
119171       VdbeCoverageIf(v, pX->op==TK_LT);
119172       VdbeCoverageIf(v, pX->op==TK_GE);
119173       sqlite3ExprCacheAffinityChange(pParse, r1, 1);
119174       sqlite3ReleaseTempReg(pParse, rTemp);
119175       disableTerm(pLevel, pStart);
119176     }else{
119177       sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
119178       VdbeCoverageIf(v, bRev==0);
119179       VdbeCoverageIf(v, bRev!=0);
119180     }
119181     if( pEnd ){
119182       Expr *pX;
119183       pX = pEnd->pExpr;
119184       assert( pX!=0 );
119185       assert( (pEnd->wtFlags & TERM_VNULL)==0 );
119186       testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
119187       testcase( pEnd->wtFlags & TERM_VIRTUAL );
119188       memEndValue = ++pParse->nMem;
119189       sqlite3ExprCode(pParse, pX->pRight, memEndValue);
119190       if( pX->op==TK_LT || pX->op==TK_GT ){
119191         testOp = bRev ? OP_Le : OP_Ge;
119192       }else{
119193         testOp = bRev ? OP_Lt : OP_Gt;
119194       }
119195       disableTerm(pLevel, pEnd);
119196     }
119197     start = sqlite3VdbeCurrentAddr(v);
119198     pLevel->op = bRev ? OP_Prev : OP_Next;
119199     pLevel->p1 = iCur;
119200     pLevel->p2 = start;
119201     assert( pLevel->p5==0 );
119202     if( testOp!=OP_Noop ){
119203       iRowidReg = ++pParse->nMem;
119204       sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
119205       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
119206       sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
119207       VdbeCoverageIf(v, testOp==OP_Le);
119208       VdbeCoverageIf(v, testOp==OP_Lt);
119209       VdbeCoverageIf(v, testOp==OP_Ge);
119210       VdbeCoverageIf(v, testOp==OP_Gt);
119211       sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
119212     }
119213   }else if( pLoop->wsFlags & WHERE_INDEXED ){
119214     /* Case 4: A scan using an index.
119215     **
119216     **         The WHERE clause may contain zero or more equality 
119217     **         terms ("==" or "IN" operators) that refer to the N
119218     **         left-most columns of the index. It may also contain
119219     **         inequality constraints (>, <, >= or <=) on the indexed
119220     **         column that immediately follows the N equalities. Only 
119221     **         the right-most column can be an inequality - the rest must
119222     **         use the "==" and "IN" operators. For example, if the 
119223     **         index is on (x,y,z), then the following clauses are all 
119224     **         optimized:
119225     **
119226     **            x=5
119227     **            x=5 AND y=10
119228     **            x=5 AND y<10
119229     **            x=5 AND y>5 AND y<10
119230     **            x=5 AND y=5 AND z<=10
119231     **
119232     **         The z<10 term of the following cannot be used, only
119233     **         the x=5 term:
119234     **
119235     **            x=5 AND z<10
119236     **
119237     **         N may be zero if there are inequality constraints.
119238     **         If there are no inequality constraints, then N is at
119239     **         least one.
119240     **
119241     **         This case is also used when there are no WHERE clause
119242     **         constraints but an index is selected anyway, in order
119243     **         to force the output order to conform to an ORDER BY.
119244     */  
119245     static const u8 aStartOp[] = {
119246       0,
119247       0,
119248       OP_Rewind,           /* 2: (!start_constraints && startEq &&  !bRev) */
119249       OP_Last,             /* 3: (!start_constraints && startEq &&   bRev) */
119250       OP_SeekGT,           /* 4: (start_constraints  && !startEq && !bRev) */
119251       OP_SeekLT,           /* 5: (start_constraints  && !startEq &&  bRev) */
119252       OP_SeekGE,           /* 6: (start_constraints  &&  startEq && !bRev) */
119253       OP_SeekLE            /* 7: (start_constraints  &&  startEq &&  bRev) */
119254     };
119255     static const u8 aEndOp[] = {
119256       OP_IdxGE,            /* 0: (end_constraints && !bRev && !endEq) */
119257       OP_IdxGT,            /* 1: (end_constraints && !bRev &&  endEq) */
119258       OP_IdxLE,            /* 2: (end_constraints &&  bRev && !endEq) */
119259       OP_IdxLT,            /* 3: (end_constraints &&  bRev &&  endEq) */
119260     };
119261     u16 nEq = pLoop->u.btree.nEq;     /* Number of == or IN terms */
119262     int regBase;                 /* Base register holding constraint values */
119263     WhereTerm *pRangeStart = 0;  /* Inequality constraint at range start */
119264     WhereTerm *pRangeEnd = 0;    /* Inequality constraint at range end */
119265     int startEq;                 /* True if range start uses ==, >= or <= */
119266     int endEq;                   /* True if range end uses ==, >= or <= */
119267     int start_constraints;       /* Start of range is constrained */
119268     int nConstraint;             /* Number of constraint terms */
119269     Index *pIdx;                 /* The index we will be using */
119270     int iIdxCur;                 /* The VDBE cursor for the index */
119271     int nExtraReg = 0;           /* Number of extra registers needed */
119272     int op;                      /* Instruction opcode */
119273     char *zStartAff;             /* Affinity for start of range constraint */
119274     char cEndAff = 0;            /* Affinity for end of range constraint */
119275     u8 bSeekPastNull = 0;        /* True to seek past initial nulls */
119276     u8 bStopAtNull = 0;          /* Add condition to terminate at NULLs */
119277
119278     pIdx = pLoop->u.btree.pIndex;
119279     iIdxCur = pLevel->iIdxCur;
119280     assert( nEq>=pLoop->nSkip );
119281
119282     /* If this loop satisfies a sort order (pOrderBy) request that 
119283     ** was passed to this function to implement a "SELECT min(x) ..." 
119284     ** query, then the caller will only allow the loop to run for
119285     ** a single iteration. This means that the first row returned
119286     ** should not have a NULL value stored in 'x'. If column 'x' is
119287     ** the first one after the nEq equality constraints in the index,
119288     ** this requires some special handling.
119289     */
119290     assert( pWInfo->pOrderBy==0
119291          || pWInfo->pOrderBy->nExpr==1
119292          || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
119293     if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
119294      && pWInfo->nOBSat>0
119295      && (pIdx->nKeyCol>nEq)
119296     ){
119297       assert( pLoop->nSkip==0 );
119298       bSeekPastNull = 1;
119299       nExtraReg = 1;
119300     }
119301
119302     /* Find any inequality constraint terms for the start and end 
119303     ** of the range. 
119304     */
119305     j = nEq;
119306     if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
119307       pRangeStart = pLoop->aLTerm[j++];
119308       nExtraReg = 1;
119309       /* Like optimization range constraints always occur in pairs */
119310       assert( (pRangeStart->wtFlags & TERM_LIKEOPT)==0 || 
119311               (pLoop->wsFlags & WHERE_TOP_LIMIT)!=0 );
119312     }
119313     if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
119314       pRangeEnd = pLoop->aLTerm[j++];
119315       nExtraReg = 1;
119316       if( (pRangeEnd->wtFlags & TERM_LIKEOPT)!=0 ){
119317         assert( pRangeStart!=0 );                     /* LIKE opt constraints */
119318         assert( pRangeStart->wtFlags & TERM_LIKEOPT );   /* occur in pairs */
119319         pLevel->iLikeRepCntr = ++pParse->nMem;
119320         testcase( bRev );
119321         testcase( pIdx->aSortOrder[nEq]==SQLITE_SO_DESC );
119322         sqlite3VdbeAddOp2(v, OP_Integer,
119323                           bRev ^ (pIdx->aSortOrder[nEq]==SQLITE_SO_DESC),
119324                           pLevel->iLikeRepCntr);
119325         VdbeComment((v, "LIKE loop counter"));
119326         pLevel->addrLikeRep = sqlite3VdbeCurrentAddr(v);
119327       }
119328       if( pRangeStart==0
119329        && (j = pIdx->aiColumn[nEq])>=0 
119330        && pIdx->pTable->aCol[j].notNull==0
119331       ){
119332         bSeekPastNull = 1;
119333       }
119334     }
119335     assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
119336
119337     /* Generate code to evaluate all constraint terms using == or IN
119338     ** and store the values of those terms in an array of registers
119339     ** starting at regBase.
119340     */
119341     regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
119342     assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
119343     if( zStartAff ) cEndAff = zStartAff[nEq];
119344     addrNxt = pLevel->addrNxt;
119345
119346     /* If we are doing a reverse order scan on an ascending index, or
119347     ** a forward order scan on a descending index, interchange the 
119348     ** start and end terms (pRangeStart and pRangeEnd).
119349     */
119350     if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
119351      || (bRev && pIdx->nKeyCol==nEq)
119352     ){
119353       SWAP(WhereTerm *, pRangeEnd, pRangeStart);
119354       SWAP(u8, bSeekPastNull, bStopAtNull);
119355     }
119356
119357     testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
119358     testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
119359     testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
119360     testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
119361     startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
119362     endEq =   !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
119363     start_constraints = pRangeStart || nEq>0;
119364
119365     /* Seek the index cursor to the start of the range. */
119366     nConstraint = nEq;
119367     if( pRangeStart ){
119368       Expr *pRight = pRangeStart->pExpr->pRight;
119369       sqlite3ExprCode(pParse, pRight, regBase+nEq);
119370       whereLikeOptimizationStringFixup(v, pLevel, pRangeStart);
119371       if( (pRangeStart->wtFlags & TERM_VNULL)==0
119372        && sqlite3ExprCanBeNull(pRight)
119373       ){
119374         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
119375         VdbeCoverage(v);
119376       }
119377       if( zStartAff ){
119378         if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
119379           /* Since the comparison is to be performed with no conversions
119380           ** applied to the operands, set the affinity to apply to pRight to 
119381           ** SQLITE_AFF_NONE.  */
119382           zStartAff[nEq] = SQLITE_AFF_NONE;
119383         }
119384         if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
119385           zStartAff[nEq] = SQLITE_AFF_NONE;
119386         }
119387       }  
119388       nConstraint++;
119389       testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
119390     }else if( bSeekPastNull ){
119391       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
119392       nConstraint++;
119393       startEq = 0;
119394       start_constraints = 1;
119395     }
119396     codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
119397     op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
119398     assert( op!=0 );
119399     sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
119400     VdbeCoverage(v);
119401     VdbeCoverageIf(v, op==OP_Rewind);  testcase( op==OP_Rewind );
119402     VdbeCoverageIf(v, op==OP_Last);    testcase( op==OP_Last );
119403     VdbeCoverageIf(v, op==OP_SeekGT);  testcase( op==OP_SeekGT );
119404     VdbeCoverageIf(v, op==OP_SeekGE);  testcase( op==OP_SeekGE );
119405     VdbeCoverageIf(v, op==OP_SeekLE);  testcase( op==OP_SeekLE );
119406     VdbeCoverageIf(v, op==OP_SeekLT);  testcase( op==OP_SeekLT );
119407
119408     /* Load the value for the inequality constraint at the end of the
119409     ** range (if any).
119410     */
119411     nConstraint = nEq;
119412     if( pRangeEnd ){
119413       Expr *pRight = pRangeEnd->pExpr->pRight;
119414       sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
119415       sqlite3ExprCode(pParse, pRight, regBase+nEq);
119416       whereLikeOptimizationStringFixup(v, pLevel, pRangeEnd);
119417       if( (pRangeEnd->wtFlags & TERM_VNULL)==0
119418        && sqlite3ExprCanBeNull(pRight)
119419       ){
119420         sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
119421         VdbeCoverage(v);
119422       }
119423       if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE
119424        && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
119425       ){
119426         codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
119427       }
119428       nConstraint++;
119429       testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
119430     }else if( bStopAtNull ){
119431       sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
119432       endEq = 0;
119433       nConstraint++;
119434     }
119435     sqlite3DbFree(db, zStartAff);
119436
119437     /* Top of the loop body */
119438     pLevel->p2 = sqlite3VdbeCurrentAddr(v);
119439
119440     /* Check if the index cursor is past the end of the range. */
119441     if( nConstraint ){
119442       op = aEndOp[bRev*2 + endEq];
119443       sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
119444       testcase( op==OP_IdxGT );  VdbeCoverageIf(v, op==OP_IdxGT );
119445       testcase( op==OP_IdxGE );  VdbeCoverageIf(v, op==OP_IdxGE );
119446       testcase( op==OP_IdxLT );  VdbeCoverageIf(v, op==OP_IdxLT );
119447       testcase( op==OP_IdxLE );  VdbeCoverageIf(v, op==OP_IdxLE );
119448     }
119449
119450     /* Seek the table cursor, if required */
119451     disableTerm(pLevel, pRangeStart);
119452     disableTerm(pLevel, pRangeEnd);
119453     if( omitTable ){
119454       /* pIdx is a covering index.  No need to access the main table. */
119455     }else if( HasRowid(pIdx->pTable) ){
119456       iRowidReg = ++pParse->nMem;
119457       sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
119458       sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
119459       sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg);  /* Deferred seek */
119460     }else if( iCur!=iIdxCur ){
119461       Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
119462       iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
119463       for(j=0; j<pPk->nKeyCol; j++){
119464         k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
119465         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
119466       }
119467       sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
119468                            iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
119469     }
119470
119471     /* Record the instruction used to terminate the loop. Disable 
119472     ** WHERE clause terms made redundant by the index range scan.
119473     */
119474     if( pLoop->wsFlags & WHERE_ONEROW ){
119475       pLevel->op = OP_Noop;
119476     }else if( bRev ){
119477       pLevel->op = OP_Prev;
119478     }else{
119479       pLevel->op = OP_Next;
119480     }
119481     pLevel->p1 = iIdxCur;
119482     pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
119483     if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
119484       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
119485     }else{
119486       assert( pLevel->p5==0 );
119487     }
119488   }else
119489
119490 #ifndef SQLITE_OMIT_OR_OPTIMIZATION
119491   if( pLoop->wsFlags & WHERE_MULTI_OR ){
119492     /* Case 5:  Two or more separately indexed terms connected by OR
119493     **
119494     ** Example:
119495     **
119496     **   CREATE TABLE t1(a,b,c,d);
119497     **   CREATE INDEX i1 ON t1(a);
119498     **   CREATE INDEX i2 ON t1(b);
119499     **   CREATE INDEX i3 ON t1(c);
119500     **
119501     **   SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
119502     **
119503     ** In the example, there are three indexed terms connected by OR.
119504     ** The top of the loop looks like this:
119505     **
119506     **          Null       1                # Zero the rowset in reg 1
119507     **
119508     ** Then, for each indexed term, the following. The arguments to
119509     ** RowSetTest are such that the rowid of the current row is inserted
119510     ** into the RowSet. If it is already present, control skips the
119511     ** Gosub opcode and jumps straight to the code generated by WhereEnd().
119512     **
119513     **        sqlite3WhereBegin(<term>)
119514     **          RowSetTest                  # Insert rowid into rowset
119515     **          Gosub      2 A
119516     **        sqlite3WhereEnd()
119517     **
119518     ** Following the above, code to terminate the loop. Label A, the target
119519     ** of the Gosub above, jumps to the instruction right after the Goto.
119520     **
119521     **          Null       1                # Zero the rowset in reg 1
119522     **          Goto       B                # The loop is finished.
119523     **
119524     **       A: <loop body>                 # Return data, whatever.
119525     **
119526     **          Return     2                # Jump back to the Gosub
119527     **
119528     **       B: <after the loop>
119529     **
119530     ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
119531     ** use an ephemeral index instead of a RowSet to record the primary
119532     ** keys of the rows we have already seen.
119533     **
119534     */
119535     WhereClause *pOrWc;    /* The OR-clause broken out into subterms */
119536     SrcList *pOrTab;       /* Shortened table list or OR-clause generation */
119537     Index *pCov = 0;             /* Potential covering index (or NULL) */
119538     int iCovCur = pParse->nTab++;  /* Cursor used for index scans (if any) */
119539
119540     int regReturn = ++pParse->nMem;           /* Register used with OP_Gosub */
119541     int regRowset = 0;                        /* Register for RowSet object */
119542     int regRowid = 0;                         /* Register holding rowid */
119543     int iLoopBody = sqlite3VdbeMakeLabel(v);  /* Start of loop body */
119544     int iRetInit;                             /* Address of regReturn init */
119545     int untestedTerms = 0;             /* Some terms not completely tested */
119546     int ii;                            /* Loop counter */
119547     u16 wctrlFlags;                    /* Flags for sub-WHERE clause */
119548     Expr *pAndExpr = 0;                /* An ".. AND (...)" expression */
119549     Table *pTab = pTabItem->pTab;
119550    
119551     pTerm = pLoop->aLTerm[0];
119552     assert( pTerm!=0 );
119553     assert( pTerm->eOperator & WO_OR );
119554     assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
119555     pOrWc = &pTerm->u.pOrInfo->wc;
119556     pLevel->op = OP_Return;
119557     pLevel->p1 = regReturn;
119558
119559     /* Set up a new SrcList in pOrTab containing the table being scanned
119560     ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
119561     ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
119562     */
119563     if( pWInfo->nLevel>1 ){
119564       int nNotReady;                 /* The number of notReady tables */
119565       struct SrcList_item *origSrc;     /* Original list of tables */
119566       nNotReady = pWInfo->nLevel - iLevel - 1;
119567       pOrTab = sqlite3StackAllocRaw(db,
119568                             sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
119569       if( pOrTab==0 ) return notReady;
119570       pOrTab->nAlloc = (u8)(nNotReady + 1);
119571       pOrTab->nSrc = pOrTab->nAlloc;
119572       memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
119573       origSrc = pWInfo->pTabList->a;
119574       for(k=1; k<=nNotReady; k++){
119575         memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
119576       }
119577     }else{
119578       pOrTab = pWInfo->pTabList;
119579     }
119580
119581     /* Initialize the rowset register to contain NULL. An SQL NULL is 
119582     ** equivalent to an empty rowset.  Or, create an ephemeral index
119583     ** capable of holding primary keys in the case of a WITHOUT ROWID.
119584     **
119585     ** Also initialize regReturn to contain the address of the instruction 
119586     ** immediately following the OP_Return at the bottom of the loop. This
119587     ** is required in a few obscure LEFT JOIN cases where control jumps
119588     ** over the top of the loop into the body of it. In this case the 
119589     ** correct response for the end-of-loop code (the OP_Return) is to 
119590     ** fall through to the next instruction, just as an OP_Next does if
119591     ** called on an uninitialized cursor.
119592     */
119593     if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
119594       if( HasRowid(pTab) ){
119595         regRowset = ++pParse->nMem;
119596         sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
119597       }else{
119598         Index *pPk = sqlite3PrimaryKeyIndex(pTab);
119599         regRowset = pParse->nTab++;
119600         sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
119601         sqlite3VdbeSetP4KeyInfo(pParse, pPk);
119602       }
119603       regRowid = ++pParse->nMem;
119604     }
119605     iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
119606
119607     /* If the original WHERE clause is z of the form:  (x1 OR x2 OR ...) AND y
119608     ** Then for every term xN, evaluate as the subexpression: xN AND z
119609     ** That way, terms in y that are factored into the disjunction will
119610     ** be picked up by the recursive calls to sqlite3WhereBegin() below.
119611     **
119612     ** Actually, each subexpression is converted to "xN AND w" where w is
119613     ** the "interesting" terms of z - terms that did not originate in the
119614     ** ON or USING clause of a LEFT JOIN, and terms that are usable as 
119615     ** indices.
119616     **
119617     ** This optimization also only applies if the (x1 OR x2 OR ...) term
119618     ** is not contained in the ON clause of a LEFT JOIN.
119619     ** See ticket http://www.sqlite.org/src/info/f2369304e4
119620     */
119621     if( pWC->nTerm>1 ){
119622       int iTerm;
119623       for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
119624         Expr *pExpr = pWC->a[iTerm].pExpr;
119625         if( &pWC->a[iTerm] == pTerm ) continue;
119626         if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
119627         if( (pWC->a[iTerm].wtFlags & TERM_VIRTUAL)!=0 ) continue;
119628         if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
119629         testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
119630         pExpr = sqlite3ExprDup(db, pExpr, 0);
119631         pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
119632       }
119633       if( pAndExpr ){
119634         pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
119635       }
119636     }
119637
119638     /* Run a separate WHERE clause for each term of the OR clause.  After
119639     ** eliminating duplicates from other WHERE clauses, the action for each
119640     ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
119641     */
119642     wctrlFlags =  WHERE_OMIT_OPEN_CLOSE
119643                 | WHERE_FORCE_TABLE
119644                 | WHERE_ONETABLE_ONLY
119645                 | WHERE_NO_AUTOINDEX;
119646     for(ii=0; ii<pOrWc->nTerm; ii++){
119647       WhereTerm *pOrTerm = &pOrWc->a[ii];
119648       if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
119649         WhereInfo *pSubWInfo;           /* Info for single OR-term scan */
119650         Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
119651         int j1 = 0;                     /* Address of jump operation */
119652         if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
119653           pAndExpr->pLeft = pOrExpr;
119654           pOrExpr = pAndExpr;
119655         }
119656         /* Loop through table entries that match term pOrTerm. */
119657         WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
119658         pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
119659                                       wctrlFlags, iCovCur);
119660         assert( pSubWInfo || pParse->nErr || db->mallocFailed );
119661         if( pSubWInfo ){
119662           WhereLoop *pSubLoop;
119663           int addrExplain = explainOneScan(
119664               pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
119665           );
119666           addScanStatus(v, pOrTab, &pSubWInfo->a[0], addrExplain);
119667
119668           /* This is the sub-WHERE clause body.  First skip over
119669           ** duplicate rows from prior sub-WHERE clauses, and record the
119670           ** rowid (or PRIMARY KEY) for the current row so that the same
119671           ** row will be skipped in subsequent sub-WHERE clauses.
119672           */
119673           if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
119674             int r;
119675             int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
119676             if( HasRowid(pTab) ){
119677               r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
119678               j1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet);
119679               VdbeCoverage(v);
119680             }else{
119681               Index *pPk = sqlite3PrimaryKeyIndex(pTab);
119682               int nPk = pPk->nKeyCol;
119683               int iPk;
119684
119685               /* Read the PK into an array of temp registers. */
119686               r = sqlite3GetTempRange(pParse, nPk);
119687               for(iPk=0; iPk<nPk; iPk++){
119688                 int iCol = pPk->aiColumn[iPk];
119689                 sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur, r+iPk, 0);
119690               }
119691
119692               /* Check if the temp table already contains this key. If so,
119693               ** the row has already been included in the result set and
119694               ** can be ignored (by jumping past the Gosub below). Otherwise,
119695               ** insert the key into the temp table and proceed with processing
119696               ** the row.
119697               **
119698               ** Use some of the same optimizations as OP_RowSetTest: If iSet
119699               ** is zero, assume that the key cannot already be present in
119700               ** the temp table. And if iSet is -1, assume that there is no 
119701               ** need to insert the key into the temp table, as it will never 
119702               ** be tested for.  */ 
119703               if( iSet ){
119704                 j1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
119705                 VdbeCoverage(v);
119706               }
119707               if( iSet>=0 ){
119708                 sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
119709                 sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
119710                 if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
119711               }
119712
119713               /* Release the array of temp registers */
119714               sqlite3ReleaseTempRange(pParse, r, nPk);
119715             }
119716           }
119717
119718           /* Invoke the main loop body as a subroutine */
119719           sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
119720
119721           /* Jump here (skipping the main loop body subroutine) if the
119722           ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
119723           if( j1 ) sqlite3VdbeJumpHere(v, j1);
119724
119725           /* The pSubWInfo->untestedTerms flag means that this OR term
119726           ** contained one or more AND term from a notReady table.  The
119727           ** terms from the notReady table could not be tested and will
119728           ** need to be tested later.
119729           */
119730           if( pSubWInfo->untestedTerms ) untestedTerms = 1;
119731
119732           /* If all of the OR-connected terms are optimized using the same
119733           ** index, and the index is opened using the same cursor number
119734           ** by each call to sqlite3WhereBegin() made by this loop, it may
119735           ** be possible to use that index as a covering index.
119736           **
119737           ** If the call to sqlite3WhereBegin() above resulted in a scan that
119738           ** uses an index, and this is either the first OR-connected term
119739           ** processed or the index is the same as that used by all previous
119740           ** terms, set pCov to the candidate covering index. Otherwise, set 
119741           ** pCov to NULL to indicate that no candidate covering index will 
119742           ** be available.
119743           */
119744           pSubLoop = pSubWInfo->a[0].pWLoop;
119745           assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
119746           if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
119747            && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
119748            && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
119749           ){
119750             assert( pSubWInfo->a[0].iIdxCur==iCovCur );
119751             pCov = pSubLoop->u.btree.pIndex;
119752             wctrlFlags |= WHERE_REOPEN_IDX;
119753           }else{
119754             pCov = 0;
119755           }
119756
119757           /* Finish the loop through table entries that match term pOrTerm. */
119758           sqlite3WhereEnd(pSubWInfo);
119759         }
119760       }
119761     }
119762     pLevel->u.pCovidx = pCov;
119763     if( pCov ) pLevel->iIdxCur = iCovCur;
119764     if( pAndExpr ){
119765       pAndExpr->pLeft = 0;
119766       sqlite3ExprDelete(db, pAndExpr);
119767     }
119768     sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
119769     sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
119770     sqlite3VdbeResolveLabel(v, iLoopBody);
119771
119772     if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
119773     if( !untestedTerms ) disableTerm(pLevel, pTerm);
119774   }else
119775 #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
119776
119777   {
119778     /* Case 6:  There is no usable index.  We must do a complete
119779     **          scan of the entire table.
119780     */
119781     static const u8 aStep[] = { OP_Next, OP_Prev };
119782     static const u8 aStart[] = { OP_Rewind, OP_Last };
119783     assert( bRev==0 || bRev==1 );
119784     if( pTabItem->isRecursive ){
119785       /* Tables marked isRecursive have only a single row that is stored in
119786       ** a pseudo-cursor.  No need to Rewind or Next such cursors. */
119787       pLevel->op = OP_Noop;
119788     }else{
119789       pLevel->op = aStep[bRev];
119790       pLevel->p1 = iCur;
119791       pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
119792       VdbeCoverageIf(v, bRev==0);
119793       VdbeCoverageIf(v, bRev!=0);
119794       pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
119795     }
119796   }
119797
119798 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
119799   pLevel->addrVisit = sqlite3VdbeCurrentAddr(v);
119800 #endif
119801
119802   /* Insert code to test every subexpression that can be completely
119803   ** computed using the current set of tables.
119804   */
119805   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
119806     Expr *pE;
119807     int skipLikeAddr = 0;
119808     testcase( pTerm->wtFlags & TERM_VIRTUAL );
119809     testcase( pTerm->wtFlags & TERM_CODED );
119810     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
119811     if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
119812       testcase( pWInfo->untestedTerms==0
119813                && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
119814       pWInfo->untestedTerms = 1;
119815       continue;
119816     }
119817     pE = pTerm->pExpr;
119818     assert( pE!=0 );
119819     if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
119820       continue;
119821     }
119822     if( pTerm->wtFlags & TERM_LIKECOND ){
119823       assert( pLevel->iLikeRepCntr>0 );
119824       skipLikeAddr = sqlite3VdbeAddOp1(v, OP_IfNot, pLevel->iLikeRepCntr);
119825       VdbeCoverage(v);
119826     }
119827     sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
119828     if( skipLikeAddr ) sqlite3VdbeJumpHere(v, skipLikeAddr);
119829     pTerm->wtFlags |= TERM_CODED;
119830   }
119831
119832   /* Insert code to test for implied constraints based on transitivity
119833   ** of the "==" operator.
119834   **
119835   ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
119836   ** and we are coding the t1 loop and the t2 loop has not yet coded,
119837   ** then we cannot use the "t1.a=t2.b" constraint, but we can code
119838   ** the implied "t1.a=123" constraint.
119839   */
119840   for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
119841     Expr *pE, *pEAlt;
119842     WhereTerm *pAlt;
119843     if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
119844     if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
119845     if( pTerm->leftCursor!=iCur ) continue;
119846     if( pLevel->iLeftJoin ) continue;
119847     pE = pTerm->pExpr;
119848     assert( !ExprHasProperty(pE, EP_FromJoin) );
119849     assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
119850     pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
119851     if( pAlt==0 ) continue;
119852     if( pAlt->wtFlags & (TERM_CODED) ) continue;
119853     testcase( pAlt->eOperator & WO_EQ );
119854     testcase( pAlt->eOperator & WO_IN );
119855     VdbeModuleComment((v, "begin transitive constraint"));
119856     pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
119857     if( pEAlt ){
119858       *pEAlt = *pAlt->pExpr;
119859       pEAlt->pLeft = pE->pLeft;
119860       sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
119861       sqlite3StackFree(db, pEAlt);
119862     }
119863   }
119864
119865   /* For a LEFT OUTER JOIN, generate code that will record the fact that
119866   ** at least one row of the right table has matched the left table.  
119867   */
119868   if( pLevel->iLeftJoin ){
119869     pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
119870     sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
119871     VdbeComment((v, "record LEFT JOIN hit"));
119872     sqlite3ExprCacheClear(pParse);
119873     for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
119874       testcase( pTerm->wtFlags & TERM_VIRTUAL );
119875       testcase( pTerm->wtFlags & TERM_CODED );
119876       if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
119877       if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
119878         assert( pWInfo->untestedTerms );
119879         continue;
119880       }
119881       assert( pTerm->pExpr );
119882       sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
119883       pTerm->wtFlags |= TERM_CODED;
119884     }
119885   }
119886
119887   return pLevel->notReady;
119888 }
119889
119890 #ifdef WHERETRACE_ENABLED
119891 /*
119892 ** Print the content of a WhereTerm object
119893 */
119894 static void whereTermPrint(WhereTerm *pTerm, int iTerm){
119895   if( pTerm==0 ){
119896     sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
119897   }else{
119898     char zType[4];
119899     memcpy(zType, "...", 4);
119900     if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
119901     if( pTerm->eOperator & WO_EQUIV  ) zType[1] = 'E';
119902     if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
119903     sqlite3DebugPrintf("TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x\n",
119904                        iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb,
119905                        pTerm->eOperator);
119906     sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
119907   }
119908 }
119909 #endif
119910
119911 #ifdef WHERETRACE_ENABLED
119912 /*
119913 ** Print a WhereLoop object for debugging purposes
119914 */
119915 static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
119916   WhereInfo *pWInfo = pWC->pWInfo;
119917   int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
119918   struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
119919   Table *pTab = pItem->pTab;
119920   sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
119921                      p->iTab, nb, p->maskSelf, nb, p->prereq);
119922   sqlite3DebugPrintf(" %12s",
119923                      pItem->zAlias ? pItem->zAlias : pTab->zName);
119924   if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
119925     const char *zName;
119926     if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
119927       if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
119928         int i = sqlite3Strlen30(zName) - 1;
119929         while( zName[i]!='_' ) i--;
119930         zName += i;
119931       }
119932       sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
119933     }else{
119934       sqlite3DebugPrintf("%20s","");
119935     }
119936   }else{
119937     char *z;
119938     if( p->u.vtab.idxStr ){
119939       z = sqlite3_mprintf("(%d,\"%s\",%x)",
119940                 p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
119941     }else{
119942       z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
119943     }
119944     sqlite3DebugPrintf(" %-19s", z);
119945     sqlite3_free(z);
119946   }
119947   if( p->wsFlags & WHERE_SKIPSCAN ){
119948     sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->nSkip);
119949   }else{
119950     sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
119951   }
119952   sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
119953   if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
119954     int i;
119955     for(i=0; i<p->nLTerm; i++){
119956       whereTermPrint(p->aLTerm[i], i);
119957     }
119958   }
119959 }
119960 #endif
119961
119962 /*
119963 ** Convert bulk memory into a valid WhereLoop that can be passed
119964 ** to whereLoopClear harmlessly.
119965 */
119966 static void whereLoopInit(WhereLoop *p){
119967   p->aLTerm = p->aLTermSpace;
119968   p->nLTerm = 0;
119969   p->nLSlot = ArraySize(p->aLTermSpace);
119970   p->wsFlags = 0;
119971 }
119972
119973 /*
119974 ** Clear the WhereLoop.u union.  Leave WhereLoop.pLTerm intact.
119975 */
119976 static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
119977   if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
119978     if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
119979       sqlite3_free(p->u.vtab.idxStr);
119980       p->u.vtab.needFree = 0;
119981       p->u.vtab.idxStr = 0;
119982     }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
119983       sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
119984       sqlite3DbFree(db, p->u.btree.pIndex);
119985       p->u.btree.pIndex = 0;
119986     }
119987   }
119988 }
119989
119990 /*
119991 ** Deallocate internal memory used by a WhereLoop object
119992 */
119993 static void whereLoopClear(sqlite3 *db, WhereLoop *p){
119994   if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
119995   whereLoopClearUnion(db, p);
119996   whereLoopInit(p);
119997 }
119998
119999 /*
120000 ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
120001 */
120002 static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
120003   WhereTerm **paNew;
120004   if( p->nLSlot>=n ) return SQLITE_OK;
120005   n = (n+7)&~7;
120006   paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
120007   if( paNew==0 ) return SQLITE_NOMEM;
120008   memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
120009   if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
120010   p->aLTerm = paNew;
120011   p->nLSlot = n;
120012   return SQLITE_OK;
120013 }
120014
120015 /*
120016 ** Transfer content from the second pLoop into the first.
120017 */
120018 static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
120019   whereLoopClearUnion(db, pTo);
120020   if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
120021     memset(&pTo->u, 0, sizeof(pTo->u));
120022     return SQLITE_NOMEM;
120023   }
120024   memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
120025   memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
120026   if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
120027     pFrom->u.vtab.needFree = 0;
120028   }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
120029     pFrom->u.btree.pIndex = 0;
120030   }
120031   return SQLITE_OK;
120032 }
120033
120034 /*
120035 ** Delete a WhereLoop object
120036 */
120037 static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
120038   whereLoopClear(db, p);
120039   sqlite3DbFree(db, p);
120040 }
120041
120042 /*
120043 ** Free a WhereInfo structure
120044 */
120045 static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
120046   if( ALWAYS(pWInfo) ){
120047     whereClauseClear(&pWInfo->sWC);
120048     while( pWInfo->pLoops ){
120049       WhereLoop *p = pWInfo->pLoops;
120050       pWInfo->pLoops = p->pNextLoop;
120051       whereLoopDelete(db, p);
120052     }
120053     sqlite3DbFree(db, pWInfo);
120054   }
120055 }
120056
120057 /*
120058 ** Return TRUE if all of the following are true:
120059 **
120060 **   (1)  X has the same or lower cost that Y
120061 **   (2)  X is a proper subset of Y
120062 **   (3)  X skips at least as many columns as Y
120063 **
120064 ** By "proper subset" we mean that X uses fewer WHERE clause terms
120065 ** than Y and that every WHERE clause term used by X is also used
120066 ** by Y.
120067 **
120068 ** If X is a proper subset of Y then Y is a better choice and ought
120069 ** to have a lower cost.  This routine returns TRUE when that cost 
120070 ** relationship is inverted and needs to be adjusted.  The third rule
120071 ** was added because if X uses skip-scan less than Y it still might
120072 ** deserve a lower cost even if it is a proper subset of Y.
120073 */
120074 static int whereLoopCheaperProperSubset(
120075   const WhereLoop *pX,       /* First WhereLoop to compare */
120076   const WhereLoop *pY        /* Compare against this WhereLoop */
120077 ){
120078   int i, j;
120079   if( pX->nLTerm-pX->nSkip >= pY->nLTerm-pY->nSkip ){
120080     return 0; /* X is not a subset of Y */
120081   }
120082   if( pY->nSkip > pX->nSkip ) return 0;
120083   if( pX->rRun >= pY->rRun ){
120084     if( pX->rRun > pY->rRun ) return 0;    /* X costs more than Y */
120085     if( pX->nOut > pY->nOut ) return 0;    /* X costs more than Y */
120086   }
120087   for(i=pX->nLTerm-1; i>=0; i--){
120088     if( pX->aLTerm[i]==0 ) continue;
120089     for(j=pY->nLTerm-1; j>=0; j--){
120090       if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
120091     }
120092     if( j<0 ) return 0;  /* X not a subset of Y since term X[i] not used by Y */
120093   }
120094   return 1;  /* All conditions meet */
120095 }
120096
120097 /*
120098 ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
120099 ** that:
120100 **
120101 **   (1) pTemplate costs less than any other WhereLoops that are a proper
120102 **       subset of pTemplate
120103 **
120104 **   (2) pTemplate costs more than any other WhereLoops for which pTemplate
120105 **       is a proper subset.
120106 **
120107 ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
120108 ** WHERE clause terms than Y and that every WHERE clause term used by X is
120109 ** also used by Y.
120110 */
120111 static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
120112   if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
120113   for(; p; p=p->pNextLoop){
120114     if( p->iTab!=pTemplate->iTab ) continue;
120115     if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
120116     if( whereLoopCheaperProperSubset(p, pTemplate) ){
120117       /* Adjust pTemplate cost downward so that it is cheaper than its 
120118       ** subset p. */
120119       WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
120120                        pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut-1));
120121       pTemplate->rRun = p->rRun;
120122       pTemplate->nOut = p->nOut - 1;
120123     }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
120124       /* Adjust pTemplate cost upward so that it is costlier than p since
120125       ** pTemplate is a proper subset of p */
120126       WHERETRACE(0x80,("subset cost adjustment %d,%d to %d,%d\n",
120127                        pTemplate->rRun, pTemplate->nOut, p->rRun, p->nOut+1));
120128       pTemplate->rRun = p->rRun;
120129       pTemplate->nOut = p->nOut + 1;
120130     }
120131   }
120132 }
120133
120134 /*
120135 ** Search the list of WhereLoops in *ppPrev looking for one that can be
120136 ** supplanted by pTemplate.
120137 **
120138 ** Return NULL if the WhereLoop list contains an entry that can supplant
120139 ** pTemplate, in other words if pTemplate does not belong on the list.
120140 **
120141 ** If pX is a WhereLoop that pTemplate can supplant, then return the
120142 ** link that points to pX.
120143 **
120144 ** If pTemplate cannot supplant any existing element of the list but needs
120145 ** to be added to the list, then return a pointer to the tail of the list.
120146 */
120147 static WhereLoop **whereLoopFindLesser(
120148   WhereLoop **ppPrev,
120149   const WhereLoop *pTemplate
120150 ){
120151   WhereLoop *p;
120152   for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
120153     if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
120154       /* If either the iTab or iSortIdx values for two WhereLoop are different
120155       ** then those WhereLoops need to be considered separately.  Neither is
120156       ** a candidate to replace the other. */
120157       continue;
120158     }
120159     /* In the current implementation, the rSetup value is either zero
120160     ** or the cost of building an automatic index (NlogN) and the NlogN
120161     ** is the same for compatible WhereLoops. */
120162     assert( p->rSetup==0 || pTemplate->rSetup==0 
120163                  || p->rSetup==pTemplate->rSetup );
120164
120165     /* whereLoopAddBtree() always generates and inserts the automatic index
120166     ** case first.  Hence compatible candidate WhereLoops never have a larger
120167     ** rSetup. Call this SETUP-INVARIANT */
120168     assert( p->rSetup>=pTemplate->rSetup );
120169
120170     /* Any loop using an appliation-defined index (or PRIMARY KEY or
120171     ** UNIQUE constraint) with one or more == constraints is better
120172     ** than an automatic index. Unless it is a skip-scan. */
120173     if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
120174      && (pTemplate->nSkip)==0
120175      && (pTemplate->wsFlags & WHERE_INDEXED)!=0
120176      && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
120177      && (p->prereq & pTemplate->prereq)==pTemplate->prereq
120178     ){
120179       break;
120180     }
120181
120182     /* If existing WhereLoop p is better than pTemplate, pTemplate can be
120183     ** discarded.  WhereLoop p is better if:
120184     **   (1)  p has no more dependencies than pTemplate, and
120185     **   (2)  p has an equal or lower cost than pTemplate
120186     */
120187     if( (p->prereq & pTemplate->prereq)==p->prereq    /* (1)  */
120188      && p->rSetup<=pTemplate->rSetup                  /* (2a) */
120189      && p->rRun<=pTemplate->rRun                      /* (2b) */
120190      && p->nOut<=pTemplate->nOut                      /* (2c) */
120191     ){
120192       return 0;  /* Discard pTemplate */
120193     }
120194
120195     /* If pTemplate is always better than p, then cause p to be overwritten
120196     ** with pTemplate.  pTemplate is better than p if:
120197     **   (1)  pTemplate has no more dependences than p, and
120198     **   (2)  pTemplate has an equal or lower cost than p.
120199     */
120200     if( (p->prereq & pTemplate->prereq)==pTemplate->prereq   /* (1)  */
120201      && p->rRun>=pTemplate->rRun                             /* (2a) */
120202      && p->nOut>=pTemplate->nOut                             /* (2b) */
120203     ){
120204       assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
120205       break;   /* Cause p to be overwritten by pTemplate */
120206     }
120207   }
120208   return ppPrev;
120209 }
120210
120211 /*
120212 ** Insert or replace a WhereLoop entry using the template supplied.
120213 **
120214 ** An existing WhereLoop entry might be overwritten if the new template
120215 ** is better and has fewer dependencies.  Or the template will be ignored
120216 ** and no insert will occur if an existing WhereLoop is faster and has
120217 ** fewer dependencies than the template.  Otherwise a new WhereLoop is
120218 ** added based on the template.
120219 **
120220 ** If pBuilder->pOrSet is not NULL then we care about only the
120221 ** prerequisites and rRun and nOut costs of the N best loops.  That
120222 ** information is gathered in the pBuilder->pOrSet object.  This special
120223 ** processing mode is used only for OR clause processing.
120224 **
120225 ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
120226 ** still might overwrite similar loops with the new template if the
120227 ** new template is better.  Loops may be overwritten if the following 
120228 ** conditions are met:
120229 **
120230 **    (1)  They have the same iTab.
120231 **    (2)  They have the same iSortIdx.
120232 **    (3)  The template has same or fewer dependencies than the current loop
120233 **    (4)  The template has the same or lower cost than the current loop
120234 */
120235 static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
120236   WhereLoop **ppPrev, *p;
120237   WhereInfo *pWInfo = pBuilder->pWInfo;
120238   sqlite3 *db = pWInfo->pParse->db;
120239
120240   /* If pBuilder->pOrSet is defined, then only keep track of the costs
120241   ** and prereqs.
120242   */
120243   if( pBuilder->pOrSet!=0 ){
120244 #if WHERETRACE_ENABLED
120245     u16 n = pBuilder->pOrSet->n;
120246     int x =
120247 #endif
120248     whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
120249                                     pTemplate->nOut);
120250 #if WHERETRACE_ENABLED /* 0x8 */
120251     if( sqlite3WhereTrace & 0x8 ){
120252       sqlite3DebugPrintf(x?"   or-%d:  ":"   or-X:  ", n);
120253       whereLoopPrint(pTemplate, pBuilder->pWC);
120254     }
120255 #endif
120256     return SQLITE_OK;
120257   }
120258
120259   /* Look for an existing WhereLoop to replace with pTemplate
120260   */
120261   whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
120262   ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
120263
120264   if( ppPrev==0 ){
120265     /* There already exists a WhereLoop on the list that is better
120266     ** than pTemplate, so just ignore pTemplate */
120267 #if WHERETRACE_ENABLED /* 0x8 */
120268     if( sqlite3WhereTrace & 0x8 ){
120269       sqlite3DebugPrintf("   skip: ");
120270       whereLoopPrint(pTemplate, pBuilder->pWC);
120271     }
120272 #endif
120273     return SQLITE_OK;  
120274   }else{
120275     p = *ppPrev;
120276   }
120277
120278   /* If we reach this point it means that either p[] should be overwritten
120279   ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
120280   ** WhereLoop and insert it.
120281   */
120282 #if WHERETRACE_ENABLED /* 0x8 */
120283   if( sqlite3WhereTrace & 0x8 ){
120284     if( p!=0 ){
120285       sqlite3DebugPrintf("replace: ");
120286       whereLoopPrint(p, pBuilder->pWC);
120287     }
120288     sqlite3DebugPrintf("    add: ");
120289     whereLoopPrint(pTemplate, pBuilder->pWC);
120290   }
120291 #endif
120292   if( p==0 ){
120293     /* Allocate a new WhereLoop to add to the end of the list */
120294     *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
120295     if( p==0 ) return SQLITE_NOMEM;
120296     whereLoopInit(p);
120297     p->pNextLoop = 0;
120298   }else{
120299     /* We will be overwriting WhereLoop p[].  But before we do, first
120300     ** go through the rest of the list and delete any other entries besides
120301     ** p[] that are also supplated by pTemplate */
120302     WhereLoop **ppTail = &p->pNextLoop;
120303     WhereLoop *pToDel;
120304     while( *ppTail ){
120305       ppTail = whereLoopFindLesser(ppTail, pTemplate);
120306       if( ppTail==0 ) break;
120307       pToDel = *ppTail;
120308       if( pToDel==0 ) break;
120309       *ppTail = pToDel->pNextLoop;
120310 #if WHERETRACE_ENABLED /* 0x8 */
120311       if( sqlite3WhereTrace & 0x8 ){
120312         sqlite3DebugPrintf(" delete: ");
120313         whereLoopPrint(pToDel, pBuilder->pWC);
120314       }
120315 #endif
120316       whereLoopDelete(db, pToDel);
120317     }
120318   }
120319   whereLoopXfer(db, p, pTemplate);
120320   if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
120321     Index *pIndex = p->u.btree.pIndex;
120322     if( pIndex && pIndex->tnum==0 ){
120323       p->u.btree.pIndex = 0;
120324     }
120325   }
120326   return SQLITE_OK;
120327 }
120328
120329 /*
120330 ** Adjust the WhereLoop.nOut value downward to account for terms of the
120331 ** WHERE clause that reference the loop but which are not used by an
120332 ** index.
120333 *
120334 ** For every WHERE clause term that is not used by the index
120335 ** and which has a truth probability assigned by one of the likelihood(),
120336 ** likely(), or unlikely() SQL functions, reduce the estimated number
120337 ** of output rows by the probability specified.
120338 **
120339 ** TUNING:  For every WHERE clause term that is not used by the index
120340 ** and which does not have an assigned truth probability, heuristics
120341 ** described below are used to try to estimate the truth probability.
120342 ** TODO --> Perhaps this is something that could be improved by better
120343 ** table statistics.
120344 **
120345 ** Heuristic 1:  Estimate the truth probability as 93.75%.  The 93.75%
120346 ** value corresponds to -1 in LogEst notation, so this means decrement
120347 ** the WhereLoop.nOut field for every such WHERE clause term.
120348 **
120349 ** Heuristic 2:  If there exists one or more WHERE clause terms of the
120350 ** form "x==EXPR" and EXPR is not a constant 0 or 1, then make sure the
120351 ** final output row estimate is no greater than 1/4 of the total number
120352 ** of rows in the table.  In other words, assume that x==EXPR will filter
120353 ** out at least 3 out of 4 rows.  If EXPR is -1 or 0 or 1, then maybe the
120354 ** "x" column is boolean or else -1 or 0 or 1 is a common default value
120355 ** on the "x" column and so in that case only cap the output row estimate
120356 ** at 1/2 instead of 1/4.
120357 */
120358 static void whereLoopOutputAdjust(
120359   WhereClause *pWC,      /* The WHERE clause */
120360   WhereLoop *pLoop,      /* The loop to adjust downward */
120361   LogEst nRow            /* Number of rows in the entire table */
120362 ){
120363   WhereTerm *pTerm, *pX;
120364   Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
120365   int i, j, k;
120366   LogEst iReduce = 0;    /* pLoop->nOut should not exceed nRow-iReduce */
120367
120368   assert( (pLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
120369   for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
120370     if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
120371     if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
120372     if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
120373     for(j=pLoop->nLTerm-1; j>=0; j--){
120374       pX = pLoop->aLTerm[j];
120375       if( pX==0 ) continue;
120376       if( pX==pTerm ) break;
120377       if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
120378     }
120379     if( j<0 ){
120380       if( pTerm->truthProb<=0 ){
120381         /* If a truth probability is specified using the likelihood() hints,
120382         ** then use the probability provided by the application. */
120383         pLoop->nOut += pTerm->truthProb;
120384       }else{
120385         /* In the absence of explicit truth probabilities, use heuristics to
120386         ** guess a reasonable truth probability. */
120387         pLoop->nOut--;
120388         if( pTerm->eOperator&WO_EQ ){
120389           Expr *pRight = pTerm->pExpr->pRight;
120390           if( sqlite3ExprIsInteger(pRight, &k) && k>=(-1) && k<=1 ){
120391             k = 10;
120392           }else{
120393             k = 20;
120394           }
120395           if( iReduce<k ) iReduce = k;
120396         }
120397       }
120398     }
120399   }
120400   if( pLoop->nOut > nRow-iReduce )  pLoop->nOut = nRow - iReduce;
120401 }
120402
120403 /*
120404 ** Adjust the cost C by the costMult facter T.  This only occurs if
120405 ** compiled with -DSQLITE_ENABLE_COSTMULT
120406 */
120407 #ifdef SQLITE_ENABLE_COSTMULT
120408 # define ApplyCostMultiplier(C,T)  C += T
120409 #else
120410 # define ApplyCostMultiplier(C,T)
120411 #endif
120412
120413 /*
120414 ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the 
120415 ** index pIndex. Try to match one more.
120416 **
120417 ** When this function is called, pBuilder->pNew->nOut contains the 
120418 ** number of rows expected to be visited by filtering using the nEq 
120419 ** terms only. If it is modified, this value is restored before this 
120420 ** function returns.
120421 **
120422 ** If pProbe->tnum==0, that means pIndex is a fake index used for the
120423 ** INTEGER PRIMARY KEY.
120424 */
120425 static int whereLoopAddBtreeIndex(
120426   WhereLoopBuilder *pBuilder,     /* The WhereLoop factory */
120427   struct SrcList_item *pSrc,      /* FROM clause term being analyzed */
120428   Index *pProbe,                  /* An index on pSrc */
120429   LogEst nInMul                   /* log(Number of iterations due to IN) */
120430 ){
120431   WhereInfo *pWInfo = pBuilder->pWInfo;  /* WHERE analyse context */
120432   Parse *pParse = pWInfo->pParse;        /* Parsing context */
120433   sqlite3 *db = pParse->db;       /* Database connection malloc context */
120434   WhereLoop *pNew;                /* Template WhereLoop under construction */
120435   WhereTerm *pTerm;               /* A WhereTerm under consideration */
120436   int opMask;                     /* Valid operators for constraints */
120437   WhereScan scan;                 /* Iterator for WHERE terms */
120438   Bitmask saved_prereq;           /* Original value of pNew->prereq */
120439   u16 saved_nLTerm;               /* Original value of pNew->nLTerm */
120440   u16 saved_nEq;                  /* Original value of pNew->u.btree.nEq */
120441   u16 saved_nSkip;                /* Original value of pNew->nSkip */
120442   u32 saved_wsFlags;              /* Original value of pNew->wsFlags */
120443   LogEst saved_nOut;              /* Original value of pNew->nOut */
120444   int iCol;                       /* Index of the column in the table */
120445   int rc = SQLITE_OK;             /* Return code */
120446   LogEst rSize;                   /* Number of rows in the table */
120447   LogEst rLogSize;                /* Logarithm of table size */
120448   WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
120449
120450   pNew = pBuilder->pNew;
120451   if( db->mallocFailed ) return SQLITE_NOMEM;
120452
120453   assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
120454   assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
120455   if( pNew->wsFlags & WHERE_BTM_LIMIT ){
120456     opMask = WO_LT|WO_LE;
120457   }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
120458     opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
120459   }else{
120460     opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
120461   }
120462   if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
120463
120464   assert( pNew->u.btree.nEq<pProbe->nColumn );
120465   iCol = pProbe->aiColumn[pNew->u.btree.nEq];
120466
120467   pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
120468                         opMask, pProbe);
120469   saved_nEq = pNew->u.btree.nEq;
120470   saved_nSkip = pNew->nSkip;
120471   saved_nLTerm = pNew->nLTerm;
120472   saved_wsFlags = pNew->wsFlags;
120473   saved_prereq = pNew->prereq;
120474   saved_nOut = pNew->nOut;
120475   pNew->rSetup = 0;
120476   rSize = pProbe->aiRowLogEst[0];
120477   rLogSize = estLog(rSize);
120478   for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
120479     u16 eOp = pTerm->eOperator;   /* Shorthand for pTerm->eOperator */
120480     LogEst rCostIdx;
120481     LogEst nOutUnadjusted;        /* nOut before IN() and WHERE adjustments */
120482     int nIn = 0;
120483 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
120484     int nRecValid = pBuilder->nRecValid;
120485 #endif
120486     if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
120487      && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
120488     ){
120489       continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
120490     }
120491     if( pTerm->prereqRight & pNew->maskSelf ) continue;
120492
120493     /* Do not allow the upper bound of a LIKE optimization range constraint
120494     ** to mix with a lower range bound from some other source */
120495     if( pTerm->wtFlags & TERM_LIKEOPT && pTerm->eOperator==WO_LT ) continue;
120496
120497     pNew->wsFlags = saved_wsFlags;
120498     pNew->u.btree.nEq = saved_nEq;
120499     pNew->nLTerm = saved_nLTerm;
120500     if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
120501     pNew->aLTerm[pNew->nLTerm++] = pTerm;
120502     pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
120503
120504     assert( nInMul==0
120505         || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0 
120506         || (pNew->wsFlags & WHERE_COLUMN_IN)!=0 
120507         || (pNew->wsFlags & WHERE_SKIPSCAN)!=0 
120508     );
120509
120510     if( eOp & WO_IN ){
120511       Expr *pExpr = pTerm->pExpr;
120512       pNew->wsFlags |= WHERE_COLUMN_IN;
120513       if( ExprHasProperty(pExpr, EP_xIsSelect) ){
120514         /* "x IN (SELECT ...)":  TUNING: the SELECT returns 25 rows */
120515         nIn = 46;  assert( 46==sqlite3LogEst(25) );
120516       }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
120517         /* "x IN (value, value, ...)" */
120518         nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
120519       }
120520       assert( nIn>0 );  /* RHS always has 2 or more terms...  The parser
120521                         ** changes "x IN (?)" into "x=?". */
120522
120523     }else if( eOp & (WO_EQ) ){
120524       pNew->wsFlags |= WHERE_COLUMN_EQ;
120525       if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1) ){
120526         if( iCol>=0 && !IsUniqueIndex(pProbe) ){
120527           pNew->wsFlags |= WHERE_UNQ_WANTED;
120528         }else{
120529           pNew->wsFlags |= WHERE_ONEROW;
120530         }
120531       }
120532     }else if( eOp & WO_ISNULL ){
120533       pNew->wsFlags |= WHERE_COLUMN_NULL;
120534     }else if( eOp & (WO_GT|WO_GE) ){
120535       testcase( eOp & WO_GT );
120536       testcase( eOp & WO_GE );
120537       pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
120538       pBtm = pTerm;
120539       pTop = 0;
120540       if( pTerm->wtFlags & TERM_LIKEOPT ){
120541         /* Range contraints that come from the LIKE optimization are
120542         ** always used in pairs. */
120543         pTop = &pTerm[1];
120544         assert( (pTop-(pTerm->pWC->a))<pTerm->pWC->nTerm );
120545         assert( pTop->wtFlags & TERM_LIKEOPT );
120546         assert( pTop->eOperator==WO_LT );
120547         if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
120548         pNew->aLTerm[pNew->nLTerm++] = pTop;
120549         pNew->wsFlags |= WHERE_TOP_LIMIT;
120550       }
120551     }else{
120552       assert( eOp & (WO_LT|WO_LE) );
120553       testcase( eOp & WO_LT );
120554       testcase( eOp & WO_LE );
120555       pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
120556       pTop = pTerm;
120557       pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
120558                      pNew->aLTerm[pNew->nLTerm-2] : 0;
120559     }
120560
120561     /* At this point pNew->nOut is set to the number of rows expected to
120562     ** be visited by the index scan before considering term pTerm, or the
120563     ** values of nIn and nInMul. In other words, assuming that all 
120564     ** "x IN(...)" terms are replaced with "x = ?". This block updates
120565     ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul).  */
120566     assert( pNew->nOut==saved_nOut );
120567     if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
120568       /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
120569       ** data, using some other estimate.  */
120570       whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
120571     }else{
120572       int nEq = ++pNew->u.btree.nEq;
120573       assert( eOp & (WO_ISNULL|WO_EQ|WO_IN) );
120574
120575       assert( pNew->nOut==saved_nOut );
120576       if( pTerm->truthProb<=0 && iCol>=0 ){
120577         assert( (eOp & WO_IN) || nIn==0 );
120578         testcase( eOp & WO_IN );
120579         pNew->nOut += pTerm->truthProb;
120580         pNew->nOut -= nIn;
120581       }else{
120582 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
120583         tRowcnt nOut = 0;
120584         if( nInMul==0 
120585          && pProbe->nSample 
120586          && pNew->u.btree.nEq<=pProbe->nSampleCol
120587          && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
120588         ){
120589           Expr *pExpr = pTerm->pExpr;
120590           if( (eOp & (WO_EQ|WO_ISNULL))!=0 ){
120591             testcase( eOp & WO_EQ );
120592             testcase( eOp & WO_ISNULL );
120593             rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
120594           }else{
120595             rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
120596           }
120597           if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
120598           if( rc!=SQLITE_OK ) break;          /* Jump out of the pTerm loop */
120599           if( nOut ){
120600             pNew->nOut = sqlite3LogEst(nOut);
120601             if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
120602             pNew->nOut -= nIn;
120603           }
120604         }
120605         if( nOut==0 )
120606 #endif
120607         {
120608           pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
120609           if( eOp & WO_ISNULL ){
120610             /* TUNING: If there is no likelihood() value, assume that a 
120611             ** "col IS NULL" expression matches twice as many rows 
120612             ** as (col=?). */
120613             pNew->nOut += 10;
120614           }
120615         }
120616       }
120617     }
120618
120619     /* Set rCostIdx to the cost of visiting selected rows in index. Add
120620     ** it to pNew->rRun, which is currently set to the cost of the index
120621     ** seek only. Then, if this is a non-covering index, add the cost of
120622     ** visiting the rows in the main table.  */
120623     rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
120624     pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
120625     if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
120626       pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
120627     }
120628     ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
120629
120630     nOutUnadjusted = pNew->nOut;
120631     pNew->rRun += nInMul + nIn;
120632     pNew->nOut += nInMul + nIn;
120633     whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
120634     rc = whereLoopInsert(pBuilder, pNew);
120635
120636     if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
120637       pNew->nOut = saved_nOut;
120638     }else{
120639       pNew->nOut = nOutUnadjusted;
120640     }
120641
120642     if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
120643      && pNew->u.btree.nEq<pProbe->nColumn
120644     ){
120645       whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
120646     }
120647     pNew->nOut = saved_nOut;
120648 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
120649     pBuilder->nRecValid = nRecValid;
120650 #endif
120651   }
120652   pNew->prereq = saved_prereq;
120653   pNew->u.btree.nEq = saved_nEq;
120654   pNew->nSkip = saved_nSkip;
120655   pNew->wsFlags = saved_wsFlags;
120656   pNew->nOut = saved_nOut;
120657   pNew->nLTerm = saved_nLTerm;
120658
120659   /* Consider using a skip-scan if there are no WHERE clause constraints
120660   ** available for the left-most terms of the index, and if the average
120661   ** number of repeats in the left-most terms is at least 18. 
120662   **
120663   ** The magic number 18 is selected on the basis that scanning 17 rows
120664   ** is almost always quicker than an index seek (even though if the index
120665   ** contains fewer than 2^17 rows we assume otherwise in other parts of
120666   ** the code). And, even if it is not, it should not be too much slower. 
120667   ** On the other hand, the extra seeks could end up being significantly
120668   ** more expensive.  */
120669   assert( 42==sqlite3LogEst(18) );
120670   if( saved_nEq==saved_nSkip
120671    && saved_nEq+1<pProbe->nKeyCol
120672    && pProbe->noSkipScan==0
120673    && pProbe->aiRowLogEst[saved_nEq+1]>=42  /* TUNING: Minimum for skip-scan */
120674    && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
120675   ){
120676     LogEst nIter;
120677     pNew->u.btree.nEq++;
120678     pNew->nSkip++;
120679     pNew->aLTerm[pNew->nLTerm++] = 0;
120680     pNew->wsFlags |= WHERE_SKIPSCAN;
120681     nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
120682     pNew->nOut -= nIter;
120683     /* TUNING:  Because uncertainties in the estimates for skip-scan queries,
120684     ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
120685     nIter += 5;
120686     whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
120687     pNew->nOut = saved_nOut;
120688     pNew->u.btree.nEq = saved_nEq;
120689     pNew->nSkip = saved_nSkip;
120690     pNew->wsFlags = saved_wsFlags;
120691   }
120692
120693   return rc;
120694 }
120695
120696 /*
120697 ** Return True if it is possible that pIndex might be useful in
120698 ** implementing the ORDER BY clause in pBuilder.
120699 **
120700 ** Return False if pBuilder does not contain an ORDER BY clause or
120701 ** if there is no way for pIndex to be useful in implementing that
120702 ** ORDER BY clause.
120703 */
120704 static int indexMightHelpWithOrderBy(
120705   WhereLoopBuilder *pBuilder,
120706   Index *pIndex,
120707   int iCursor
120708 ){
120709   ExprList *pOB;
120710   int ii, jj;
120711
120712   if( pIndex->bUnordered ) return 0;
120713   if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
120714   for(ii=0; ii<pOB->nExpr; ii++){
120715     Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
120716     if( pExpr->op!=TK_COLUMN ) return 0;
120717     if( pExpr->iTable==iCursor ){
120718       if( pExpr->iColumn<0 ) return 1;
120719       for(jj=0; jj<pIndex->nKeyCol; jj++){
120720         if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
120721       }
120722     }
120723   }
120724   return 0;
120725 }
120726
120727 /*
120728 ** Return a bitmask where 1s indicate that the corresponding column of
120729 ** the table is used by an index.  Only the first 63 columns are considered.
120730 */
120731 static Bitmask columnsInIndex(Index *pIdx){
120732   Bitmask m = 0;
120733   int j;
120734   for(j=pIdx->nColumn-1; j>=0; j--){
120735     int x = pIdx->aiColumn[j];
120736     if( x>=0 ){
120737       testcase( x==BMS-1 );
120738       testcase( x==BMS-2 );
120739       if( x<BMS-1 ) m |= MASKBIT(x);
120740     }
120741   }
120742   return m;
120743 }
120744
120745 /* Check to see if a partial index with pPartIndexWhere can be used
120746 ** in the current query.  Return true if it can be and false if not.
120747 */
120748 static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
120749   int i;
120750   WhereTerm *pTerm;
120751   for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
120752     Expr *pExpr = pTerm->pExpr;
120753     if( sqlite3ExprImpliesExpr(pExpr, pWhere, iTab) 
120754      && (!ExprHasProperty(pExpr, EP_FromJoin) || pExpr->iRightJoinTable==iTab)
120755     ){
120756       return 1;
120757     }
120758   }
120759   return 0;
120760 }
120761
120762 /*
120763 ** Add all WhereLoop objects for a single table of the join where the table
120764 ** is idenfied by pBuilder->pNew->iTab.  That table is guaranteed to be
120765 ** a b-tree table, not a virtual table.
120766 **
120767 ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
120768 ** are calculated as follows:
120769 **
120770 ** For a full scan, assuming the table (or index) contains nRow rows:
120771 **
120772 **     cost = nRow * 3.0                    // full-table scan
120773 **     cost = nRow * K                      // scan of covering index
120774 **     cost = nRow * (K+3.0)                // scan of non-covering index
120775 **
120776 ** where K is a value between 1.1 and 3.0 set based on the relative 
120777 ** estimated average size of the index and table records.
120778 **
120779 ** For an index scan, where nVisit is the number of index rows visited
120780 ** by the scan, and nSeek is the number of seek operations required on 
120781 ** the index b-tree:
120782 **
120783 **     cost = nSeek * (log(nRow) + K * nVisit)          // covering index
120784 **     cost = nSeek * (log(nRow) + (K+3.0) * nVisit)    // non-covering index
120785 **
120786 ** Normally, nSeek is 1. nSeek values greater than 1 come about if the 
120787 ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when 
120788 ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
120789 **
120790 ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
120791 ** of uncertainty.  For this reason, scoring is designed to pick plans that
120792 ** "do the least harm" if the estimates are inaccurate.  For example, a
120793 ** log(nRow) factor is omitted from a non-covering index scan in order to
120794 ** bias the scoring in favor of using an index, since the worst-case
120795 ** performance of using an index is far better than the worst-case performance
120796 ** of a full table scan.
120797 */
120798 static int whereLoopAddBtree(
120799   WhereLoopBuilder *pBuilder, /* WHERE clause information */
120800   Bitmask mExtra              /* Extra prerequesites for using this table */
120801 ){
120802   WhereInfo *pWInfo;          /* WHERE analysis context */
120803   Index *pProbe;              /* An index we are evaluating */
120804   Index sPk;                  /* A fake index object for the primary key */
120805   LogEst aiRowEstPk[2];       /* The aiRowLogEst[] value for the sPk index */
120806   i16 aiColumnPk = -1;        /* The aColumn[] value for the sPk index */
120807   SrcList *pTabList;          /* The FROM clause */
120808   struct SrcList_item *pSrc;  /* The FROM clause btree term to add */
120809   WhereLoop *pNew;            /* Template WhereLoop object */
120810   int rc = SQLITE_OK;         /* Return code */
120811   int iSortIdx = 1;           /* Index number */
120812   int b;                      /* A boolean value */
120813   LogEst rSize;               /* number of rows in the table */
120814   LogEst rLogSize;            /* Logarithm of the number of rows in the table */
120815   WhereClause *pWC;           /* The parsed WHERE clause */
120816   Table *pTab;                /* Table being queried */
120817   
120818   pNew = pBuilder->pNew;
120819   pWInfo = pBuilder->pWInfo;
120820   pTabList = pWInfo->pTabList;
120821   pSrc = pTabList->a + pNew->iTab;
120822   pTab = pSrc->pTab;
120823   pWC = pBuilder->pWC;
120824   assert( !IsVirtual(pSrc->pTab) );
120825
120826   if( pSrc->pIndex ){
120827     /* An INDEXED BY clause specifies a particular index to use */
120828     pProbe = pSrc->pIndex;
120829   }else if( !HasRowid(pTab) ){
120830     pProbe = pTab->pIndex;
120831   }else{
120832     /* There is no INDEXED BY clause.  Create a fake Index object in local
120833     ** variable sPk to represent the rowid primary key index.  Make this
120834     ** fake index the first in a chain of Index objects with all of the real
120835     ** indices to follow */
120836     Index *pFirst;                  /* First of real indices on the table */
120837     memset(&sPk, 0, sizeof(Index));
120838     sPk.nKeyCol = 1;
120839     sPk.nColumn = 1;
120840     sPk.aiColumn = &aiColumnPk;
120841     sPk.aiRowLogEst = aiRowEstPk;
120842     sPk.onError = OE_Replace;
120843     sPk.pTable = pTab;
120844     sPk.szIdxRow = pTab->szTabRow;
120845     aiRowEstPk[0] = pTab->nRowLogEst;
120846     aiRowEstPk[1] = 0;
120847     pFirst = pSrc->pTab->pIndex;
120848     if( pSrc->notIndexed==0 ){
120849       /* The real indices of the table are only considered if the
120850       ** NOT INDEXED qualifier is omitted from the FROM clause */
120851       sPk.pNext = pFirst;
120852     }
120853     pProbe = &sPk;
120854   }
120855   rSize = pTab->nRowLogEst;
120856   rLogSize = estLog(rSize);
120857
120858 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
120859   /* Automatic indexes */
120860   if( !pBuilder->pOrSet
120861    && (pWInfo->wctrlFlags & WHERE_NO_AUTOINDEX)==0
120862    && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
120863    && pSrc->pIndex==0
120864    && !pSrc->viaCoroutine
120865    && !pSrc->notIndexed
120866    && HasRowid(pTab)
120867    && !pSrc->isCorrelated
120868    && !pSrc->isRecursive
120869   ){
120870     /* Generate auto-index WhereLoops */
120871     WhereTerm *pTerm;
120872     WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
120873     for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
120874       if( pTerm->prereqRight & pNew->maskSelf ) continue;
120875       if( termCanDriveIndex(pTerm, pSrc, 0) ){
120876         pNew->u.btree.nEq = 1;
120877         pNew->nSkip = 0;
120878         pNew->u.btree.pIndex = 0;
120879         pNew->nLTerm = 1;
120880         pNew->aLTerm[0] = pTerm;
120881         /* TUNING: One-time cost for computing the automatic index is
120882         ** estimated to be X*N*log2(N) where N is the number of rows in
120883         ** the table being indexed and where X is 7 (LogEst=28) for normal
120884         ** tables or 1.375 (LogEst=4) for views and subqueries.  The value
120885         ** of X is smaller for views and subqueries so that the query planner
120886         ** will be more aggressive about generating automatic indexes for
120887         ** those objects, since there is no opportunity to add schema
120888         ** indexes on subqueries and views. */
120889         pNew->rSetup = rLogSize + rSize + 4;
120890         if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
120891           pNew->rSetup += 24;
120892         }
120893         ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
120894         /* TUNING: Each index lookup yields 20 rows in the table.  This
120895         ** is more than the usual guess of 10 rows, since we have no way
120896         ** of knowing how selective the index will ultimately be.  It would
120897         ** not be unreasonable to make this value much larger. */
120898         pNew->nOut = 43;  assert( 43==sqlite3LogEst(20) );
120899         pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
120900         pNew->wsFlags = WHERE_AUTO_INDEX;
120901         pNew->prereq = mExtra | pTerm->prereqRight;
120902         rc = whereLoopInsert(pBuilder, pNew);
120903       }
120904     }
120905   }
120906 #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
120907
120908   /* Loop over all indices
120909   */
120910   for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
120911     if( pProbe->pPartIdxWhere!=0
120912      && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
120913       testcase( pNew->iTab!=pSrc->iCursor );  /* See ticket [98d973b8f5] */
120914       continue;  /* Partial index inappropriate for this query */
120915     }
120916     rSize = pProbe->aiRowLogEst[0];
120917     pNew->u.btree.nEq = 0;
120918     pNew->nSkip = 0;
120919     pNew->nLTerm = 0;
120920     pNew->iSortIdx = 0;
120921     pNew->rSetup = 0;
120922     pNew->prereq = mExtra;
120923     pNew->nOut = rSize;
120924     pNew->u.btree.pIndex = pProbe;
120925     b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
120926     /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
120927     assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
120928     if( pProbe->tnum<=0 ){
120929       /* Integer primary key index */
120930       pNew->wsFlags = WHERE_IPK;
120931
120932       /* Full table scan */
120933       pNew->iSortIdx = b ? iSortIdx : 0;
120934       /* TUNING: Cost of full table scan is (N*3.0). */
120935       pNew->rRun = rSize + 16;
120936       ApplyCostMultiplier(pNew->rRun, pTab->costMult);
120937       whereLoopOutputAdjust(pWC, pNew, rSize);
120938       rc = whereLoopInsert(pBuilder, pNew);
120939       pNew->nOut = rSize;
120940       if( rc ) break;
120941     }else{
120942       Bitmask m;
120943       if( pProbe->isCovering ){
120944         pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
120945         m = 0;
120946       }else{
120947         m = pSrc->colUsed & ~columnsInIndex(pProbe);
120948         pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
120949       }
120950
120951       /* Full scan via index */
120952       if( b
120953        || !HasRowid(pTab)
120954        || ( m==0
120955          && pProbe->bUnordered==0
120956          && (pProbe->szIdxRow<pTab->szTabRow)
120957          && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
120958          && sqlite3GlobalConfig.bUseCis
120959          && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
120960           )
120961       ){
120962         pNew->iSortIdx = b ? iSortIdx : 0;
120963
120964         /* The cost of visiting the index rows is N*K, where K is
120965         ** between 1.1 and 3.0, depending on the relative sizes of the
120966         ** index and table rows. If this is a non-covering index scan,
120967         ** also add the cost of visiting table rows (N*3.0).  */
120968         pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
120969         if( m!=0 ){
120970           pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
120971         }
120972         ApplyCostMultiplier(pNew->rRun, pTab->costMult);
120973         whereLoopOutputAdjust(pWC, pNew, rSize);
120974         rc = whereLoopInsert(pBuilder, pNew);
120975         pNew->nOut = rSize;
120976         if( rc ) break;
120977       }
120978     }
120979
120980     rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
120981 #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
120982     sqlite3Stat4ProbeFree(pBuilder->pRec);
120983     pBuilder->nRecValid = 0;
120984     pBuilder->pRec = 0;
120985 #endif
120986
120987     /* If there was an INDEXED BY clause, then only that one index is
120988     ** considered. */
120989     if( pSrc->pIndex ) break;
120990   }
120991   return rc;
120992 }
120993
120994 #ifndef SQLITE_OMIT_VIRTUALTABLE
120995 /*
120996 ** Add all WhereLoop objects for a table of the join identified by
120997 ** pBuilder->pNew->iTab.  That table is guaranteed to be a virtual table.
120998 */
120999 static int whereLoopAddVirtual(
121000   WhereLoopBuilder *pBuilder,  /* WHERE clause information */
121001   Bitmask mExtra
121002 ){
121003   WhereInfo *pWInfo;           /* WHERE analysis context */
121004   Parse *pParse;               /* The parsing context */
121005   WhereClause *pWC;            /* The WHERE clause */
121006   struct SrcList_item *pSrc;   /* The FROM clause term to search */
121007   Table *pTab;
121008   sqlite3 *db;
121009   sqlite3_index_info *pIdxInfo;
121010   struct sqlite3_index_constraint *pIdxCons;
121011   struct sqlite3_index_constraint_usage *pUsage;
121012   WhereTerm *pTerm;
121013   int i, j;
121014   int iTerm, mxTerm;
121015   int nConstraint;
121016   int seenIn = 0;              /* True if an IN operator is seen */
121017   int seenVar = 0;             /* True if a non-constant constraint is seen */
121018   int iPhase;                  /* 0: const w/o IN, 1: const, 2: no IN,  2: IN */
121019   WhereLoop *pNew;
121020   int rc = SQLITE_OK;
121021
121022   pWInfo = pBuilder->pWInfo;
121023   pParse = pWInfo->pParse;
121024   db = pParse->db;
121025   pWC = pBuilder->pWC;
121026   pNew = pBuilder->pNew;
121027   pSrc = &pWInfo->pTabList->a[pNew->iTab];
121028   pTab = pSrc->pTab;
121029   assert( IsVirtual(pTab) );
121030   pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
121031   if( pIdxInfo==0 ) return SQLITE_NOMEM;
121032   pNew->prereq = 0;
121033   pNew->rSetup = 0;
121034   pNew->wsFlags = WHERE_VIRTUALTABLE;
121035   pNew->nLTerm = 0;
121036   pNew->u.vtab.needFree = 0;
121037   pUsage = pIdxInfo->aConstraintUsage;
121038   nConstraint = pIdxInfo->nConstraint;
121039   if( whereLoopResize(db, pNew, nConstraint) ){
121040     sqlite3DbFree(db, pIdxInfo);
121041     return SQLITE_NOMEM;
121042   }
121043
121044   for(iPhase=0; iPhase<=3; iPhase++){
121045     if( !seenIn && (iPhase&1)!=0 ){
121046       iPhase++;
121047       if( iPhase>3 ) break;
121048     }
121049     if( !seenVar && iPhase>1 ) break;
121050     pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
121051     for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
121052       j = pIdxCons->iTermOffset;
121053       pTerm = &pWC->a[j];
121054       switch( iPhase ){
121055         case 0:    /* Constants without IN operator */
121056           pIdxCons->usable = 0;
121057           if( (pTerm->eOperator & WO_IN)!=0 ){
121058             seenIn = 1;
121059           }
121060           if( pTerm->prereqRight!=0 ){
121061             seenVar = 1;
121062           }else if( (pTerm->eOperator & WO_IN)==0 ){
121063             pIdxCons->usable = 1;
121064           }
121065           break;
121066         case 1:    /* Constants with IN operators */
121067           assert( seenIn );
121068           pIdxCons->usable = (pTerm->prereqRight==0);
121069           break;
121070         case 2:    /* Variables without IN */
121071           assert( seenVar );
121072           pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
121073           break;
121074         default:   /* Variables with IN */
121075           assert( seenVar && seenIn );
121076           pIdxCons->usable = 1;
121077           break;
121078       }
121079     }
121080     memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
121081     if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
121082     pIdxInfo->idxStr = 0;
121083     pIdxInfo->idxNum = 0;
121084     pIdxInfo->needToFreeIdxStr = 0;
121085     pIdxInfo->orderByConsumed = 0;
121086     pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
121087     pIdxInfo->estimatedRows = 25;
121088     rc = vtabBestIndex(pParse, pTab, pIdxInfo);
121089     if( rc ) goto whereLoopAddVtab_exit;
121090     pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
121091     pNew->prereq = mExtra;
121092     mxTerm = -1;
121093     assert( pNew->nLSlot>=nConstraint );
121094     for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
121095     pNew->u.vtab.omitMask = 0;
121096     for(i=0; i<nConstraint; i++, pIdxCons++){
121097       if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
121098         j = pIdxCons->iTermOffset;
121099         if( iTerm>=nConstraint
121100          || j<0
121101          || j>=pWC->nTerm
121102          || pNew->aLTerm[iTerm]!=0
121103         ){
121104           rc = SQLITE_ERROR;
121105           sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
121106           goto whereLoopAddVtab_exit;
121107         }
121108         testcase( iTerm==nConstraint-1 );
121109         testcase( j==0 );
121110         testcase( j==pWC->nTerm-1 );
121111         pTerm = &pWC->a[j];
121112         pNew->prereq |= pTerm->prereqRight;
121113         assert( iTerm<pNew->nLSlot );
121114         pNew->aLTerm[iTerm] = pTerm;
121115         if( iTerm>mxTerm ) mxTerm = iTerm;
121116         testcase( iTerm==15 );
121117         testcase( iTerm==16 );
121118         if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
121119         if( (pTerm->eOperator & WO_IN)!=0 ){
121120           if( pUsage[i].omit==0 ){
121121             /* Do not attempt to use an IN constraint if the virtual table
121122             ** says that the equivalent EQ constraint cannot be safely omitted.
121123             ** If we do attempt to use such a constraint, some rows might be
121124             ** repeated in the output. */
121125             break;
121126           }
121127           /* A virtual table that is constrained by an IN clause may not
121128           ** consume the ORDER BY clause because (1) the order of IN terms
121129           ** is not necessarily related to the order of output terms and
121130           ** (2) Multiple outputs from a single IN value will not merge
121131           ** together.  */
121132           pIdxInfo->orderByConsumed = 0;
121133         }
121134       }
121135     }
121136     if( i>=nConstraint ){
121137       pNew->nLTerm = mxTerm+1;
121138       assert( pNew->nLTerm<=pNew->nLSlot );
121139       pNew->u.vtab.idxNum = pIdxInfo->idxNum;
121140       pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
121141       pIdxInfo->needToFreeIdxStr = 0;
121142       pNew->u.vtab.idxStr = pIdxInfo->idxStr;
121143       pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
121144                                       pIdxInfo->nOrderBy : 0);
121145       pNew->rSetup = 0;
121146       pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
121147       pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
121148       whereLoopInsert(pBuilder, pNew);
121149       if( pNew->u.vtab.needFree ){
121150         sqlite3_free(pNew->u.vtab.idxStr);
121151         pNew->u.vtab.needFree = 0;
121152       }
121153     }
121154   }  
121155
121156 whereLoopAddVtab_exit:
121157   if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
121158   sqlite3DbFree(db, pIdxInfo);
121159   return rc;
121160 }
121161 #endif /* SQLITE_OMIT_VIRTUALTABLE */
121162
121163 /*
121164 ** Add WhereLoop entries to handle OR terms.  This works for either
121165 ** btrees or virtual tables.
121166 */
121167 static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
121168   WhereInfo *pWInfo = pBuilder->pWInfo;
121169   WhereClause *pWC;
121170   WhereLoop *pNew;
121171   WhereTerm *pTerm, *pWCEnd;
121172   int rc = SQLITE_OK;
121173   int iCur;
121174   WhereClause tempWC;
121175   WhereLoopBuilder sSubBuild;
121176   WhereOrSet sSum, sCur;
121177   struct SrcList_item *pItem;
121178   
121179   pWC = pBuilder->pWC;
121180   pWCEnd = pWC->a + pWC->nTerm;
121181   pNew = pBuilder->pNew;
121182   memset(&sSum, 0, sizeof(sSum));
121183   pItem = pWInfo->pTabList->a + pNew->iTab;
121184   iCur = pItem->iCursor;
121185
121186   for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
121187     if( (pTerm->eOperator & WO_OR)!=0
121188      && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0 
121189     ){
121190       WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
121191       WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
121192       WhereTerm *pOrTerm;
121193       int once = 1;
121194       int i, j;
121195     
121196       sSubBuild = *pBuilder;
121197       sSubBuild.pOrderBy = 0;
121198       sSubBuild.pOrSet = &sCur;
121199
121200       WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
121201       for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
121202         if( (pOrTerm->eOperator & WO_AND)!=0 ){
121203           sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
121204         }else if( pOrTerm->leftCursor==iCur ){
121205           tempWC.pWInfo = pWC->pWInfo;
121206           tempWC.pOuter = pWC;
121207           tempWC.op = TK_AND;
121208           tempWC.nTerm = 1;
121209           tempWC.a = pOrTerm;
121210           sSubBuild.pWC = &tempWC;
121211         }else{
121212           continue;
121213         }
121214         sCur.n = 0;
121215 #ifdef WHERETRACE_ENABLED
121216         WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n", 
121217                    (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
121218         if( sqlite3WhereTrace & 0x400 ){
121219           for(i=0; i<sSubBuild.pWC->nTerm; i++){
121220             whereTermPrint(&sSubBuild.pWC->a[i], i);
121221           }
121222         }
121223 #endif
121224 #ifndef SQLITE_OMIT_VIRTUALTABLE
121225         if( IsVirtual(pItem->pTab) ){
121226           rc = whereLoopAddVirtual(&sSubBuild, mExtra);
121227         }else
121228 #endif
121229         {
121230           rc = whereLoopAddBtree(&sSubBuild, mExtra);
121231         }
121232         if( rc==SQLITE_OK ){
121233           rc = whereLoopAddOr(&sSubBuild, mExtra);
121234         }
121235         assert( rc==SQLITE_OK || sCur.n==0 );
121236         if( sCur.n==0 ){
121237           sSum.n = 0;
121238           break;
121239         }else if( once ){
121240           whereOrMove(&sSum, &sCur);
121241           once = 0;
121242         }else{
121243           WhereOrSet sPrev;
121244           whereOrMove(&sPrev, &sSum);
121245           sSum.n = 0;
121246           for(i=0; i<sPrev.n; i++){
121247             for(j=0; j<sCur.n; j++){
121248               whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
121249                             sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
121250                             sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
121251             }
121252           }
121253         }
121254       }
121255       pNew->nLTerm = 1;
121256       pNew->aLTerm[0] = pTerm;
121257       pNew->wsFlags = WHERE_MULTI_OR;
121258       pNew->rSetup = 0;
121259       pNew->iSortIdx = 0;
121260       memset(&pNew->u, 0, sizeof(pNew->u));
121261       for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
121262         /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
121263         ** of all sub-scans required by the OR-scan. However, due to rounding
121264         ** errors, it may be that the cost of the OR-scan is equal to its
121265         ** most expensive sub-scan. Add the smallest possible penalty 
121266         ** (equivalent to multiplying the cost by 1.07) to ensure that 
121267         ** this does not happen. Otherwise, for WHERE clauses such as the
121268         ** following where there is an index on "y":
121269         **
121270         **     WHERE likelihood(x=?, 0.99) OR y=?
121271         **
121272         ** the planner may elect to "OR" together a full-table scan and an
121273         ** index lookup. And other similarly odd results.  */
121274         pNew->rRun = sSum.a[i].rRun + 1;
121275         pNew->nOut = sSum.a[i].nOut;
121276         pNew->prereq = sSum.a[i].prereq;
121277         rc = whereLoopInsert(pBuilder, pNew);
121278       }
121279       WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
121280     }
121281   }
121282   return rc;
121283 }
121284
121285 /*
121286 ** Add all WhereLoop objects for all tables 
121287 */
121288 static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
121289   WhereInfo *pWInfo = pBuilder->pWInfo;
121290   Bitmask mExtra = 0;
121291   Bitmask mPrior = 0;
121292   int iTab;
121293   SrcList *pTabList = pWInfo->pTabList;
121294   struct SrcList_item *pItem;
121295   sqlite3 *db = pWInfo->pParse->db;
121296   int nTabList = pWInfo->nLevel;
121297   int rc = SQLITE_OK;
121298   u8 priorJoinType = 0;
121299   WhereLoop *pNew;
121300
121301   /* Loop over the tables in the join, from left to right */
121302   pNew = pBuilder->pNew;
121303   whereLoopInit(pNew);
121304   for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
121305     pNew->iTab = iTab;
121306     pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
121307     if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
121308       mExtra = mPrior;
121309     }
121310     priorJoinType = pItem->jointype;
121311     if( IsVirtual(pItem->pTab) ){
121312       rc = whereLoopAddVirtual(pBuilder, mExtra);
121313     }else{
121314       rc = whereLoopAddBtree(pBuilder, mExtra);
121315     }
121316     if( rc==SQLITE_OK ){
121317       rc = whereLoopAddOr(pBuilder, mExtra);
121318     }
121319     mPrior |= pNew->maskSelf;
121320     if( rc || db->mallocFailed ) break;
121321   }
121322   whereLoopClear(db, pNew);
121323   return rc;
121324 }
121325
121326 /*
121327 ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
121328 ** parameters) to see if it outputs rows in the requested ORDER BY
121329 ** (or GROUP BY) without requiring a separate sort operation.  Return N:
121330 ** 
121331 **   N>0:   N terms of the ORDER BY clause are satisfied
121332 **   N==0:  No terms of the ORDER BY clause are satisfied
121333 **   N<0:   Unknown yet how many terms of ORDER BY might be satisfied.   
121334 **
121335 ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
121336 ** strict.  With GROUP BY and DISTINCT the only requirement is that
121337 ** equivalent rows appear immediately adjacent to one another.  GROUP BY
121338 ** and DISTINCT do not require rows to appear in any particular order as long
121339 ** as equivalent rows are grouped together.  Thus for GROUP BY and DISTINCT
121340 ** the pOrderBy terms can be matched in any order.  With ORDER BY, the 
121341 ** pOrderBy terms must be matched in strict left-to-right order.
121342 */
121343 static i8 wherePathSatisfiesOrderBy(
121344   WhereInfo *pWInfo,    /* The WHERE clause */
121345   ExprList *pOrderBy,   /* ORDER BY or GROUP BY or DISTINCT clause to check */
121346   WherePath *pPath,     /* The WherePath to check */
121347   u16 wctrlFlags,       /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
121348   u16 nLoop,            /* Number of entries in pPath->aLoop[] */
121349   WhereLoop *pLast,     /* Add this WhereLoop to the end of pPath->aLoop[] */
121350   Bitmask *pRevMask     /* OUT: Mask of WhereLoops to run in reverse order */
121351 ){
121352   u8 revSet;            /* True if rev is known */
121353   u8 rev;               /* Composite sort order */
121354   u8 revIdx;            /* Index sort order */
121355   u8 isOrderDistinct;   /* All prior WhereLoops are order-distinct */
121356   u8 distinctColumns;   /* True if the loop has UNIQUE NOT NULL columns */
121357   u8 isMatch;           /* iColumn matches a term of the ORDER BY clause */
121358   u16 nKeyCol;          /* Number of key columns in pIndex */
121359   u16 nColumn;          /* Total number of ordered columns in the index */
121360   u16 nOrderBy;         /* Number terms in the ORDER BY clause */
121361   int iLoop;            /* Index of WhereLoop in pPath being processed */
121362   int i, j;             /* Loop counters */
121363   int iCur;             /* Cursor number for current WhereLoop */
121364   int iColumn;          /* A column number within table iCur */
121365   WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
121366   WhereTerm *pTerm;     /* A single term of the WHERE clause */
121367   Expr *pOBExpr;        /* An expression from the ORDER BY clause */
121368   CollSeq *pColl;       /* COLLATE function from an ORDER BY clause term */
121369   Index *pIndex;        /* The index associated with pLoop */
121370   sqlite3 *db = pWInfo->pParse->db;  /* Database connection */
121371   Bitmask obSat = 0;    /* Mask of ORDER BY terms satisfied so far */
121372   Bitmask obDone;       /* Mask of all ORDER BY terms */
121373   Bitmask orderDistinctMask;  /* Mask of all well-ordered loops */
121374   Bitmask ready;              /* Mask of inner loops */
121375
121376   /*
121377   ** We say the WhereLoop is "one-row" if it generates no more than one
121378   ** row of output.  A WhereLoop is one-row if all of the following are true:
121379   **  (a) All index columns match with WHERE_COLUMN_EQ.
121380   **  (b) The index is unique
121381   ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
121382   ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
121383   **
121384   ** We say the WhereLoop is "order-distinct" if the set of columns from
121385   ** that WhereLoop that are in the ORDER BY clause are different for every
121386   ** row of the WhereLoop.  Every one-row WhereLoop is automatically
121387   ** order-distinct.   A WhereLoop that has no columns in the ORDER BY clause
121388   ** is not order-distinct. To be order-distinct is not quite the same as being
121389   ** UNIQUE since a UNIQUE column or index can have multiple rows that 
121390   ** are NULL and NULL values are equivalent for the purpose of order-distinct.
121391   ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
121392   **
121393   ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
121394   ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
121395   ** automatically order-distinct.
121396   */
121397
121398   assert( pOrderBy!=0 );
121399   if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
121400
121401   nOrderBy = pOrderBy->nExpr;
121402   testcase( nOrderBy==BMS-1 );
121403   if( nOrderBy>BMS-1 ) return 0;  /* Cannot optimize overly large ORDER BYs */
121404   isOrderDistinct = 1;
121405   obDone = MASKBIT(nOrderBy)-1;
121406   orderDistinctMask = 0;
121407   ready = 0;
121408   for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
121409     if( iLoop>0 ) ready |= pLoop->maskSelf;
121410     pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
121411     if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
121412       if( pLoop->u.vtab.isOrdered ) obSat = obDone;
121413       break;
121414     }
121415     iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
121416
121417     /* Mark off any ORDER BY term X that is a column in the table of
121418     ** the current loop for which there is term in the WHERE
121419     ** clause of the form X IS NULL or X=? that reference only outer
121420     ** loops.
121421     */
121422     for(i=0; i<nOrderBy; i++){
121423       if( MASKBIT(i) & obSat ) continue;
121424       pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
121425       if( pOBExpr->op!=TK_COLUMN ) continue;
121426       if( pOBExpr->iTable!=iCur ) continue;
121427       pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
121428                        ~ready, WO_EQ|WO_ISNULL, 0);
121429       if( pTerm==0 ) continue;
121430       if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
121431         const char *z1, *z2;
121432         pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
121433         if( !pColl ) pColl = db->pDfltColl;
121434         z1 = pColl->zName;
121435         pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
121436         if( !pColl ) pColl = db->pDfltColl;
121437         z2 = pColl->zName;
121438         if( sqlite3StrICmp(z1, z2)!=0 ) continue;
121439       }
121440       obSat |= MASKBIT(i);
121441     }
121442
121443     if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
121444       if( pLoop->wsFlags & WHERE_IPK ){
121445         pIndex = 0;
121446         nKeyCol = 0;
121447         nColumn = 1;
121448       }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
121449         return 0;
121450       }else{
121451         nKeyCol = pIndex->nKeyCol;
121452         nColumn = pIndex->nColumn;
121453         assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
121454         assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
121455         isOrderDistinct = IsUniqueIndex(pIndex);
121456       }
121457
121458       /* Loop through all columns of the index and deal with the ones
121459       ** that are not constrained by == or IN.
121460       */
121461       rev = revSet = 0;
121462       distinctColumns = 0;
121463       for(j=0; j<nColumn; j++){
121464         u8 bOnce;   /* True to run the ORDER BY search loop */
121465
121466         /* Skip over == and IS NULL terms */
121467         if( j<pLoop->u.btree.nEq
121468          && pLoop->nSkip==0
121469          && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
121470         ){
121471           if( i & WO_ISNULL ){
121472             testcase( isOrderDistinct );
121473             isOrderDistinct = 0;
121474           }
121475           continue;  
121476         }
121477
121478         /* Get the column number in the table (iColumn) and sort order
121479         ** (revIdx) for the j-th column of the index.
121480         */
121481         if( pIndex ){
121482           iColumn = pIndex->aiColumn[j];
121483           revIdx = pIndex->aSortOrder[j];
121484           if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
121485         }else{
121486           iColumn = -1;
121487           revIdx = 0;
121488         }
121489
121490         /* An unconstrained column that might be NULL means that this
121491         ** WhereLoop is not well-ordered
121492         */
121493         if( isOrderDistinct
121494          && iColumn>=0
121495          && j>=pLoop->u.btree.nEq
121496          && pIndex->pTable->aCol[iColumn].notNull==0
121497         ){
121498           isOrderDistinct = 0;
121499         }
121500
121501         /* Find the ORDER BY term that corresponds to the j-th column
121502         ** of the index and mark that ORDER BY term off 
121503         */
121504         bOnce = 1;
121505         isMatch = 0;
121506         for(i=0; bOnce && i<nOrderBy; i++){
121507           if( MASKBIT(i) & obSat ) continue;
121508           pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
121509           testcase( wctrlFlags & WHERE_GROUPBY );
121510           testcase( wctrlFlags & WHERE_DISTINCTBY );
121511           if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
121512           if( pOBExpr->op!=TK_COLUMN ) continue;
121513           if( pOBExpr->iTable!=iCur ) continue;
121514           if( pOBExpr->iColumn!=iColumn ) continue;
121515           if( iColumn>=0 ){
121516             pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
121517             if( !pColl ) pColl = db->pDfltColl;
121518             if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
121519           }
121520           isMatch = 1;
121521           break;
121522         }
121523         if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
121524           /* Make sure the sort order is compatible in an ORDER BY clause.
121525           ** Sort order is irrelevant for a GROUP BY clause. */
121526           if( revSet ){
121527             if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
121528           }else{
121529             rev = revIdx ^ pOrderBy->a[i].sortOrder;
121530             if( rev ) *pRevMask |= MASKBIT(iLoop);
121531             revSet = 1;
121532           }
121533         }
121534         if( isMatch ){
121535           if( iColumn<0 ){
121536             testcase( distinctColumns==0 );
121537             distinctColumns = 1;
121538           }
121539           obSat |= MASKBIT(i);
121540         }else{
121541           /* No match found */
121542           if( j==0 || j<nKeyCol ){
121543             testcase( isOrderDistinct!=0 );
121544             isOrderDistinct = 0;
121545           }
121546           break;
121547         }
121548       } /* end Loop over all index columns */
121549       if( distinctColumns ){
121550         testcase( isOrderDistinct==0 );
121551         isOrderDistinct = 1;
121552       }
121553     } /* end-if not one-row */
121554
121555     /* Mark off any other ORDER BY terms that reference pLoop */
121556     if( isOrderDistinct ){
121557       orderDistinctMask |= pLoop->maskSelf;
121558       for(i=0; i<nOrderBy; i++){
121559         Expr *p;
121560         Bitmask mTerm;
121561         if( MASKBIT(i) & obSat ) continue;
121562         p = pOrderBy->a[i].pExpr;
121563         mTerm = exprTableUsage(&pWInfo->sMaskSet,p);
121564         if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
121565         if( (mTerm&~orderDistinctMask)==0 ){
121566           obSat |= MASKBIT(i);
121567         }
121568       }
121569     }
121570   } /* End the loop over all WhereLoops from outer-most down to inner-most */
121571   if( obSat==obDone ) return (i8)nOrderBy;
121572   if( !isOrderDistinct ){
121573     for(i=nOrderBy-1; i>0; i--){
121574       Bitmask m = MASKBIT(i) - 1;
121575       if( (obSat&m)==m ) return i;
121576     }
121577     return 0;
121578   }
121579   return -1;
121580 }
121581
121582
121583 /*
121584 ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
121585 ** the planner assumes that the specified pOrderBy list is actually a GROUP
121586 ** BY clause - and so any order that groups rows as required satisfies the
121587 ** request.
121588 **
121589 ** Normally, in this case it is not possible for the caller to determine
121590 ** whether or not the rows are really being delivered in sorted order, or
121591 ** just in some other order that provides the required grouping. However,
121592 ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
121593 ** this function may be called on the returned WhereInfo object. It returns
121594 ** true if the rows really will be sorted in the specified order, or false
121595 ** otherwise.
121596 **
121597 ** For example, assuming:
121598 **
121599 **   CREATE INDEX i1 ON t1(x, Y);
121600 **
121601 ** then
121602 **
121603 **   SELECT * FROM t1 GROUP BY x,y ORDER BY x,y;   -- IsSorted()==1
121604 **   SELECT * FROM t1 GROUP BY y,x ORDER BY y,x;   -- IsSorted()==0
121605 */
121606 SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
121607   assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
121608   assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
121609   return pWInfo->sorted;
121610 }
121611
121612 #ifdef WHERETRACE_ENABLED
121613 /* For debugging use only: */
121614 static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
121615   static char zName[65];
121616   int i;
121617   for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
121618   if( pLast ) zName[i++] = pLast->cId;
121619   zName[i] = 0;
121620   return zName;
121621 }
121622 #endif
121623
121624 /*
121625 ** Return the cost of sorting nRow rows, assuming that the keys have 
121626 ** nOrderby columns and that the first nSorted columns are already in
121627 ** order.
121628 */
121629 static LogEst whereSortingCost(
121630   WhereInfo *pWInfo,
121631   LogEst nRow,
121632   int nOrderBy,
121633   int nSorted
121634 ){
121635   /* TUNING: Estimated cost of a full external sort, where N is 
121636   ** the number of rows to sort is:
121637   **
121638   **   cost = (3.0 * N * log(N)).
121639   ** 
121640   ** Or, if the order-by clause has X terms but only the last Y 
121641   ** terms are out of order, then block-sorting will reduce the 
121642   ** sorting cost to:
121643   **
121644   **   cost = (3.0 * N * log(N)) * (Y/X)
121645   **
121646   ** The (Y/X) term is implemented using stack variable rScale
121647   ** below.  */
121648   LogEst rScale, rSortCost;
121649   assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
121650   rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
121651   rSortCost = nRow + estLog(nRow) + rScale + 16;
121652
121653   /* TUNING: The cost of implementing DISTINCT using a B-TREE is
121654   ** similar but with a larger constant of proportionality. 
121655   ** Multiply by an additional factor of 3.0.  */
121656   if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
121657     rSortCost += 16;
121658   }
121659
121660   return rSortCost;
121661 }
121662
121663 /*
121664 ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
121665 ** attempts to find the lowest cost path that visits each WhereLoop
121666 ** once.  This path is then loaded into the pWInfo->a[].pWLoop fields.
121667 **
121668 ** Assume that the total number of output rows that will need to be sorted
121669 ** will be nRowEst (in the 10*log2 representation).  Or, ignore sorting
121670 ** costs if nRowEst==0.
121671 **
121672 ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
121673 ** error occurs.
121674 */
121675 static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
121676   int mxChoice;             /* Maximum number of simultaneous paths tracked */
121677   int nLoop;                /* Number of terms in the join */
121678   Parse *pParse;            /* Parsing context */
121679   sqlite3 *db;              /* The database connection */
121680   int iLoop;                /* Loop counter over the terms of the join */
121681   int ii, jj;               /* Loop counters */
121682   int mxI = 0;              /* Index of next entry to replace */
121683   int nOrderBy;             /* Number of ORDER BY clause terms */
121684   LogEst mxCost = 0;        /* Maximum cost of a set of paths */
121685   LogEst mxUnsorted = 0;    /* Maximum unsorted cost of a set of path */
121686   int nTo, nFrom;           /* Number of valid entries in aTo[] and aFrom[] */
121687   WherePath *aFrom;         /* All nFrom paths at the previous level */
121688   WherePath *aTo;           /* The nTo best paths at the current level */
121689   WherePath *pFrom;         /* An element of aFrom[] that we are working on */
121690   WherePath *pTo;           /* An element of aTo[] that we are working on */
121691   WhereLoop *pWLoop;        /* One of the WhereLoop objects */
121692   WhereLoop **pX;           /* Used to divy up the pSpace memory */
121693   LogEst *aSortCost = 0;    /* Sorting and partial sorting costs */
121694   char *pSpace;             /* Temporary memory used by this routine */
121695   int nSpace;               /* Bytes of space allocated at pSpace */
121696
121697   pParse = pWInfo->pParse;
121698   db = pParse->db;
121699   nLoop = pWInfo->nLevel;
121700   /* TUNING: For simple queries, only the best path is tracked.
121701   ** For 2-way joins, the 5 best paths are followed.
121702   ** For joins of 3 or more tables, track the 10 best paths */
121703   mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
121704   assert( nLoop<=pWInfo->pTabList->nSrc );
121705   WHERETRACE(0x002, ("---- begin solver.  (nRowEst=%d)\n", nRowEst));
121706
121707   /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
121708   ** case the purpose of this call is to estimate the number of rows returned
121709   ** by the overall query. Once this estimate has been obtained, the caller
121710   ** will invoke this function a second time, passing the estimate as the
121711   ** nRowEst parameter.  */
121712   if( pWInfo->pOrderBy==0 || nRowEst==0 ){
121713     nOrderBy = 0;
121714   }else{
121715     nOrderBy = pWInfo->pOrderBy->nExpr;
121716   }
121717
121718   /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
121719   nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
121720   nSpace += sizeof(LogEst) * nOrderBy;
121721   pSpace = sqlite3DbMallocRaw(db, nSpace);
121722   if( pSpace==0 ) return SQLITE_NOMEM;
121723   aTo = (WherePath*)pSpace;
121724   aFrom = aTo+mxChoice;
121725   memset(aFrom, 0, sizeof(aFrom[0]));
121726   pX = (WhereLoop**)(aFrom+mxChoice);
121727   for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
121728     pFrom->aLoop = pX;
121729   }
121730   if( nOrderBy ){
121731     /* If there is an ORDER BY clause and it is not being ignored, set up
121732     ** space for the aSortCost[] array. Each element of the aSortCost array
121733     ** is either zero - meaning it has not yet been initialized - or the
121734     ** cost of sorting nRowEst rows of data where the first X terms of
121735     ** the ORDER BY clause are already in order, where X is the array 
121736     ** index.  */
121737     aSortCost = (LogEst*)pX;
121738     memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
121739   }
121740   assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
121741   assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
121742
121743   /* Seed the search with a single WherePath containing zero WhereLoops.
121744   **
121745   ** TUNING: Do not let the number of iterations go above 28.  If the cost
121746   ** of computing an automatic index is not paid back within the first 28
121747   ** rows, then do not use the automatic index. */
121748   aFrom[0].nRow = MIN(pParse->nQueryLoop, 48);  assert( 48==sqlite3LogEst(28) );
121749   nFrom = 1;
121750   assert( aFrom[0].isOrdered==0 );
121751   if( nOrderBy ){
121752     /* If nLoop is zero, then there are no FROM terms in the query. Since
121753     ** in this case the query may return a maximum of one row, the results
121754     ** are already in the requested order. Set isOrdered to nOrderBy to
121755     ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
121756     ** -1, indicating that the result set may or may not be ordered, 
121757     ** depending on the loops added to the current plan.  */
121758     aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
121759   }
121760
121761   /* Compute successively longer WherePaths using the previous generation
121762   ** of WherePaths as the basis for the next.  Keep track of the mxChoice
121763   ** best paths at each generation */
121764   for(iLoop=0; iLoop<nLoop; iLoop++){
121765     nTo = 0;
121766     for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
121767       for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
121768         LogEst nOut;                      /* Rows visited by (pFrom+pWLoop) */
121769         LogEst rCost;                     /* Cost of path (pFrom+pWLoop) */
121770         LogEst rUnsorted;                 /* Unsorted cost of (pFrom+pWLoop) */
121771         i8 isOrdered = pFrom->isOrdered;  /* isOrdered for (pFrom+pWLoop) */
121772         Bitmask maskNew;                  /* Mask of src visited by (..) */
121773         Bitmask revMask = 0;              /* Mask of rev-order loops for (..) */
121774
121775         if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
121776         if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
121777         /* At this point, pWLoop is a candidate to be the next loop. 
121778         ** Compute its cost */
121779         rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
121780         rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
121781         nOut = pFrom->nRow + pWLoop->nOut;
121782         maskNew = pFrom->maskLoop | pWLoop->maskSelf;
121783         if( isOrdered<0 ){
121784           isOrdered = wherePathSatisfiesOrderBy(pWInfo,
121785                        pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
121786                        iLoop, pWLoop, &revMask);
121787         }else{
121788           revMask = pFrom->revLoop;
121789         }
121790         if( isOrdered>=0 && isOrdered<nOrderBy ){
121791           if( aSortCost[isOrdered]==0 ){
121792             aSortCost[isOrdered] = whereSortingCost(
121793                 pWInfo, nRowEst, nOrderBy, isOrdered
121794             );
121795           }
121796           rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
121797
121798           WHERETRACE(0x002,
121799               ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
121800                aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy, 
121801                rUnsorted, rCost));
121802         }else{
121803           rCost = rUnsorted;
121804         }
121805
121806         /* Check to see if pWLoop should be added to the set of
121807         ** mxChoice best-so-far paths.
121808         **
121809         ** First look for an existing path among best-so-far paths
121810         ** that covers the same set of loops and has the same isOrdered
121811         ** setting as the current path candidate.
121812         **
121813         ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
121814         ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
121815         ** of legal values for isOrdered, -1..64.
121816         */
121817         for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
121818           if( pTo->maskLoop==maskNew
121819            && ((pTo->isOrdered^isOrdered)&0x80)==0
121820           ){
121821             testcase( jj==nTo-1 );
121822             break;
121823           }
121824         }
121825         if( jj>=nTo ){
121826           /* None of the existing best-so-far paths match the candidate. */
121827           if( nTo>=mxChoice
121828            && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
121829           ){
121830             /* The current candidate is no better than any of the mxChoice
121831             ** paths currently in the best-so-far buffer.  So discard
121832             ** this candidate as not viable. */
121833 #ifdef WHERETRACE_ENABLED /* 0x4 */
121834             if( sqlite3WhereTrace&0x4 ){
121835               sqlite3DebugPrintf("Skip   %s cost=%-3d,%3d order=%c\n",
121836                   wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
121837                   isOrdered>=0 ? isOrdered+'0' : '?');
121838             }
121839 #endif
121840             continue;
121841           }
121842           /* If we reach this points it means that the new candidate path
121843           ** needs to be added to the set of best-so-far paths. */
121844           if( nTo<mxChoice ){
121845             /* Increase the size of the aTo set by one */
121846             jj = nTo++;
121847           }else{
121848             /* New path replaces the prior worst to keep count below mxChoice */
121849             jj = mxI;
121850           }
121851           pTo = &aTo[jj];
121852 #ifdef WHERETRACE_ENABLED /* 0x4 */
121853           if( sqlite3WhereTrace&0x4 ){
121854             sqlite3DebugPrintf("New    %s cost=%-3d,%3d order=%c\n",
121855                 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
121856                 isOrdered>=0 ? isOrdered+'0' : '?');
121857           }
121858 #endif
121859         }else{
121860           /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
121861           ** same set of loops and has the sam isOrdered setting as the
121862           ** candidate path.  Check to see if the candidate should replace
121863           ** pTo or if the candidate should be skipped */
121864           if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
121865 #ifdef WHERETRACE_ENABLED /* 0x4 */
121866             if( sqlite3WhereTrace&0x4 ){
121867               sqlite3DebugPrintf(
121868                   "Skip   %s cost=%-3d,%3d order=%c",
121869                   wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
121870                   isOrdered>=0 ? isOrdered+'0' : '?');
121871               sqlite3DebugPrintf("   vs %s cost=%-3d,%d order=%c\n",
121872                   wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
121873                   pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
121874             }
121875 #endif
121876             /* Discard the candidate path from further consideration */
121877             testcase( pTo->rCost==rCost );
121878             continue;
121879           }
121880           testcase( pTo->rCost==rCost+1 );
121881           /* Control reaches here if the candidate path is better than the
121882           ** pTo path.  Replace pTo with the candidate. */
121883 #ifdef WHERETRACE_ENABLED /* 0x4 */
121884           if( sqlite3WhereTrace&0x4 ){
121885             sqlite3DebugPrintf(
121886                 "Update %s cost=%-3d,%3d order=%c",
121887                 wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
121888                 isOrdered>=0 ? isOrdered+'0' : '?');
121889             sqlite3DebugPrintf("  was %s cost=%-3d,%3d order=%c\n",
121890                 wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
121891                 pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
121892           }
121893 #endif
121894         }
121895         /* pWLoop is a winner.  Add it to the set of best so far */
121896         pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
121897         pTo->revLoop = revMask;
121898         pTo->nRow = nOut;
121899         pTo->rCost = rCost;
121900         pTo->rUnsorted = rUnsorted;
121901         pTo->isOrdered = isOrdered;
121902         memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
121903         pTo->aLoop[iLoop] = pWLoop;
121904         if( nTo>=mxChoice ){
121905           mxI = 0;
121906           mxCost = aTo[0].rCost;
121907           mxUnsorted = aTo[0].nRow;
121908           for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
121909             if( pTo->rCost>mxCost 
121910              || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted) 
121911             ){
121912               mxCost = pTo->rCost;
121913               mxUnsorted = pTo->rUnsorted;
121914               mxI = jj;
121915             }
121916           }
121917         }
121918       }
121919     }
121920
121921 #ifdef WHERETRACE_ENABLED  /* >=2 */
121922     if( sqlite3WhereTrace & 0x02 ){
121923       sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
121924       for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
121925         sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
121926            wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
121927            pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
121928         if( pTo->isOrdered>0 ){
121929           sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
121930         }else{
121931           sqlite3DebugPrintf("\n");
121932         }
121933       }
121934     }
121935 #endif
121936
121937     /* Swap the roles of aFrom and aTo for the next generation */
121938     pFrom = aTo;
121939     aTo = aFrom;
121940     aFrom = pFrom;
121941     nFrom = nTo;
121942   }
121943
121944   if( nFrom==0 ){
121945     sqlite3ErrorMsg(pParse, "no query solution");
121946     sqlite3DbFree(db, pSpace);
121947     return SQLITE_ERROR;
121948   }
121949   
121950   /* Find the lowest cost path.  pFrom will be left pointing to that path */
121951   pFrom = aFrom;
121952   for(ii=1; ii<nFrom; ii++){
121953     if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
121954   }
121955   assert( pWInfo->nLevel==nLoop );
121956   /* Load the lowest cost path into pWInfo */
121957   for(iLoop=0; iLoop<nLoop; iLoop++){
121958     WhereLevel *pLevel = pWInfo->a + iLoop;
121959     pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
121960     pLevel->iFrom = pWLoop->iTab;
121961     pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
121962   }
121963   if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
121964    && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
121965    && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
121966    && nRowEst
121967   ){
121968     Bitmask notUsed;
121969     int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
121970                  WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
121971     if( rc==pWInfo->pResultSet->nExpr ){
121972       pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
121973     }
121974   }
121975   if( pWInfo->pOrderBy ){
121976     if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
121977       if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
121978         pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
121979       }
121980     }else{
121981       pWInfo->nOBSat = pFrom->isOrdered;
121982       if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
121983       pWInfo->revMask = pFrom->revLoop;
121984     }
121985     if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
121986         && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr
121987     ){
121988       Bitmask revMask = 0;
121989       int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy, 
121990           pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
121991       );
121992       assert( pWInfo->sorted==0 );
121993       if( nOrder==pWInfo->pOrderBy->nExpr ){
121994         pWInfo->sorted = 1;
121995         pWInfo->revMask = revMask;
121996       }
121997     }
121998   }
121999
122000
122001   pWInfo->nRowOut = pFrom->nRow;
122002
122003   /* Free temporary memory and return success */
122004   sqlite3DbFree(db, pSpace);
122005   return SQLITE_OK;
122006 }
122007
122008 /*
122009 ** Most queries use only a single table (they are not joins) and have
122010 ** simple == constraints against indexed fields.  This routine attempts
122011 ** to plan those simple cases using much less ceremony than the
122012 ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
122013 ** times for the common case.
122014 **
122015 ** Return non-zero on success, if this query can be handled by this
122016 ** no-frills query planner.  Return zero if this query needs the 
122017 ** general-purpose query planner.
122018 */
122019 static int whereShortCut(WhereLoopBuilder *pBuilder){
122020   WhereInfo *pWInfo;
122021   struct SrcList_item *pItem;
122022   WhereClause *pWC;
122023   WhereTerm *pTerm;
122024   WhereLoop *pLoop;
122025   int iCur;
122026   int j;
122027   Table *pTab;
122028   Index *pIdx;
122029   
122030   pWInfo = pBuilder->pWInfo;
122031   if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
122032   assert( pWInfo->pTabList->nSrc>=1 );
122033   pItem = pWInfo->pTabList->a;
122034   pTab = pItem->pTab;
122035   if( IsVirtual(pTab) ) return 0;
122036   if( pItem->zIndex ) return 0;
122037   iCur = pItem->iCursor;
122038   pWC = &pWInfo->sWC;
122039   pLoop = pBuilder->pNew;
122040   pLoop->wsFlags = 0;
122041   pLoop->nSkip = 0;
122042   pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
122043   if( pTerm ){
122044     pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
122045     pLoop->aLTerm[0] = pTerm;
122046     pLoop->nLTerm = 1;
122047     pLoop->u.btree.nEq = 1;
122048     /* TUNING: Cost of a rowid lookup is 10 */
122049     pLoop->rRun = 33;  /* 33==sqlite3LogEst(10) */
122050   }else{
122051     for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
122052       assert( pLoop->aLTermSpace==pLoop->aLTerm );
122053       if( !IsUniqueIndex(pIdx)
122054        || pIdx->pPartIdxWhere!=0 
122055        || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace) 
122056       ) continue;
122057       for(j=0; j<pIdx->nKeyCol; j++){
122058         pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
122059         if( pTerm==0 ) break;
122060         pLoop->aLTerm[j] = pTerm;
122061       }
122062       if( j!=pIdx->nKeyCol ) continue;
122063       pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
122064       if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
122065         pLoop->wsFlags |= WHERE_IDX_ONLY;
122066       }
122067       pLoop->nLTerm = j;
122068       pLoop->u.btree.nEq = j;
122069       pLoop->u.btree.pIndex = pIdx;
122070       /* TUNING: Cost of a unique index lookup is 15 */
122071       pLoop->rRun = 39;  /* 39==sqlite3LogEst(15) */
122072       break;
122073     }
122074   }
122075   if( pLoop->wsFlags ){
122076     pLoop->nOut = (LogEst)1;
122077     pWInfo->a[0].pWLoop = pLoop;
122078     pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
122079     pWInfo->a[0].iTabCur = iCur;
122080     pWInfo->nRowOut = 1;
122081     if( pWInfo->pOrderBy ) pWInfo->nOBSat =  pWInfo->pOrderBy->nExpr;
122082     if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
122083       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
122084     }
122085 #ifdef SQLITE_DEBUG
122086     pLoop->cId = '0';
122087 #endif
122088     return 1;
122089   }
122090   return 0;
122091 }
122092
122093 /*
122094 ** Generate the beginning of the loop used for WHERE clause processing.
122095 ** The return value is a pointer to an opaque structure that contains
122096 ** information needed to terminate the loop.  Later, the calling routine
122097 ** should invoke sqlite3WhereEnd() with the return value of this function
122098 ** in order to complete the WHERE clause processing.
122099 **
122100 ** If an error occurs, this routine returns NULL.
122101 **
122102 ** The basic idea is to do a nested loop, one loop for each table in
122103 ** the FROM clause of a select.  (INSERT and UPDATE statements are the
122104 ** same as a SELECT with only a single table in the FROM clause.)  For
122105 ** example, if the SQL is this:
122106 **
122107 **       SELECT * FROM t1, t2, t3 WHERE ...;
122108 **
122109 ** Then the code generated is conceptually like the following:
122110 **
122111 **      foreach row1 in t1 do       \    Code generated
122112 **        foreach row2 in t2 do      |-- by sqlite3WhereBegin()
122113 **          foreach row3 in t3 do   /
122114 **            ...
122115 **          end                     \    Code generated
122116 **        end                        |-- by sqlite3WhereEnd()
122117 **      end                         /
122118 **
122119 ** Note that the loops might not be nested in the order in which they
122120 ** appear in the FROM clause if a different order is better able to make
122121 ** use of indices.  Note also that when the IN operator appears in
122122 ** the WHERE clause, it might result in additional nested loops for
122123 ** scanning through all values on the right-hand side of the IN.
122124 **
122125 ** There are Btree cursors associated with each table.  t1 uses cursor
122126 ** number pTabList->a[0].iCursor.  t2 uses the cursor pTabList->a[1].iCursor.
122127 ** And so forth.  This routine generates code to open those VDBE cursors
122128 ** and sqlite3WhereEnd() generates the code to close them.
122129 **
122130 ** The code that sqlite3WhereBegin() generates leaves the cursors named
122131 ** in pTabList pointing at their appropriate entries.  The [...] code
122132 ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
122133 ** data from the various tables of the loop.
122134 **
122135 ** If the WHERE clause is empty, the foreach loops must each scan their
122136 ** entire tables.  Thus a three-way join is an O(N^3) operation.  But if
122137 ** the tables have indices and there are terms in the WHERE clause that
122138 ** refer to those indices, a complete table scan can be avoided and the
122139 ** code will run much faster.  Most of the work of this routine is checking
122140 ** to see if there are indices that can be used to speed up the loop.
122141 **
122142 ** Terms of the WHERE clause are also used to limit which rows actually
122143 ** make it to the "..." in the middle of the loop.  After each "foreach",
122144 ** terms of the WHERE clause that use only terms in that loop and outer
122145 ** loops are evaluated and if false a jump is made around all subsequent
122146 ** inner loops (or around the "..." if the test occurs within the inner-
122147 ** most loop)
122148 **
122149 ** OUTER JOINS
122150 **
122151 ** An outer join of tables t1 and t2 is conceptally coded as follows:
122152 **
122153 **    foreach row1 in t1 do
122154 **      flag = 0
122155 **      foreach row2 in t2 do
122156 **        start:
122157 **          ...
122158 **          flag = 1
122159 **      end
122160 **      if flag==0 then
122161 **        move the row2 cursor to a null row
122162 **        goto start
122163 **      fi
122164 **    end
122165 **
122166 ** ORDER BY CLAUSE PROCESSING
122167 **
122168 ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
122169 ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
122170 ** if there is one.  If there is no ORDER BY clause or if this routine
122171 ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
122172 **
122173 ** The iIdxCur parameter is the cursor number of an index.  If 
122174 ** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
122175 ** to use for OR clause processing.  The WHERE clause should use this
122176 ** specific cursor.  If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
122177 ** the first cursor in an array of cursors for all indices.  iIdxCur should
122178 ** be used to compute the appropriate cursor depending on which index is
122179 ** used.
122180 */
122181 SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
122182   Parse *pParse,        /* The parser context */
122183   SrcList *pTabList,    /* FROM clause: A list of all tables to be scanned */
122184   Expr *pWhere,         /* The WHERE clause */
122185   ExprList *pOrderBy,   /* An ORDER BY (or GROUP BY) clause, or NULL */
122186   ExprList *pResultSet, /* Result set of the query */
122187   u16 wctrlFlags,       /* One of the WHERE_* flags defined in sqliteInt.h */
122188   int iIdxCur           /* If WHERE_ONETABLE_ONLY is set, index cursor number */
122189 ){
122190   int nByteWInfo;            /* Num. bytes allocated for WhereInfo struct */
122191   int nTabList;              /* Number of elements in pTabList */
122192   WhereInfo *pWInfo;         /* Will become the return value of this function */
122193   Vdbe *v = pParse->pVdbe;   /* The virtual database engine */
122194   Bitmask notReady;          /* Cursors that are not yet positioned */
122195   WhereLoopBuilder sWLB;     /* The WhereLoop builder */
122196   WhereMaskSet *pMaskSet;    /* The expression mask set */
122197   WhereLevel *pLevel;        /* A single level in pWInfo->a[] */
122198   WhereLoop *pLoop;          /* Pointer to a single WhereLoop object */
122199   int ii;                    /* Loop counter */
122200   sqlite3 *db;               /* Database connection */
122201   int rc;                    /* Return code */
122202
122203
122204   /* Variable initialization */
122205   db = pParse->db;
122206   memset(&sWLB, 0, sizeof(sWLB));
122207
122208   /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
122209   testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
122210   if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
122211   sWLB.pOrderBy = pOrderBy;
122212
122213   /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
122214   ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
122215   if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
122216     wctrlFlags &= ~WHERE_WANT_DISTINCT;
122217   }
122218
122219   /* The number of tables in the FROM clause is limited by the number of
122220   ** bits in a Bitmask 
122221   */
122222   testcase( pTabList->nSrc==BMS );
122223   if( pTabList->nSrc>BMS ){
122224     sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
122225     return 0;
122226   }
122227
122228   /* This function normally generates a nested loop for all tables in 
122229   ** pTabList.  But if the WHERE_ONETABLE_ONLY flag is set, then we should
122230   ** only generate code for the first table in pTabList and assume that
122231   ** any cursors associated with subsequent tables are uninitialized.
122232   */
122233   nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
122234
122235   /* Allocate and initialize the WhereInfo structure that will become the
122236   ** return value. A single allocation is used to store the WhereInfo
122237   ** struct, the contents of WhereInfo.a[], the WhereClause structure
122238   ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
122239   ** field (type Bitmask) it must be aligned on an 8-byte boundary on
122240   ** some architectures. Hence the ROUND8() below.
122241   */
122242   nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
122243   pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
122244   if( db->mallocFailed ){
122245     sqlite3DbFree(db, pWInfo);
122246     pWInfo = 0;
122247     goto whereBeginError;
122248   }
122249   pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
122250   pWInfo->nLevel = nTabList;
122251   pWInfo->pParse = pParse;
122252   pWInfo->pTabList = pTabList;
122253   pWInfo->pOrderBy = pOrderBy;
122254   pWInfo->pResultSet = pResultSet;
122255   pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
122256   pWInfo->wctrlFlags = wctrlFlags;
122257   pWInfo->savedNQueryLoop = pParse->nQueryLoop;
122258   pMaskSet = &pWInfo->sMaskSet;
122259   sWLB.pWInfo = pWInfo;
122260   sWLB.pWC = &pWInfo->sWC;
122261   sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
122262   assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
122263   whereLoopInit(sWLB.pNew);
122264 #ifdef SQLITE_DEBUG
122265   sWLB.pNew->cId = '*';
122266 #endif
122267
122268   /* Split the WHERE clause into separate subexpressions where each
122269   ** subexpression is separated by an AND operator.
122270   */
122271   initMaskSet(pMaskSet);
122272   whereClauseInit(&pWInfo->sWC, pWInfo);
122273   whereSplit(&pWInfo->sWC, pWhere, TK_AND);
122274     
122275   /* Special case: a WHERE clause that is constant.  Evaluate the
122276   ** expression and either jump over all of the code or fall thru.
122277   */
122278   for(ii=0; ii<sWLB.pWC->nTerm; ii++){
122279     if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
122280       sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
122281                          SQLITE_JUMPIFNULL);
122282       sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
122283     }
122284   }
122285
122286   /* Special case: No FROM clause
122287   */
122288   if( nTabList==0 ){
122289     if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
122290     if( wctrlFlags & WHERE_WANT_DISTINCT ){
122291       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
122292     }
122293   }
122294
122295   /* Assign a bit from the bitmask to every term in the FROM clause.
122296   **
122297   ** When assigning bitmask values to FROM clause cursors, it must be
122298   ** the case that if X is the bitmask for the N-th FROM clause term then
122299   ** the bitmask for all FROM clause terms to the left of the N-th term
122300   ** is (X-1).   An expression from the ON clause of a LEFT JOIN can use
122301   ** its Expr.iRightJoinTable value to find the bitmask of the right table
122302   ** of the join.  Subtracting one from the right table bitmask gives a
122303   ** bitmask for all tables to the left of the join.  Knowing the bitmask
122304   ** for all tables to the left of a left join is important.  Ticket #3015.
122305   **
122306   ** Note that bitmasks are created for all pTabList->nSrc tables in
122307   ** pTabList, not just the first nTabList tables.  nTabList is normally
122308   ** equal to pTabList->nSrc but might be shortened to 1 if the
122309   ** WHERE_ONETABLE_ONLY flag is set.
122310   */
122311   for(ii=0; ii<pTabList->nSrc; ii++){
122312     createMask(pMaskSet, pTabList->a[ii].iCursor);
122313   }
122314 #ifndef NDEBUG
122315   {
122316     Bitmask toTheLeft = 0;
122317     for(ii=0; ii<pTabList->nSrc; ii++){
122318       Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
122319       assert( (m-1)==toTheLeft );
122320       toTheLeft |= m;
122321     }
122322   }
122323 #endif
122324
122325   /* Analyze all of the subexpressions.  Note that exprAnalyze() might
122326   ** add new virtual terms onto the end of the WHERE clause.  We do not
122327   ** want to analyze these virtual terms, so start analyzing at the end
122328   ** and work forward so that the added virtual terms are never processed.
122329   */
122330   exprAnalyzeAll(pTabList, &pWInfo->sWC);
122331   if( db->mallocFailed ){
122332     goto whereBeginError;
122333   }
122334
122335   if( wctrlFlags & WHERE_WANT_DISTINCT ){
122336     if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
122337       /* The DISTINCT marking is pointless.  Ignore it. */
122338       pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
122339     }else if( pOrderBy==0 ){
122340       /* Try to ORDER BY the result set to make distinct processing easier */
122341       pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
122342       pWInfo->pOrderBy = pResultSet;
122343     }
122344   }
122345
122346   /* Construct the WhereLoop objects */
122347   WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
122348 #if defined(WHERETRACE_ENABLED)
122349   /* Display all terms of the WHERE clause */
122350   if( sqlite3WhereTrace & 0x100 ){
122351     int i;
122352     for(i=0; i<sWLB.pWC->nTerm; i++){
122353       whereTermPrint(&sWLB.pWC->a[i], i);
122354     }
122355   }
122356 #endif
122357
122358   if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
122359     rc = whereLoopAddAll(&sWLB);
122360     if( rc ) goto whereBeginError;
122361   
122362     /* Display all of the WhereLoop objects if wheretrace is enabled */
122363 #ifdef WHERETRACE_ENABLED /* !=0 */
122364     if( sqlite3WhereTrace ){
122365       WhereLoop *p;
122366       int i;
122367       static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
122368                                        "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
122369       for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
122370         p->cId = zLabel[i%sizeof(zLabel)];
122371         whereLoopPrint(p, sWLB.pWC);
122372       }
122373     }
122374 #endif
122375   
122376     wherePathSolver(pWInfo, 0);
122377     if( db->mallocFailed ) goto whereBeginError;
122378     if( pWInfo->pOrderBy ){
122379        wherePathSolver(pWInfo, pWInfo->nRowOut+1);
122380        if( db->mallocFailed ) goto whereBeginError;
122381     }
122382   }
122383   if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
122384      pWInfo->revMask = (Bitmask)(-1);
122385   }
122386   if( pParse->nErr || NEVER(db->mallocFailed) ){
122387     goto whereBeginError;
122388   }
122389 #ifdef WHERETRACE_ENABLED /* !=0 */
122390   if( sqlite3WhereTrace ){
122391     int ii;
122392     sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
122393     if( pWInfo->nOBSat>0 ){
122394       sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
122395     }
122396     switch( pWInfo->eDistinct ){
122397       case WHERE_DISTINCT_UNIQUE: {
122398         sqlite3DebugPrintf("  DISTINCT=unique");
122399         break;
122400       }
122401       case WHERE_DISTINCT_ORDERED: {
122402         sqlite3DebugPrintf("  DISTINCT=ordered");
122403         break;
122404       }
122405       case WHERE_DISTINCT_UNORDERED: {
122406         sqlite3DebugPrintf("  DISTINCT=unordered");
122407         break;
122408       }
122409     }
122410     sqlite3DebugPrintf("\n");
122411     for(ii=0; ii<pWInfo->nLevel; ii++){
122412       whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
122413     }
122414   }
122415 #endif
122416   /* Attempt to omit tables from the join that do not effect the result */
122417   if( pWInfo->nLevel>=2
122418    && pResultSet!=0
122419    && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
122420   ){
122421     Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
122422     if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
122423     while( pWInfo->nLevel>=2 ){
122424       WhereTerm *pTerm, *pEnd;
122425       pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
122426       if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
122427       if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
122428        && (pLoop->wsFlags & WHERE_ONEROW)==0
122429       ){
122430         break;
122431       }
122432       if( (tabUsed & pLoop->maskSelf)!=0 ) break;
122433       pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
122434       for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
122435         if( (pTerm->prereqAll & pLoop->maskSelf)!=0
122436          && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
122437         ){
122438           break;
122439         }
122440       }
122441       if( pTerm<pEnd ) break;
122442       WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
122443       pWInfo->nLevel--;
122444       nTabList--;
122445     }
122446   }
122447   WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
122448   pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
122449
122450   /* If the caller is an UPDATE or DELETE statement that is requesting
122451   ** to use a one-pass algorithm, determine if this is appropriate.
122452   ** The one-pass algorithm only works if the WHERE clause constrains
122453   ** the statement to update a single row.
122454   */
122455   assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
122456   if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0 
122457    && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
122458     pWInfo->okOnePass = 1;
122459     if( HasRowid(pTabList->a[0].pTab) ){
122460       pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
122461     }
122462   }
122463
122464   /* Open all tables in the pTabList and any indices selected for
122465   ** searching those tables.
122466   */
122467   notReady = ~(Bitmask)0;
122468   for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
122469     Table *pTab;     /* Table to open */
122470     int iDb;         /* Index of database containing table/index */
122471     struct SrcList_item *pTabItem;
122472
122473     pTabItem = &pTabList->a[pLevel->iFrom];
122474     pTab = pTabItem->pTab;
122475     iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
122476     pLoop = pLevel->pWLoop;
122477     if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
122478       /* Do nothing */
122479     }else
122480 #ifndef SQLITE_OMIT_VIRTUALTABLE
122481     if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
122482       const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
122483       int iCur = pTabItem->iCursor;
122484       sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
122485     }else if( IsVirtual(pTab) ){
122486       /* noop */
122487     }else
122488 #endif
122489     if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
122490          && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
122491       int op = OP_OpenRead;
122492       if( pWInfo->okOnePass ){
122493         op = OP_OpenWrite;
122494         pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
122495       };
122496       sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
122497       assert( pTabItem->iCursor==pLevel->iTabCur );
122498       testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
122499       testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
122500       if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
122501         Bitmask b = pTabItem->colUsed;
122502         int n = 0;
122503         for(; b; b=b>>1, n++){}
122504         sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1, 
122505                             SQLITE_INT_TO_PTR(n), P4_INT32);
122506         assert( n<=pTab->nCol );
122507       }
122508     }else{
122509       sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
122510     }
122511     if( pLoop->wsFlags & WHERE_INDEXED ){
122512       Index *pIx = pLoop->u.btree.pIndex;
122513       int iIndexCur;
122514       int op = OP_OpenRead;
122515       /* iIdxCur is always set if to a positive value if ONEPASS is possible */
122516       assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
122517       if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
122518        && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
122519       ){
122520         /* This is one term of an OR-optimization using the PRIMARY KEY of a
122521         ** WITHOUT ROWID table.  No need for a separate index */
122522         iIndexCur = pLevel->iTabCur;
122523         op = 0;
122524       }else if( pWInfo->okOnePass ){
122525         Index *pJ = pTabItem->pTab->pIndex;
122526         iIndexCur = iIdxCur;
122527         assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
122528         while( ALWAYS(pJ) && pJ!=pIx ){
122529           iIndexCur++;
122530           pJ = pJ->pNext;
122531         }
122532         op = OP_OpenWrite;
122533         pWInfo->aiCurOnePass[1] = iIndexCur;
122534       }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
122535         iIndexCur = iIdxCur;
122536         if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx;
122537       }else{
122538         iIndexCur = pParse->nTab++;
122539       }
122540       pLevel->iIdxCur = iIndexCur;
122541       assert( pIx->pSchema==pTab->pSchema );
122542       assert( iIndexCur>=0 );
122543       if( op ){
122544         sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
122545         sqlite3VdbeSetP4KeyInfo(pParse, pIx);
122546         if( (pLoop->wsFlags & WHERE_CONSTRAINT)!=0
122547          && (pLoop->wsFlags & (WHERE_COLUMN_RANGE|WHERE_SKIPSCAN))==0
122548          && (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0
122549         ){
122550           sqlite3VdbeChangeP5(v, OPFLAG_SEEKEQ); /* Hint to COMDB2 */
122551         }
122552         VdbeComment((v, "%s", pIx->zName));
122553       }
122554     }
122555     if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
122556     notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
122557   }
122558   pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
122559   if( db->mallocFailed ) goto whereBeginError;
122560
122561   /* Generate the code to do the search.  Each iteration of the for
122562   ** loop below generates code for a single nested loop of the VM
122563   ** program.
122564   */
122565   notReady = ~(Bitmask)0;
122566   for(ii=0; ii<nTabList; ii++){
122567     int addrExplain;
122568     int wsFlags;
122569     pLevel = &pWInfo->a[ii];
122570     wsFlags = pLevel->pWLoop->wsFlags;
122571 #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
122572     if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
122573       constructAutomaticIndex(pParse, &pWInfo->sWC,
122574                 &pTabList->a[pLevel->iFrom], notReady, pLevel);
122575       if( db->mallocFailed ) goto whereBeginError;
122576     }
122577 #endif
122578     addrExplain = explainOneScan(
122579         pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags
122580     );
122581     pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
122582     notReady = codeOneLoopStart(pWInfo, ii, notReady);
122583     pWInfo->iContinue = pLevel->addrCont;
122584     if( (wsFlags&WHERE_MULTI_OR)==0 && (wctrlFlags&WHERE_ONETABLE_ONLY)==0 ){
122585       addScanStatus(v, pTabList, pLevel, addrExplain);
122586     }
122587   }
122588
122589   /* Done. */
122590   VdbeModuleComment((v, "Begin WHERE-core"));
122591   return pWInfo;
122592
122593   /* Jump here if malloc fails */
122594 whereBeginError:
122595   if( pWInfo ){
122596     pParse->nQueryLoop = pWInfo->savedNQueryLoop;
122597     whereInfoFree(db, pWInfo);
122598   }
122599   return 0;
122600 }
122601
122602 /*
122603 ** Generate the end of the WHERE loop.  See comments on 
122604 ** sqlite3WhereBegin() for additional information.
122605 */
122606 SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
122607   Parse *pParse = pWInfo->pParse;
122608   Vdbe *v = pParse->pVdbe;
122609   int i;
122610   WhereLevel *pLevel;
122611   WhereLoop *pLoop;
122612   SrcList *pTabList = pWInfo->pTabList;
122613   sqlite3 *db = pParse->db;
122614
122615   /* Generate loop termination code.
122616   */
122617   VdbeModuleComment((v, "End WHERE-core"));
122618   sqlite3ExprCacheClear(pParse);
122619   for(i=pWInfo->nLevel-1; i>=0; i--){
122620     int addr;
122621     pLevel = &pWInfo->a[i];
122622     pLoop = pLevel->pWLoop;
122623     sqlite3VdbeResolveLabel(v, pLevel->addrCont);
122624     if( pLevel->op!=OP_Noop ){
122625       sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
122626       sqlite3VdbeChangeP5(v, pLevel->p5);
122627       VdbeCoverage(v);
122628       VdbeCoverageIf(v, pLevel->op==OP_Next);
122629       VdbeCoverageIf(v, pLevel->op==OP_Prev);
122630       VdbeCoverageIf(v, pLevel->op==OP_VNext);
122631     }
122632     if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
122633       struct InLoop *pIn;
122634       int j;
122635       sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
122636       for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
122637         sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
122638         sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
122639         VdbeCoverage(v);
122640         VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
122641         VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
122642         sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
122643       }
122644       sqlite3DbFree(db, pLevel->u.in.aInLoop);
122645     }
122646     sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
122647     if( pLevel->addrSkip ){
122648       sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
122649       VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
122650       sqlite3VdbeJumpHere(v, pLevel->addrSkip);
122651       sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
122652     }
122653     if( pLevel->addrLikeRep ){
122654       int op;
122655       if( sqlite3VdbeGetOp(v, pLevel->addrLikeRep-1)->p1 ){
122656         op = OP_DecrJumpZero;
122657       }else{
122658         op = OP_JumpZeroIncr;
122659       }
122660       sqlite3VdbeAddOp2(v, op, pLevel->iLikeRepCntr, pLevel->addrLikeRep);
122661       VdbeCoverage(v);
122662     }
122663     if( pLevel->iLeftJoin ){
122664       addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
122665       assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
122666            || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
122667       if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
122668         sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
122669       }
122670       if( pLoop->wsFlags & WHERE_INDEXED ){
122671         sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
122672       }
122673       if( pLevel->op==OP_Return ){
122674         sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
122675       }else{
122676         sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
122677       }
122678       sqlite3VdbeJumpHere(v, addr);
122679     }
122680     VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
122681                      pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
122682   }
122683
122684   /* The "break" point is here, just past the end of the outer loop.
122685   ** Set it.
122686   */
122687   sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
122688
122689   assert( pWInfo->nLevel<=pTabList->nSrc );
122690   for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
122691     int k, last;
122692     VdbeOp *pOp;
122693     Index *pIdx = 0;
122694     struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
122695     Table *pTab = pTabItem->pTab;
122696     assert( pTab!=0 );
122697     pLoop = pLevel->pWLoop;
122698
122699     /* For a co-routine, change all OP_Column references to the table of
122700     ** the co-routine into OP_SCopy of result contained in a register.
122701     ** OP_Rowid becomes OP_Null.
122702     */
122703     if( pTabItem->viaCoroutine && !db->mallocFailed ){
122704       last = sqlite3VdbeCurrentAddr(v);
122705       k = pLevel->addrBody;
122706       pOp = sqlite3VdbeGetOp(v, k);
122707       for(; k<last; k++, pOp++){
122708         if( pOp->p1!=pLevel->iTabCur ) continue;
122709         if( pOp->opcode==OP_Column ){
122710           pOp->opcode = OP_Copy;
122711           pOp->p1 = pOp->p2 + pTabItem->regResult;
122712           pOp->p2 = pOp->p3;
122713           pOp->p3 = 0;
122714         }else if( pOp->opcode==OP_Rowid ){
122715           pOp->opcode = OP_Null;
122716           pOp->p1 = 0;
122717           pOp->p3 = 0;
122718         }
122719       }
122720       continue;
122721     }
122722
122723     /* Close all of the cursors that were opened by sqlite3WhereBegin.
122724     ** Except, do not close cursors that will be reused by the OR optimization
122725     ** (WHERE_OMIT_OPEN_CLOSE).  And do not close the OP_OpenWrite cursors
122726     ** created for the ONEPASS optimization.
122727     */
122728     if( (pTab->tabFlags & TF_Ephemeral)==0
122729      && pTab->pSelect==0
122730      && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
122731     ){
122732       int ws = pLoop->wsFlags;
122733       if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
122734         sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
122735       }
122736       if( (ws & WHERE_INDEXED)!=0
122737        && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0 
122738        && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
122739       ){
122740         sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
122741       }
122742     }
122743
122744     /* If this scan uses an index, make VDBE code substitutions to read data
122745     ** from the index instead of from the table where possible.  In some cases
122746     ** this optimization prevents the table from ever being read, which can
122747     ** yield a significant performance boost.
122748     ** 
122749     ** Calls to the code generator in between sqlite3WhereBegin and
122750     ** sqlite3WhereEnd will have created code that references the table
122751     ** directly.  This loop scans all that code looking for opcodes
122752     ** that reference the table and converts them into opcodes that
122753     ** reference the index.
122754     */
122755     if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
122756       pIdx = pLoop->u.btree.pIndex;
122757     }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
122758       pIdx = pLevel->u.pCovidx;
122759     }
122760     if( pIdx && !db->mallocFailed ){
122761       last = sqlite3VdbeCurrentAddr(v);
122762       k = pLevel->addrBody;
122763       pOp = sqlite3VdbeGetOp(v, k);
122764       for(; k<last; k++, pOp++){
122765         if( pOp->p1!=pLevel->iTabCur ) continue;
122766         if( pOp->opcode==OP_Column ){
122767           int x = pOp->p2;
122768           assert( pIdx->pTable==pTab );
122769           if( !HasRowid(pTab) ){
122770             Index *pPk = sqlite3PrimaryKeyIndex(pTab);
122771             x = pPk->aiColumn[x];
122772           }
122773           x = sqlite3ColumnOfIndex(pIdx, x);
122774           if( x>=0 ){
122775             pOp->p2 = x;
122776             pOp->p1 = pLevel->iIdxCur;
122777           }
122778           assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
122779         }else if( pOp->opcode==OP_Rowid ){
122780           pOp->p1 = pLevel->iIdxCur;
122781           pOp->opcode = OP_IdxRowid;
122782         }
122783       }
122784     }
122785   }
122786
122787   /* Final cleanup
122788   */
122789   pParse->nQueryLoop = pWInfo->savedNQueryLoop;
122790   whereInfoFree(db, pWInfo);
122791   return;
122792 }
122793
122794 /************** End of where.c ***********************************************/
122795 /************** Begin file parse.c *******************************************/
122796 /* Driver template for the LEMON parser generator.
122797 ** The author disclaims copyright to this source code.
122798 **
122799 ** This version of "lempar.c" is modified, slightly, for use by SQLite.
122800 ** The only modifications are the addition of a couple of NEVER()
122801 ** macros to disable tests that are needed in the case of a general
122802 ** LALR(1) grammar but which are always false in the
122803 ** specific grammar used by SQLite.
122804 */
122805 /* First off, code is included that follows the "include" declaration
122806 ** in the input grammar file. */
122807 /* #include <stdio.h> */
122808
122809
122810 /*
122811 ** Disable all error recovery processing in the parser push-down
122812 ** automaton.
122813 */
122814 #define YYNOERRORRECOVERY 1
122815
122816 /*
122817 ** Make yytestcase() the same as testcase()
122818 */
122819 #define yytestcase(X) testcase(X)
122820
122821 /*
122822 ** An instance of this structure holds information about the
122823 ** LIMIT clause of a SELECT statement.
122824 */
122825 struct LimitVal {
122826   Expr *pLimit;    /* The LIMIT expression.  NULL if there is no limit */
122827   Expr *pOffset;   /* The OFFSET expression.  NULL if there is none */
122828 };
122829
122830 /*
122831 ** An instance of this structure is used to store the LIKE,
122832 ** GLOB, NOT LIKE, and NOT GLOB operators.
122833 */
122834 struct LikeOp {
122835   Token eOperator;  /* "like" or "glob" or "regexp" */
122836   int bNot;         /* True if the NOT keyword is present */
122837 };
122838
122839 /*
122840 ** An instance of the following structure describes the event of a
122841 ** TRIGGER.  "a" is the event type, one of TK_UPDATE, TK_INSERT,
122842 ** TK_DELETE, or TK_INSTEAD.  If the event is of the form
122843 **
122844 **      UPDATE ON (a,b,c)
122845 **
122846 ** Then the "b" IdList records the list "a,b,c".
122847 */
122848 struct TrigEvent { int a; IdList * b; };
122849
122850 /*
122851 ** An instance of this structure holds the ATTACH key and the key type.
122852 */
122853 struct AttachKey { int type;  Token key; };
122854
122855
122856   /* This is a utility routine used to set the ExprSpan.zStart and
122857   ** ExprSpan.zEnd values of pOut so that the span covers the complete
122858   ** range of text beginning with pStart and going to the end of pEnd.
122859   */
122860   static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
122861     pOut->zStart = pStart->z;
122862     pOut->zEnd = &pEnd->z[pEnd->n];
122863   }
122864
122865   /* Construct a new Expr object from a single identifier.  Use the
122866   ** new Expr to populate pOut.  Set the span of pOut to be the identifier
122867   ** that created the expression.
122868   */
122869   static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
122870     pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
122871     pOut->zStart = pValue->z;
122872     pOut->zEnd = &pValue->z[pValue->n];
122873   }
122874
122875   /* This routine constructs a binary expression node out of two ExprSpan
122876   ** objects and uses the result to populate a new ExprSpan object.
122877   */
122878   static void spanBinaryExpr(
122879     ExprSpan *pOut,     /* Write the result here */
122880     Parse *pParse,      /* The parsing context.  Errors accumulate here */
122881     int op,             /* The binary operation */
122882     ExprSpan *pLeft,    /* The left operand */
122883     ExprSpan *pRight    /* The right operand */
122884   ){
122885     pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
122886     pOut->zStart = pLeft->zStart;
122887     pOut->zEnd = pRight->zEnd;
122888   }
122889
122890   /* Construct an expression node for a unary postfix operator
122891   */
122892   static void spanUnaryPostfix(
122893     ExprSpan *pOut,        /* Write the new expression node here */
122894     Parse *pParse,         /* Parsing context to record errors */
122895     int op,                /* The operator */
122896     ExprSpan *pOperand,    /* The operand */
122897     Token *pPostOp         /* The operand token for setting the span */
122898   ){
122899     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
122900     pOut->zStart = pOperand->zStart;
122901     pOut->zEnd = &pPostOp->z[pPostOp->n];
122902   }                           
122903
122904   /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
122905   ** unary TK_ISNULL or TK_NOTNULL expression. */
122906   static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
122907     sqlite3 *db = pParse->db;
122908     if( pY && pA && pY->op==TK_NULL ){
122909       pA->op = (u8)op;
122910       sqlite3ExprDelete(db, pA->pRight);
122911       pA->pRight = 0;
122912     }
122913   }
122914
122915   /* Construct an expression node for a unary prefix operator
122916   */
122917   static void spanUnaryPrefix(
122918     ExprSpan *pOut,        /* Write the new expression node here */
122919     Parse *pParse,         /* Parsing context to record errors */
122920     int op,                /* The operator */
122921     ExprSpan *pOperand,    /* The operand */
122922     Token *pPreOp         /* The operand token for setting the span */
122923   ){
122924     pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
122925     pOut->zStart = pPreOp->z;
122926     pOut->zEnd = pOperand->zEnd;
122927   }
122928 /* Next is all token values, in a form suitable for use by makeheaders.
122929 ** This section will be null unless lemon is run with the -m switch.
122930 */
122931 /* 
122932 ** These constants (all generated automatically by the parser generator)
122933 ** specify the various kinds of tokens (terminals) that the parser
122934 ** understands. 
122935 **
122936 ** Each symbol here is a terminal symbol in the grammar.
122937 */
122938 /* Make sure the INTERFACE macro is defined.
122939 */
122940 #ifndef INTERFACE
122941 # define INTERFACE 1
122942 #endif
122943 /* The next thing included is series of defines which control
122944 ** various aspects of the generated parser.
122945 **    YYCODETYPE         is the data type used for storing terminal
122946 **                       and nonterminal numbers.  "unsigned char" is
122947 **                       used if there are fewer than 250 terminals
122948 **                       and nonterminals.  "int" is used otherwise.
122949 **    YYNOCODE           is a number of type YYCODETYPE which corresponds
122950 **                       to no legal terminal or nonterminal number.  This
122951 **                       number is used to fill in empty slots of the hash 
122952 **                       table.
122953 **    YYFALLBACK         If defined, this indicates that one or more tokens
122954 **                       have fall-back values which should be used if the
122955 **                       original value of the token will not parse.
122956 **    YYACTIONTYPE       is the data type used for storing terminal
122957 **                       and nonterminal numbers.  "unsigned char" is
122958 **                       used if there are fewer than 250 rules and
122959 **                       states combined.  "int" is used otherwise.
122960 **    sqlite3ParserTOKENTYPE     is the data type used for minor tokens given 
122961 **                       directly to the parser from the tokenizer.
122962 **    YYMINORTYPE        is the data type used for all minor tokens.
122963 **                       This is typically a union of many types, one of
122964 **                       which is sqlite3ParserTOKENTYPE.  The entry in the union
122965 **                       for base tokens is called "yy0".
122966 **    YYSTACKDEPTH       is the maximum depth of the parser's stack.  If
122967 **                       zero the stack is dynamically sized using realloc()
122968 **    sqlite3ParserARG_SDECL     A static variable declaration for the %extra_argument
122969 **    sqlite3ParserARG_PDECL     A parameter declaration for the %extra_argument
122970 **    sqlite3ParserARG_STORE     Code to store %extra_argument into yypParser
122971 **    sqlite3ParserARG_FETCH     Code to extract %extra_argument from yypParser
122972 **    YYNSTATE           the combined number of states.
122973 **    YYNRULE            the number of rules in the grammar
122974 **    YYERRORSYMBOL      is the code number of the error symbol.  If not
122975 **                       defined, then do no error processing.
122976 */
122977 #define YYCODETYPE unsigned char
122978 #define YYNOCODE 254
122979 #define YYACTIONTYPE unsigned short int
122980 #define YYWILDCARD 70
122981 #define sqlite3ParserTOKENTYPE Token
122982 typedef union {
122983   int yyinit;
122984   sqlite3ParserTOKENTYPE yy0;
122985   Select* yy3;
122986   ExprList* yy14;
122987   With* yy59;
122988   SrcList* yy65;
122989   struct LikeOp yy96;
122990   Expr* yy132;
122991   u8 yy186;
122992   int yy328;
122993   ExprSpan yy346;
122994   struct TrigEvent yy378;
122995   u16 yy381;
122996   IdList* yy408;
122997   struct {int value; int mask;} yy429;
122998   TriggerStep* yy473;
122999   struct LimitVal yy476;
123000 } YYMINORTYPE;
123001 #ifndef YYSTACKDEPTH
123002 #define YYSTACKDEPTH 100
123003 #endif
123004 #define sqlite3ParserARG_SDECL Parse *pParse;
123005 #define sqlite3ParserARG_PDECL ,Parse *pParse
123006 #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
123007 #define sqlite3ParserARG_STORE yypParser->pParse = pParse
123008 #define YYNSTATE 642
123009 #define YYNRULE 327
123010 #define YYFALLBACK 1
123011 #define YY_NO_ACTION      (YYNSTATE+YYNRULE+2)
123012 #define YY_ACCEPT_ACTION  (YYNSTATE+YYNRULE+1)
123013 #define YY_ERROR_ACTION   (YYNSTATE+YYNRULE)
123014
123015 /* The yyzerominor constant is used to initialize instances of
123016 ** YYMINORTYPE objects to zero. */
123017 static const YYMINORTYPE yyzerominor = { 0 };
123018
123019 /* Define the yytestcase() macro to be a no-op if is not already defined
123020 ** otherwise.
123021 **
123022 ** Applications can choose to define yytestcase() in the %include section
123023 ** to a macro that can assist in verifying code coverage.  For production
123024 ** code the yytestcase() macro should be turned off.  But it is useful
123025 ** for testing.
123026 */
123027 #ifndef yytestcase
123028 # define yytestcase(X)
123029 #endif
123030
123031
123032 /* Next are the tables used to determine what action to take based on the
123033 ** current state and lookahead token.  These tables are used to implement
123034 ** functions that take a state number and lookahead value and return an
123035 ** action integer.  
123036 **
123037 ** Suppose the action integer is N.  Then the action is determined as
123038 ** follows
123039 **
123040 **   0 <= N < YYNSTATE                  Shift N.  That is, push the lookahead
123041 **                                      token onto the stack and goto state N.
123042 **
123043 **   YYNSTATE <= N < YYNSTATE+YYNRULE   Reduce by rule N-YYNSTATE.
123044 **
123045 **   N == YYNSTATE+YYNRULE              A syntax error has occurred.
123046 **
123047 **   N == YYNSTATE+YYNRULE+1            The parser accepts its input.
123048 **
123049 **   N == YYNSTATE+YYNRULE+2            No such action.  Denotes unused
123050 **                                      slots in the yy_action[] table.
123051 **
123052 ** The action table is constructed as a single large table named yy_action[].
123053 ** Given state S and lookahead X, the action is computed as
123054 **
123055 **      yy_action[ yy_shift_ofst[S] + X ]
123056 **
123057 ** If the index value yy_shift_ofst[S]+X is out of range or if the value
123058 ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
123059 ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
123060 ** and that yy_default[S] should be used instead.  
123061 **
123062 ** The formula above is for computing the action when the lookahead is
123063 ** a terminal symbol.  If the lookahead is a non-terminal (as occurs after
123064 ** a reduce action) then the yy_reduce_ofst[] array is used in place of
123065 ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
123066 ** YY_SHIFT_USE_DFLT.
123067 **
123068 ** The following are the tables generated in this section:
123069 **
123070 **  yy_action[]        A single table containing all actions.
123071 **  yy_lookahead[]     A table containing the lookahead for each entry in
123072 **                     yy_action.  Used to detect hash collisions.
123073 **  yy_shift_ofst[]    For each state, the offset into yy_action for
123074 **                     shifting terminals.
123075 **  yy_reduce_ofst[]   For each state, the offset into yy_action for
123076 **                     shifting non-terminals after a reduce.
123077 **  yy_default[]       Default action for each state.
123078 */
123079 #define YY_ACTTAB_COUNT (1497)
123080 static const YYACTIONTYPE yy_action[] = {
123081  /*     0 */   306,  212,  432,  955,  639,  191,  955,  295,  559,   88,
123082  /*    10 */    88,   88,   88,   81,   86,   86,   86,   86,   85,   85,
123083  /*    20 */    84,   84,   84,   83,  330,  185,  184,  183,  635,  635,
123084  /*    30 */   292,  606,  606,   88,   88,   88,   88,  683,   86,   86,
123085  /*    40 */    86,   86,   85,   85,   84,   84,   84,   83,  330,   16,
123086  /*    50 */   436,  597,   89,   90,   80,  600,  599,  601,  601,   87,
123087  /*    60 */    87,   88,   88,   88,   88,  684,   86,   86,   86,   86,
123088  /*    70 */    85,   85,   84,   84,   84,   83,  330,  306,  559,   84,
123089  /*    80 */    84,   84,   83,  330,   65,   86,   86,   86,   86,   85,
123090  /*    90 */    85,   84,   84,   84,   83,  330,  635,  635,  634,  633,
123091  /*   100 */   182,  682,  550,  379,  376,  375,   17,  322,  606,  606,
123092  /*   110 */   371,  198,  479,   91,  374,   82,   79,  165,   85,   85,
123093  /*   120 */    84,   84,   84,   83,  330,  598,  635,  635,  107,   89,
123094  /*   130 */    90,   80,  600,  599,  601,  601,   87,   87,   88,   88,
123095  /*   140 */    88,   88,  186,   86,   86,   86,   86,   85,   85,   84,
123096  /*   150 */    84,   84,   83,  330,  306,  594,  594,  142,  328,  327,
123097  /*   160 */   484,  249,  344,  238,  635,  635,  634,  633,  585,  448,
123098  /*   170 */   526,  525,  229,  388,    1,  394,  450,  584,  449,  635,
123099  /*   180 */   635,  635,  635,  319,  395,  606,  606,  199,  157,  273,
123100  /*   190 */   382,  268,  381,  187,  635,  635,  634,  633,  311,  555,
123101  /*   200 */   266,  593,  593,  266,  347,  588,   89,   90,   80,  600,
123102  /*   210 */   599,  601,  601,   87,   87,   88,   88,   88,   88,  478,
123103  /*   220 */    86,   86,   86,   86,   85,   85,   84,   84,   84,   83,
123104  /*   230 */   330,  306,  272,  536,  634,  633,  146,  610,  197,  310,
123105  /*   240 */   575,  182,  482,  271,  379,  376,  375,  506,   21,  634,
123106  /*   250 */   633,  634,  633,  635,  635,  374,  611,  574,  548,  440,
123107  /*   260 */   111,  563,  606,  606,  634,  633,  324,  479,  608,  608,
123108  /*   270 */   608,  300,  435,  573,  119,  407,  210,  162,  562,  883,
123109  /*   280 */   592,  592,  306,   89,   90,   80,  600,  599,  601,  601,
123110  /*   290 */    87,   87,   88,   88,   88,   88,  506,   86,   86,   86,
123111  /*   300 */    86,   85,   85,   84,   84,   84,   83,  330,  620,  111,
123112  /*   310 */   635,  635,  361,  606,  606,  358,  249,  349,  248,  433,
123113  /*   320 */   243,  479,  586,  634,  633,  195,  611,   93,  119,  221,
123114  /*   330 */   575,  497,  534,  534,   89,   90,   80,  600,  599,  601,
123115  /*   340 */   601,   87,   87,   88,   88,   88,   88,  574,   86,   86,
123116  /*   350 */    86,   86,   85,   85,   84,   84,   84,   83,  330,  306,
123117  /*   360 */    77,  429,  638,  573,  589,  530,  240,  230,  242,  105,
123118  /*   370 */   249,  349,  248,  515,  588,  208,  460,  529,  564,  173,
123119  /*   380 */   634,  633,  970,  144,  430,    2,  424,  228,  380,  557,
123120  /*   390 */   606,  606,  190,  153,  159,  158,  514,   51,  632,  631,
123121  /*   400 */   630,   71,  536,  432,  954,  196,  610,  954,  614,   45,
123122  /*   410 */    18,   89,   90,   80,  600,  599,  601,  601,   87,   87,
123123  /*   420 */    88,   88,   88,   88,  261,   86,   86,   86,   86,   85,
123124  /*   430 */    85,   84,   84,   84,   83,  330,  306,  608,  608,  608,
123125  /*   440 */   542,  424,  402,  385,  241,  506,  451,  320,  211,  543,
123126  /*   450 */   164,  436,  386,  293,  451,  587,  108,  496,  111,  334,
123127  /*   460 */   391,  591,  424,  614,   27,  452,  453,  606,  606,   72,
123128  /*   470 */   257,   70,  259,  452,  339,  342,  564,  582,   68,  415,
123129  /*   480 */   469,  328,  327,   62,  614,   45,  110,  393,   89,   90,
123130  /*   490 */    80,  600,  599,  601,  601,   87,   87,   88,   88,   88,
123131  /*   500 */    88,  152,   86,   86,   86,   86,   85,   85,   84,   84,
123132  /*   510 */    84,   83,  330,  306,  110,  499,  520,  538,  402,  389,
123133  /*   520 */   424,  110,  566,  500,  593,  593,  454,   82,   79,  165,
123134  /*   530 */   424,  591,  384,  564,  340,  615,  188,  162,  424,  350,
123135  /*   540 */   616,  424,  614,   44,  606,  606,  445,  582,  300,  434,
123136  /*   550 */   151,   19,  614,    9,  568,  580,  348,  615,  469,  567,
123137  /*   560 */   614,   26,  616,  614,   45,   89,   90,   80,  600,  599,
123138  /*   570 */   601,  601,   87,   87,   88,   88,   88,   88,  411,   86,
123139  /*   580 */    86,   86,   86,   85,   85,   84,   84,   84,   83,  330,
123140  /*   590 */   306,  579,  110,  578,  521,  282,  433,  398,  400,  255,
123141  /*   600 */   486,   82,   79,  165,  487,  164,   82,   79,  165,  488,
123142  /*   610 */   488,  364,  387,  424,  544,  544,  509,  350,  362,  155,
123143  /*   620 */   191,  606,  606,  559,  642,  640,  333,   82,   79,  165,
123144  /*   630 */   305,  564,  507,  312,  357,  614,   45,  329,  596,  595,
123145  /*   640 */   194,  337,   89,   90,   80,  600,  599,  601,  601,   87,
123146  /*   650 */    87,   88,   88,   88,   88,  424,   86,   86,   86,   86,
123147  /*   660 */    85,   85,   84,   84,   84,   83,  330,  306,   20,  323,
123148  /*   670 */   150,  263,  211,  543,  421,  596,  595,  614,   22,  424,
123149  /*   680 */   193,  424,  284,  424,  391,  424,  509,  424,  577,  424,
123150  /*   690 */   186,  335,  424,  559,  424,  313,  120,  546,  606,  606,
123151  /*   700 */    67,  614,   47,  614,   50,  614,   48,  614,  100,  614,
123152  /*   710 */    99,  614,  101,  576,  614,  102,  614,  109,  326,   89,
123153  /*   720 */    90,   80,  600,  599,  601,  601,   87,   87,   88,   88,
123154  /*   730 */    88,   88,  424,   86,   86,   86,   86,   85,   85,   84,
123155  /*   740 */    84,   84,   83,  330,  306,  424,  311,  424,  585,   54,
123156  /*   750 */   424,  516,  517,  590,  614,  112,  424,  584,  424,  572,
123157  /*   760 */   424,  195,  424,  571,  424,   67,  424,  614,   94,  614,
123158  /*   770 */    98,  424,  614,   97,  264,  606,  606,  195,  614,   46,
123159  /*   780 */   614,   96,  614,   30,  614,   49,  614,  115,  614,  114,
123160  /*   790 */   418,  229,  388,  614,  113,  306,   89,   90,   80,  600,
123161  /*   800 */   599,  601,  601,   87,   87,   88,   88,   88,   88,  424,
123162  /*   810 */    86,   86,   86,   86,   85,   85,   84,   84,   84,   83,
123163  /*   820 */   330,  119,  424,  590,  110,  372,  606,  606,  195,   53,
123164  /*   830 */   250,  614,   29,  195,  472,  438,  729,  190,  302,  498,
123165  /*   840 */    14,  523,  641,    2,  614,   43,  306,   89,   90,   80,
123166  /*   850 */   600,  599,  601,  601,   87,   87,   88,   88,   88,   88,
123167  /*   860 */   424,   86,   86,   86,   86,   85,   85,   84,   84,   84,
123168  /*   870 */    83,  330,  424,  613,  964,  964,  354,  606,  606,  420,
123169  /*   880 */   312,   64,  614,   42,  391,  355,  283,  437,  301,  255,
123170  /*   890 */   414,  410,  495,  492,  614,   28,  471,  306,   89,   90,
123171  /*   900 */    80,  600,  599,  601,  601,   87,   87,   88,   88,   88,
123172  /*   910 */    88,  424,   86,   86,   86,   86,   85,   85,   84,   84,
123173  /*   920 */    84,   83,  330,  424,  110,  110,  110,  110,  606,  606,
123174  /*   930 */   110,  254,   13,  614,   41,  532,  531,  283,  481,  531,
123175  /*   940 */   457,  284,  119,  561,  356,  614,   40,  284,  306,   89,
123176  /*   950 */    78,   80,  600,  599,  601,  601,   87,   87,   88,   88,
123177  /*   960 */    88,   88,  424,   86,   86,   86,   86,   85,   85,   84,
123178  /*   970 */    84,   84,   83,  330,  110,  424,  341,  220,  555,  606,
123179  /*   980 */   606,  351,  555,  318,  614,   95,  413,  255,   83,  330,
123180  /*   990 */   284,  284,  255,  640,  333,  356,  255,  614,   39,  306,
123181  /*  1000 */   356,   90,   80,  600,  599,  601,  601,   87,   87,   88,
123182  /*  1010 */    88,   88,   88,  424,   86,   86,   86,   86,   85,   85,
123183  /*  1020 */    84,   84,   84,   83,  330,  424,  317,  316,  141,  465,
123184  /*  1030 */   606,  606,  219,  619,  463,  614,   10,  417,  462,  255,
123185  /*  1040 */   189,  510,  553,  351,  207,  363,  161,  614,   38,  315,
123186  /*  1050 */   218,  255,  255,   80,  600,  599,  601,  601,   87,   87,
123187  /*  1060 */    88,   88,   88,   88,  424,   86,   86,   86,   86,   85,
123188  /*  1070 */    85,   84,   84,   84,   83,  330,   76,  419,  255,    3,
123189  /*  1080 */   878,  461,  424,  247,  331,  331,  614,   37,  217,   76,
123190  /*  1090 */   419,  390,    3,  216,  215,  422,    4,  331,  331,  424,
123191  /*  1100 */   547,   12,  424,  545,  614,   36,  424,  541,  422,  424,
123192  /*  1110 */   540,  424,  214,  424,  408,  424,  539,  403,  605,  605,
123193  /*  1120 */   237,  614,   25,  119,  614,   24,  588,  408,  614,   45,
123194  /*  1130 */   118,  614,   35,  614,   34,  614,   33,  614,   23,  588,
123195  /*  1140 */    60,  223,  603,  602,  513,  378,   73,   74,  140,  139,
123196  /*  1150 */   424,  110,  265,   75,  426,  425,   59,  424,  610,   73,
123197  /*  1160 */    74,  549,  402,  404,  424,  373,   75,  426,  425,  604,
123198  /*  1170 */   138,  610,  614,   11,  392,   76,  419,  181,    3,  614,
123199  /*  1180 */    32,  271,  369,  331,  331,  493,  614,   31,  149,  608,
123200  /*  1190 */   608,  608,  607,   15,  422,  365,  614,    8,  137,  489,
123201  /*  1200 */   136,  190,  608,  608,  608,  607,   15,  485,  176,  135,
123202  /*  1210 */     7,  252,  477,  408,  174,  133,  175,  474,   57,   56,
123203  /*  1220 */   132,  130,  119,   76,  419,  588,    3,  468,  245,  464,
123204  /*  1230 */   171,  331,  331,  125,  123,  456,  447,  122,  446,  104,
123205  /*  1240 */   336,  231,  422,  166,  154,   73,   74,  332,  116,  431,
123206  /*  1250 */   121,  309,   75,  426,  425,  222,  106,  610,  308,  637,
123207  /*  1260 */   204,  408,  629,  627,  628,    6,  200,  428,  427,  290,
123208  /*  1270 */   203,  622,  201,  588,   62,   63,  289,   66,  419,  399,
123209  /*  1280 */     3,  401,  288,   92,  143,  331,  331,  287,  608,  608,
123210  /*  1290 */   608,  607,   15,   73,   74,  227,  422,  325,   69,  416,
123211  /*  1300 */    75,  426,  425,  612,  412,  610,  192,   61,  569,  209,
123212  /*  1310 */   396,  226,  278,  225,  383,  408,  527,  558,  276,  533,
123213  /*  1320 */   552,  528,  321,  523,  370,  508,  180,  588,  494,  179,
123214  /*  1330 */   366,  117,  253,  269,  522,  503,  608,  608,  608,  607,
123215  /*  1340 */    15,  551,  502,   58,  274,  524,  178,   73,   74,  304,
123216  /*  1350 */   501,  368,  303,  206,   75,  426,  425,  491,  360,  610,
123217  /*  1360 */   213,  177,  483,  131,  345,  298,  297,  296,  202,  294,
123218  /*  1370 */   480,  490,  466,  134,  172,  129,  444,  346,  470,  128,
123219  /*  1380 */   314,  459,  103,  127,  126,  148,  124,  167,  443,  235,
123220  /*  1390 */   608,  608,  608,  607,   15,  442,  439,  623,  234,  299,
123221  /*  1400 */   145,  583,  291,  377,  581,  160,  119,  156,  270,  636,
123222  /*  1410 */   971,  169,  279,  626,  520,  625,  473,  624,  170,  621,
123223  /*  1420 */   618,  119,  168,   55,  409,  423,  537,  609,  286,  285,
123224  /*  1430 */   405,  570,  560,  556,    5,   52,  458,  554,  147,  267,
123225  /*  1440 */   519,  504,  518,  406,  262,  239,  260,  512,  343,  511,
123226  /*  1450 */   258,  353,  565,  256,  224,  251,  359,  277,  275,  476,
123227  /*  1460 */   475,  246,  352,  244,  467,  455,  236,  233,  232,  307,
123228  /*  1470 */   441,  281,  205,  163,  397,  280,  535,  505,  330,  617,
123229  /*  1480 */   971,  971,  971,  971,  367,  971,  971,  971,  971,  971,
123230  /*  1490 */   971,  971,  971,  971,  971,  971,  338,
123231 };
123232 static const YYCODETYPE yy_lookahead[] = {
123233  /*     0 */    19,   22,   22,   23,    1,   24,   26,   15,   27,   80,
123234  /*    10 */    81,   82,   83,   84,   85,   86,   87,   88,   89,   90,
123235  /*    20 */    91,   92,   93,   94,   95,  108,  109,  110,   27,   28,
123236  /*    30 */    23,   50,   51,   80,   81,   82,   83,  122,   85,   86,
123237  /*    40 */    87,   88,   89,   90,   91,   92,   93,   94,   95,   22,
123238  /*    50 */    70,   23,   71,   72,   73,   74,   75,   76,   77,   78,
123239  /*    60 */    79,   80,   81,   82,   83,  122,   85,   86,   87,   88,
123240  /*    70 */    89,   90,   91,   92,   93,   94,   95,   19,   97,   91,
123241  /*    80 */    92,   93,   94,   95,   26,   85,   86,   87,   88,   89,
123242  /*    90 */    90,   91,   92,   93,   94,   95,   27,   28,   97,   98,
123243  /*   100 */    99,  122,  211,  102,  103,  104,   79,   19,   50,   51,
123244  /*   110 */    19,  122,   59,   55,  113,  224,  225,  226,   89,   90,
123245  /*   120 */    91,   92,   93,   94,   95,   23,   27,   28,   26,   71,
123246  /*   130 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
123247  /*   140 */    82,   83,   51,   85,   86,   87,   88,   89,   90,   91,
123248  /*   150 */    92,   93,   94,   95,   19,  132,  133,   58,   89,   90,
123249  /*   160 */    21,  108,  109,  110,   27,   28,   97,   98,   33,  100,
123250  /*   170 */     7,    8,  119,  120,   22,   19,  107,   42,  109,   27,
123251  /*   180 */    28,   27,   28,   95,   28,   50,   51,   99,  100,  101,
123252  /*   190 */   102,  103,  104,  105,   27,   28,   97,   98,  107,  152,
123253  /*   200 */   112,  132,  133,  112,   65,   69,   71,   72,   73,   74,
123254  /*   210 */    75,   76,   77,   78,   79,   80,   81,   82,   83,   11,
123255  /*   220 */    85,   86,   87,   88,   89,   90,   91,   92,   93,   94,
123256  /*   230 */    95,   19,  101,   97,   97,   98,   24,  101,  122,  157,
123257  /*   240 */    12,   99,  103,  112,  102,  103,  104,  152,   22,   97,
123258  /*   250 */    98,   97,   98,   27,   28,  113,   27,   29,   91,  164,
123259  /*   260 */   165,  124,   50,   51,   97,   98,  219,   59,  132,  133,
123260  /*   270 */   134,   22,   23,   45,   66,   47,  212,  213,  124,  140,
123261  /*   280 */   132,  133,   19,   71,   72,   73,   74,   75,   76,   77,
123262  /*   290 */    78,   79,   80,   81,   82,   83,  152,   85,   86,   87,
123263  /*   300 */    88,   89,   90,   91,   92,   93,   94,   95,  164,  165,
123264  /*   310 */    27,   28,  230,   50,   51,  233,  108,  109,  110,   70,
123265  /*   320 */    16,   59,   23,   97,   98,   26,   97,   22,   66,  185,
123266  /*   330 */    12,  187,   27,   28,   71,   72,   73,   74,   75,   76,
123267  /*   340 */    77,   78,   79,   80,   81,   82,   83,   29,   85,   86,
123268  /*   350 */    87,   88,   89,   90,   91,   92,   93,   94,   95,   19,
123269  /*   360 */    22,  148,  149,   45,   23,   47,   62,  154,   64,  156,
123270  /*   370 */   108,  109,  110,   37,   69,   23,  163,   59,   26,   26,
123271  /*   380 */    97,   98,  144,  145,  146,  147,  152,  200,   52,   23,
123272  /*   390 */    50,   51,   26,   22,   89,   90,   60,  210,    7,    8,
123273  /*   400 */     9,  138,   97,   22,   23,   26,  101,   26,  174,  175,
123274  /*   410 */   197,   71,   72,   73,   74,   75,   76,   77,   78,   79,
123275  /*   420 */    80,   81,   82,   83,   16,   85,   86,   87,   88,   89,
123276  /*   430 */    90,   91,   92,   93,   94,   95,   19,  132,  133,  134,
123277  /*   440 */    23,  152,  208,  209,  140,  152,  152,  111,  195,  196,
123278  /*   450 */    98,   70,  163,  160,  152,   23,   22,  164,  165,  246,
123279  /*   460 */   207,   27,  152,  174,  175,  171,  172,   50,   51,  137,
123280  /*   470 */    62,  139,   64,  171,  172,  222,  124,   27,  138,   24,
123281  /*   480 */   163,   89,   90,  130,  174,  175,  197,  163,   71,   72,
123282  /*   490 */    73,   74,   75,   76,   77,   78,   79,   80,   81,   82,
123283  /*   500 */    83,   22,   85,   86,   87,   88,   89,   90,   91,   92,
123284  /*   510 */    93,   94,   95,   19,  197,  181,  182,   23,  208,  209,
123285  /*   520 */   152,  197,   26,  189,  132,  133,  232,  224,  225,  226,
123286  /*   530 */   152,   97,   91,   26,  232,  116,  212,  213,  152,  222,
123287  /*   540 */   121,  152,  174,  175,   50,   51,  243,   97,   22,   23,
123288  /*   550 */    22,  234,  174,  175,  177,   23,  239,  116,  163,  177,
123289  /*   560 */   174,  175,  121,  174,  175,   71,   72,   73,   74,   75,
123290  /*   570 */    76,   77,   78,   79,   80,   81,   82,   83,   24,   85,
123291  /*   580 */    86,   87,   88,   89,   90,   91,   92,   93,   94,   95,
123292  /*   590 */    19,   23,  197,   11,   23,  227,   70,  208,  220,  152,
123293  /*   600 */    31,  224,  225,  226,   35,   98,  224,  225,  226,  108,
123294  /*   610 */   109,  110,  115,  152,  117,  118,   27,  222,   49,  123,
123295  /*   620 */    24,   50,   51,   27,    0,    1,    2,  224,  225,  226,
123296  /*   630 */   166,  124,  168,  169,  239,  174,  175,  170,  171,  172,
123297  /*   640 */    22,  194,   71,   72,   73,   74,   75,   76,   77,   78,
123298  /*   650 */    79,   80,   81,   82,   83,  152,   85,   86,   87,   88,
123299  /*   660 */    89,   90,   91,   92,   93,   94,   95,   19,   22,  208,
123300  /*   670 */    24,   23,  195,  196,  170,  171,  172,  174,  175,  152,
123301  /*   680 */    26,  152,  152,  152,  207,  152,   97,  152,   23,  152,
123302  /*   690 */    51,  244,  152,   97,  152,  247,  248,   23,   50,   51,
123303  /*   700 */    26,  174,  175,  174,  175,  174,  175,  174,  175,  174,
123304  /*   710 */   175,  174,  175,   23,  174,  175,  174,  175,  188,   71,
123305  /*   720 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
123306  /*   730 */    82,   83,  152,   85,   86,   87,   88,   89,   90,   91,
123307  /*   740 */    92,   93,   94,   95,   19,  152,  107,  152,   33,   24,
123308  /*   750 */   152,  100,  101,   27,  174,  175,  152,   42,  152,   23,
123309  /*   760 */   152,   26,  152,   23,  152,   26,  152,  174,  175,  174,
123310  /*   770 */   175,  152,  174,  175,   23,   50,   51,   26,  174,  175,
123311  /*   780 */   174,  175,  174,  175,  174,  175,  174,  175,  174,  175,
123312  /*   790 */   163,  119,  120,  174,  175,   19,   71,   72,   73,   74,
123313  /*   800 */    75,   76,   77,   78,   79,   80,   81,   82,   83,  152,
123314  /*   810 */    85,   86,   87,   88,   89,   90,   91,   92,   93,   94,
123315  /*   820 */    95,   66,  152,   97,  197,   23,   50,   51,   26,   53,
123316  /*   830 */    23,  174,  175,   26,   23,   23,   23,   26,   26,   26,
123317  /*   840 */    36,  106,  146,  147,  174,  175,   19,   71,   72,   73,
123318  /*   850 */    74,   75,   76,   77,   78,   79,   80,   81,   82,   83,
123319  /*   860 */   152,   85,   86,   87,   88,   89,   90,   91,   92,   93,
123320  /*   870 */    94,   95,  152,  196,  119,  120,   19,   50,   51,  168,
123321  /*   880 */   169,   26,  174,  175,  207,   28,  152,  249,  250,  152,
123322  /*   890 */   163,  163,  163,  163,  174,  175,  163,   19,   71,   72,
123323  /*   900 */    73,   74,   75,   76,   77,   78,   79,   80,   81,   82,
123324  /*   910 */    83,  152,   85,   86,   87,   88,   89,   90,   91,   92,
123325  /*   920 */    93,   94,   95,  152,  197,  197,  197,  197,   50,   51,
123326  /*   930 */   197,  194,   36,  174,  175,  191,  192,  152,  191,  192,
123327  /*   940 */   163,  152,   66,  124,  152,  174,  175,  152,   19,   71,
123328  /*   950 */    72,   73,   74,   75,   76,   77,   78,   79,   80,   81,
123329  /*   960 */    82,   83,  152,   85,   86,   87,   88,   89,   90,   91,
123330  /*   970 */    92,   93,   94,   95,  197,  152,  100,  188,  152,   50,
123331  /*   980 */    51,  152,  152,  188,  174,  175,  252,  152,   94,   95,
123332  /*   990 */   152,  152,  152,    1,    2,  152,  152,  174,  175,   19,
123333  /*  1000 */   152,   72,   73,   74,   75,   76,   77,   78,   79,   80,
123334  /*  1010 */    81,   82,   83,  152,   85,   86,   87,   88,   89,   90,
123335  /*  1020 */    91,   92,   93,   94,   95,  152,  188,  188,   22,  194,
123336  /*  1030 */    50,   51,  240,  173,  194,  174,  175,  252,  194,  152,
123337  /*  1040 */    36,  181,   28,  152,   23,  219,  122,  174,  175,  219,
123338  /*  1050 */   221,  152,  152,   73,   74,   75,   76,   77,   78,   79,
123339  /*  1060 */    80,   81,   82,   83,  152,   85,   86,   87,   88,   89,
123340  /*  1070 */    90,   91,   92,   93,   94,   95,   19,   20,  152,   22,
123341  /*  1080 */    23,  194,  152,  240,   27,   28,  174,  175,  240,   19,
123342  /*  1090 */    20,   26,   22,  194,  194,   38,   22,   27,   28,  152,
123343  /*  1100 */    23,   22,  152,  116,  174,  175,  152,   23,   38,  152,
123344  /*  1110 */    23,  152,  221,  152,   57,  152,   23,  163,   50,   51,
123345  /*  1120 */   194,  174,  175,   66,  174,  175,   69,   57,  174,  175,
123346  /*  1130 */    40,  174,  175,  174,  175,  174,  175,  174,  175,   69,
123347  /*  1140 */    22,   53,   74,   75,   30,   53,   89,   90,   22,   22,
123348  /*  1150 */   152,  197,   23,   96,   97,   98,   22,  152,  101,   89,
123349  /*  1160 */    90,   91,  208,  209,  152,   53,   96,   97,   98,  101,
123350  /*  1170 */    22,  101,  174,  175,  152,   19,   20,  105,   22,  174,
123351  /*  1180 */   175,  112,   19,   27,   28,   20,  174,  175,   24,  132,
123352  /*  1190 */   133,  134,  135,  136,   38,   44,  174,  175,  107,   61,
123353  /*  1200 */    54,   26,  132,  133,  134,  135,  136,   54,  107,   22,
123354  /*  1210 */     5,  140,    1,   57,   36,  111,  122,   28,   79,   79,
123355  /*  1220 */   131,  123,   66,   19,   20,   69,   22,    1,   16,   20,
123356  /*  1230 */   125,   27,   28,  123,  111,  120,   23,  131,   23,   16,
123357  /*  1240 */    68,  142,   38,   15,   22,   89,   90,    3,  167,    4,
123358  /*  1250 */   248,  251,   96,   97,   98,  180,  180,  101,  251,  151,
123359  /*  1260 */     6,   57,  151,   13,  151,   26,   25,  151,  161,  202,
123360  /*  1270 */   153,  162,  153,   69,  130,  128,  203,   19,   20,  127,
123361  /*  1280 */    22,  126,  204,  129,   22,   27,   28,  205,  132,  133,
123362  /*  1290 */   134,  135,  136,   89,   90,  231,   38,   95,  137,  179,
123363  /*  1300 */    96,   97,   98,  206,  179,  101,  122,  107,  159,  159,
123364  /*  1310 */   125,  231,  216,  228,  107,   57,  184,  217,  216,  176,
123365  /*  1320 */   217,  176,   48,  106,   18,  184,  158,   69,  159,  158,
123366  /*  1330 */    46,   71,  237,  176,  176,  176,  132,  133,  134,  135,
123367  /*  1340 */   136,  217,  176,  137,  216,  178,  158,   89,   90,  179,
123368  /*  1350 */   176,  159,  179,  159,   96,   97,   98,  159,  159,  101,
123369  /*  1360 */     5,  158,  202,   22,   18,   10,   11,   12,   13,   14,
123370  /*  1370 */   190,  238,   17,  190,  158,  193,   41,  159,  202,  193,
123371  /*  1380 */   159,  202,  245,  193,  193,  223,  190,   32,  159,   34,
123372  /*  1390 */   132,  133,  134,  135,  136,  159,   39,  155,   43,  150,
123373  /*  1400 */   223,  177,  201,  178,  177,  186,   66,  199,  177,  152,
123374  /*  1410 */   253,   56,  215,  152,  182,  152,  202,  152,   63,  152,
123375  /*  1420 */   152,   66,   67,  242,  229,  152,  174,  152,  152,  152,
123376  /*  1430 */   152,  152,  152,  152,  199,  242,  202,  152,  198,  152,
123377  /*  1440 */   152,  152,  183,  192,  152,  215,  152,  183,  215,  183,
123378  /*  1450 */   152,  241,  214,  152,  211,  152,  152,  211,  211,  152,
123379  /*  1460 */   152,  241,  152,  152,  152,  152,  152,  152,  152,  114,
123380  /*  1470 */   152,  152,  235,  152,  152,  152,  174,  187,   95,  174,
123381  /*  1480 */   253,  253,  253,  253,  236,  253,  253,  253,  253,  253,
123382  /*  1490 */   253,  253,  253,  253,  253,  253,  141,
123383 };
123384 #define YY_SHIFT_USE_DFLT (-86)
123385 #define YY_SHIFT_COUNT (429)
123386 #define YY_SHIFT_MIN   (-85)
123387 #define YY_SHIFT_MAX   (1383)
123388 static const short yy_shift_ofst[] = {
123389  /*     0 */   992, 1057, 1355, 1156, 1204, 1204,    1,  262,  -19,  135,
123390  /*    10 */   135,  776, 1204, 1204, 1204, 1204,   69,   69,   53,  208,
123391  /*    20 */   283,  755,   58,  725,  648,  571,  494,  417,  340,  263,
123392  /*    30 */   212,  827,  827,  827,  827,  827,  827,  827,  827,  827,
123393  /*    40 */   827,  827,  827,  827,  827,  827,  878,  827,  929,  980,
123394  /*    50 */   980, 1070, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
123395  /*    60 */  1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
123396  /*    70 */  1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
123397  /*    80 */  1258, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
123398  /*    90 */  1204, 1204, 1204, 1204,  -71,  -47,  -47,  -47,  -47,  -47,
123399  /*   100 */     0,   29,  -12,  283,  283,  139,   91,  392,  392,  894,
123400  /*   110 */   672,  726, 1383,  -86,  -86,  -86,   88,  318,  318,   99,
123401  /*   120 */   381,  -20,  283,  283,  283,  283,  283,  283,  283,  283,
123402  /*   130 */   283,  283,  283,  283,  283,  283,  283,  283,  283,  283,
123403  /*   140 */   283,  283,  283,  283,  624,  876,  726,  672, 1340, 1340,
123404  /*   150 */  1340, 1340, 1340, 1340,  -86,  -86,  -86,  305,  136,  136,
123405  /*   160 */   142,  167,  226,  154,  137,  152,  283,  283,  283,  283,
123406  /*   170 */   283,  283,  283,  283,  283,  283,  283,  283,  283,  283,
123407  /*   180 */   283,  283,  283,  336,  336,  336,  283,  283,  352,  283,
123408  /*   190 */   283,  283,  283,  283,  228,  283,  283,  283,  283,  283,
123409  /*   200 */   283,  283,  283,  283,  283,  501,  569,  596,  596,  596,
123410  /*   210 */   507,  497,  441,  391,  353,  156,  156,  857,  353,  857,
123411  /*   220 */   735,  813,  639,  715,  156,  332,  715,  715,  496,  419,
123412  /*   230 */   646, 1357, 1184, 1184, 1335, 1335, 1184, 1341, 1260, 1144,
123413  /*   240 */  1346, 1346, 1346, 1346, 1184, 1306, 1144, 1341, 1260, 1260,
123414  /*   250 */  1144, 1184, 1306, 1206, 1284, 1184, 1184, 1306, 1184, 1306,
123415  /*   260 */  1184, 1306, 1262, 1207, 1207, 1207, 1274, 1262, 1207, 1217,
123416  /*   270 */  1207, 1274, 1207, 1207, 1185, 1200, 1185, 1200, 1185, 1200,
123417  /*   280 */  1184, 1184, 1161, 1262, 1202, 1202, 1262, 1154, 1155, 1147,
123418  /*   290 */  1152, 1144, 1241, 1239, 1250, 1250, 1254, 1254, 1254, 1254,
123419  /*   300 */   -86,  -86,  -86,  -86,  -86,  -86, 1068,  304,  526,  249,
123420  /*   310 */   408,  -83,  434,  812,   27,  811,  807,  802,  751,  589,
123421  /*   320 */   651,  163,  131,  674,  366,  450,  299,  148,   23,  102,
123422  /*   330 */   229,  -21, 1245, 1244, 1222, 1099, 1228, 1172, 1223, 1215,
123423  /*   340 */  1213, 1115, 1106, 1123, 1110, 1209, 1105, 1212, 1226, 1098,
123424  /*   350 */  1089, 1140, 1139, 1104, 1189, 1178, 1094, 1211, 1205, 1187,
123425  /*   360 */  1101, 1071, 1153, 1175, 1146, 1138, 1151, 1091, 1164, 1165,
123426  /*   370 */  1163, 1069, 1072, 1148, 1112, 1134, 1127, 1129, 1126, 1092,
123427  /*   380 */  1114, 1118, 1088, 1090, 1093, 1087, 1084,  987, 1079, 1077,
123428  /*   390 */  1074, 1065,  924, 1021, 1014, 1004, 1006,  819,  739,  896,
123429  /*   400 */   855,  804,  739,  740,  736,  690,  654,  665,  618,  582,
123430  /*   410 */   568,  528,  554,  379,  532,  479,  455,  379,  432,  371,
123431  /*   420 */   341,   28,  338,  116,  -11,  -57,  -85,    7,   -8,    3,
123432 };
123433 #define YY_REDUCE_USE_DFLT (-110)
123434 #define YY_REDUCE_COUNT (305)
123435 #define YY_REDUCE_MIN   (-109)
123436 #define YY_REDUCE_MAX   (1323)
123437 static const short yy_reduce_ofst[] = {
123438  /*     0 */   238,  954,  213,  289,  310,  234,  144,  317, -109,  382,
123439  /*    10 */   377,  303,  461,  389,  378,  368,  302,  294,  253,  395,
123440  /*    20 */   293,  324,  403,  403,  403,  403,  403,  403,  403,  403,
123441  /*    30 */   403,  403,  403,  403,  403,  403,  403,  403,  403,  403,
123442  /*    40 */   403,  403,  403,  403,  403,  403,  403,  403,  403,  403,
123443  /*    50 */   403, 1022, 1012, 1005,  998,  963,  961,  959,  957,  950,
123444  /*    60 */   947,  930,  912,  873,  861,  823,  810,  771,  759,  720,
123445  /*    70 */   708,  670,  657,  619,  614,  612,  610,  608,  606,  604,
123446  /*    80 */   598,  595,  593,  580,  542,  540,  537,  535,  533,  531,
123447  /*    90 */   529,  527,  503,  386,  403,  403,  403,  403,  403,  403,
123448  /*   100 */   403,  403,  403,   95,  447,   82,  334,  504,  467,  403,
123449  /*   110 */   477,  464,  403,  403,  403,  403,  860,  747,  744,  785,
123450  /*   120 */   638,  638,  926,  891,  900,  899,  887,  844,  840,  835,
123451  /*   130 */   848,  830,  843,  829,  792,  839,  826,  737,  838,  795,
123452  /*   140 */   789,   47,  734,  530,  696,  777,  711,  677,  733,  730,
123453  /*   150 */   729,  728,  727,  627,  448,   64,  187, 1305, 1302, 1252,
123454  /*   160 */  1290, 1273, 1323, 1322, 1321, 1319, 1318, 1316, 1315, 1314,
123455  /*   170 */  1313, 1312, 1311, 1310, 1308, 1307, 1304, 1303, 1301, 1298,
123456  /*   180 */  1294, 1292, 1289, 1266, 1264, 1259, 1288, 1287, 1238, 1285,
123457  /*   190 */  1281, 1280, 1279, 1278, 1251, 1277, 1276, 1275, 1273, 1268,
123458  /*   200 */  1267, 1265, 1263, 1261, 1257, 1248, 1237, 1247, 1246, 1243,
123459  /*   210 */  1238, 1240, 1235, 1249, 1234, 1233, 1230, 1220, 1214, 1210,
123460  /*   220 */  1225, 1219, 1232, 1231, 1197, 1195, 1227, 1224, 1201, 1208,
123461  /*   230 */  1242, 1137, 1236, 1229, 1193, 1181, 1221, 1177, 1196, 1179,
123462  /*   240 */  1191, 1190, 1186, 1182, 1218, 1216, 1176, 1162, 1183, 1180,
123463  /*   250 */  1160, 1199, 1203, 1133, 1095, 1198, 1194, 1188, 1192, 1171,
123464  /*   260 */  1169, 1168, 1173, 1174, 1166, 1159, 1141, 1170, 1158, 1167,
123465  /*   270 */  1157, 1132, 1145, 1143, 1124, 1128, 1103, 1102, 1100, 1096,
123466  /*   280 */  1150, 1149, 1085, 1125, 1080, 1064, 1120, 1097, 1082, 1078,
123467  /*   290 */  1073, 1067, 1109, 1107, 1119, 1117, 1116, 1113, 1111, 1108,
123468  /*   300 */  1007, 1000, 1002, 1076, 1075, 1081,
123469 };
123470 static const YYACTIONTYPE yy_default[] = {
123471  /*     0 */   647,  964,  964,  964,  878,  878,  969,  964,  774,  802,
123472  /*    10 */   802,  938,  969,  969,  969,  876,  969,  969,  969,  964,
123473  /*    20 */   969,  778,  808,  969,  969,  969,  969,  969,  969,  969,
123474  /*    30 */   969,  937,  939,  816,  815,  918,  789,  813,  806,  810,
123475  /*    40 */   879,  872,  873,  871,  875,  880,  969,  809,  841,  856,
123476  /*    50 */   840,  969,  969,  969,  969,  969,  969,  969,  969,  969,
123477  /*    60 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
123478  /*    70 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
123479  /*    80 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
123480  /*    90 */   969,  969,  969,  969,  850,  855,  862,  854,  851,  843,
123481  /*   100 */   842,  844,  845,  969,  969,  673,  739,  969,  969,  846,
123482  /*   110 */   969,  685,  847,  859,  858,  857,  680,  969,  969,  969,
123483  /*   120 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
123484  /*   130 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
123485  /*   140 */   969,  969,  969,  969,  647,  964,  969,  969,  964,  964,
123486  /*   150 */   964,  964,  964,  964,  956,  778,  768,  969,  969,  969,
123487  /*   160 */   969,  969,  969,  969,  969,  969,  969,  944,  942,  969,
123488  /*   170 */   891,  969,  969,  969,  969,  969,  969,  969,  969,  969,
123489  /*   180 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
123490  /*   190 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
123491  /*   200 */   969,  969,  969,  969,  653,  969,  911,  774,  774,  774,
123492  /*   210 */   776,  754,  766,  655,  812,  791,  791,  923,  812,  923,
123493  /*   220 */   710,  733,  707,  802,  791,  874,  802,  802,  775,  766,
123494  /*   230 */   969,  949,  782,  782,  941,  941,  782,  821,  743,  812,
123495  /*   240 */   750,  750,  750,  750,  782,  670,  812,  821,  743,  743,
123496  /*   250 */   812,  782,  670,  917,  915,  782,  782,  670,  782,  670,
123497  /*   260 */   782,  670,  884,  741,  741,  741,  725,  884,  741,  710,
123498  /*   270 */   741,  725,  741,  741,  795,  790,  795,  790,  795,  790,
123499  /*   280 */   782,  782,  969,  884,  888,  888,  884,  807,  796,  805,
123500  /*   290 */   803,  812,  676,  728,  663,  663,  652,  652,  652,  652,
123501  /*   300 */   961,  961,  956,  712,  712,  695,  969,  969,  969,  969,
123502  /*   310 */   969,  969,  687,  969,  893,  969,  969,  969,  969,  969,
123503  /*   320 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
123504  /*   330 */   969,  828,  969,  648,  951,  969,  969,  948,  969,  969,
123505  /*   340 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
123506  /*   350 */   969,  969,  969,  969,  969,  969,  921,  969,  969,  969,
123507  /*   360 */   969,  969,  969,  914,  913,  969,  969,  969,  969,  969,
123508  /*   370 */   969,  969,  969,  969,  969,  969,  969,  969,  969,  969,
123509  /*   380 */   969,  969,  969,  969,  969,  969,  969,  757,  969,  969,
123510  /*   390 */   969,  761,  969,  969,  969,  969,  969,  969,  804,  969,
123511  /*   400 */   797,  969,  877,  969,  969,  969,  969,  969,  969,  969,
123512  /*   410 */   969,  969,  969,  966,  969,  969,  969,  965,  969,  969,
123513  /*   420 */   969,  969,  969,  830,  969,  829,  833,  969,  661,  969,
123514  /*   430 */   644,  649,  960,  963,  962,  959,  958,  957,  952,  950,
123515  /*   440 */   947,  946,  945,  943,  940,  936,  897,  895,  902,  901,
123516  /*   450 */   900,  899,  898,  896,  894,  892,  818,  817,  814,  811,
123517  /*   460 */   753,  935,  890,  752,  749,  748,  669,  953,  920,  929,
123518  /*   470 */   928,  927,  822,  926,  925,  924,  922,  919,  906,  820,
123519  /*   480 */   819,  744,  882,  881,  672,  910,  909,  908,  912,  916,
123520  /*   490 */   907,  784,  751,  671,  668,  675,  679,  731,  732,  740,
123521  /*   500 */   738,  737,  736,  735,  734,  730,  681,  686,  724,  709,
123522  /*   510 */   708,  717,  716,  722,  721,  720,  719,  718,  715,  714,
123523  /*   520 */   713,  706,  705,  711,  704,  727,  726,  723,  703,  747,
123524  /*   530 */   746,  745,  742,  702,  701,  700,  833,  699,  698,  838,
123525  /*   540 */   837,  866,  826,  755,  759,  758,  762,  763,  771,  770,
123526  /*   550 */   769,  780,  781,  793,  792,  824,  823,  794,  779,  773,
123527  /*   560 */   772,  788,  787,  786,  785,  777,  767,  799,  798,  868,
123528  /*   570 */   783,  867,  865,  934,  933,  932,  931,  930,  870,  967,
123529  /*   580 */   968,  887,  889,  886,  801,  800,  885,  869,  839,  836,
123530  /*   590 */   690,  691,  905,  904,  903,  693,  692,  689,  688,  863,
123531  /*   600 */   860,  852,  864,  861,  853,  849,  848,  834,  832,  831,
123532  /*   610 */   827,  835,  760,  756,  825,  765,  764,  697,  696,  694,
123533  /*   620 */   678,  677,  674,  667,  665,  664,  666,  662,  660,  659,
123534  /*   630 */   658,  657,  656,  684,  683,  682,  654,  651,  650,  646,
123535  /*   640 */   645,  643,
123536 };
123537
123538 /* The next table maps tokens into fallback tokens.  If a construct
123539 ** like the following:
123540 ** 
123541 **      %fallback ID X Y Z.
123542 **
123543 ** appears in the grammar, then ID becomes a fallback token for X, Y,
123544 ** and Z.  Whenever one of the tokens X, Y, or Z is input to the parser
123545 ** but it does not parse, the type of the token is changed to ID and
123546 ** the parse is retried before an error is thrown.
123547 */
123548 #ifdef YYFALLBACK
123549 static const YYCODETYPE yyFallback[] = {
123550     0,  /*          $ => nothing */
123551     0,  /*       SEMI => nothing */
123552    27,  /*    EXPLAIN => ID */
123553    27,  /*      QUERY => ID */
123554    27,  /*       PLAN => ID */
123555    27,  /*      BEGIN => ID */
123556     0,  /* TRANSACTION => nothing */
123557    27,  /*   DEFERRED => ID */
123558    27,  /*  IMMEDIATE => ID */
123559    27,  /*  EXCLUSIVE => ID */
123560     0,  /*     COMMIT => nothing */
123561    27,  /*        END => ID */
123562    27,  /*   ROLLBACK => ID */
123563    27,  /*  SAVEPOINT => ID */
123564    27,  /*    RELEASE => ID */
123565     0,  /*         TO => nothing */
123566     0,  /*      TABLE => nothing */
123567     0,  /*     CREATE => nothing */
123568    27,  /*         IF => ID */
123569     0,  /*        NOT => nothing */
123570     0,  /*     EXISTS => nothing */
123571    27,  /*       TEMP => ID */
123572     0,  /*         LP => nothing */
123573     0,  /*         RP => nothing */
123574     0,  /*         AS => nothing */
123575    27,  /*    WITHOUT => ID */
123576     0,  /*      COMMA => nothing */
123577     0,  /*         ID => nothing */
123578     0,  /*    INDEXED => nothing */
123579    27,  /*      ABORT => ID */
123580    27,  /*     ACTION => ID */
123581    27,  /*      AFTER => ID */
123582    27,  /*    ANALYZE => ID */
123583    27,  /*        ASC => ID */
123584    27,  /*     ATTACH => ID */
123585    27,  /*     BEFORE => ID */
123586    27,  /*         BY => ID */
123587    27,  /*    CASCADE => ID */
123588    27,  /*       CAST => ID */
123589    27,  /*   COLUMNKW => ID */
123590    27,  /*   CONFLICT => ID */
123591    27,  /*   DATABASE => ID */
123592    27,  /*       DESC => ID */
123593    27,  /*     DETACH => ID */
123594    27,  /*       EACH => ID */
123595    27,  /*       FAIL => ID */
123596    27,  /*        FOR => ID */
123597    27,  /*     IGNORE => ID */
123598    27,  /*  INITIALLY => ID */
123599    27,  /*    INSTEAD => ID */
123600    27,  /*    LIKE_KW => ID */
123601    27,  /*      MATCH => ID */
123602    27,  /*         NO => ID */
123603    27,  /*        KEY => ID */
123604    27,  /*         OF => ID */
123605    27,  /*     OFFSET => ID */
123606    27,  /*     PRAGMA => ID */
123607    27,  /*      RAISE => ID */
123608    27,  /*  RECURSIVE => ID */
123609    27,  /*    REPLACE => ID */
123610    27,  /*   RESTRICT => ID */
123611    27,  /*        ROW => ID */
123612    27,  /*    TRIGGER => ID */
123613    27,  /*     VACUUM => ID */
123614    27,  /*       VIEW => ID */
123615    27,  /*    VIRTUAL => ID */
123616    27,  /*       WITH => ID */
123617    27,  /*    REINDEX => ID */
123618    27,  /*     RENAME => ID */
123619    27,  /*   CTIME_KW => ID */
123620 };
123621 #endif /* YYFALLBACK */
123622
123623 /* The following structure represents a single element of the
123624 ** parser's stack.  Information stored includes:
123625 **
123626 **   +  The state number for the parser at this level of the stack.
123627 **
123628 **   +  The value of the token stored at this level of the stack.
123629 **      (In other words, the "major" token.)
123630 **
123631 **   +  The semantic value stored at this level of the stack.  This is
123632 **      the information used by the action routines in the grammar.
123633 **      It is sometimes called the "minor" token.
123634 */
123635 struct yyStackEntry {
123636   YYACTIONTYPE stateno;  /* The state-number */
123637   YYCODETYPE major;      /* The major token value.  This is the code
123638                          ** number for the token at this stack level */
123639   YYMINORTYPE minor;     /* The user-supplied minor token value.  This
123640                          ** is the value of the token  */
123641 };
123642 typedef struct yyStackEntry yyStackEntry;
123643
123644 /* The state of the parser is completely contained in an instance of
123645 ** the following structure */
123646 struct yyParser {
123647   int yyidx;                    /* Index of top element in stack */
123648 #ifdef YYTRACKMAXSTACKDEPTH
123649   int yyidxMax;                 /* Maximum value of yyidx */
123650 #endif
123651   int yyerrcnt;                 /* Shifts left before out of the error */
123652   sqlite3ParserARG_SDECL                /* A place to hold %extra_argument */
123653 #if YYSTACKDEPTH<=0
123654   int yystksz;                  /* Current side of the stack */
123655   yyStackEntry *yystack;        /* The parser's stack */
123656 #else
123657   yyStackEntry yystack[YYSTACKDEPTH];  /* The parser's stack */
123658 #endif
123659 };
123660 typedef struct yyParser yyParser;
123661
123662 #ifndef NDEBUG
123663 /* #include <stdio.h> */
123664 static FILE *yyTraceFILE = 0;
123665 static char *yyTracePrompt = 0;
123666 #endif /* NDEBUG */
123667
123668 #ifndef NDEBUG
123669 /* 
123670 ** Turn parser tracing on by giving a stream to which to write the trace
123671 ** and a prompt to preface each trace message.  Tracing is turned off
123672 ** by making either argument NULL 
123673 **
123674 ** Inputs:
123675 ** <ul>
123676 ** <li> A FILE* to which trace output should be written.
123677 **      If NULL, then tracing is turned off.
123678 ** <li> A prefix string written at the beginning of every
123679 **      line of trace output.  If NULL, then tracing is
123680 **      turned off.
123681 ** </ul>
123682 **
123683 ** Outputs:
123684 ** None.
123685 */
123686 SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
123687   yyTraceFILE = TraceFILE;
123688   yyTracePrompt = zTracePrompt;
123689   if( yyTraceFILE==0 ) yyTracePrompt = 0;
123690   else if( yyTracePrompt==0 ) yyTraceFILE = 0;
123691 }
123692 #endif /* NDEBUG */
123693
123694 #ifndef NDEBUG
123695 /* For tracing shifts, the names of all terminals and nonterminals
123696 ** are required.  The following table supplies these names */
123697 static const char *const yyTokenName[] = { 
123698   "$",             "SEMI",          "EXPLAIN",       "QUERY",       
123699   "PLAN",          "BEGIN",         "TRANSACTION",   "DEFERRED",    
123700   "IMMEDIATE",     "EXCLUSIVE",     "COMMIT",        "END",         
123701   "ROLLBACK",      "SAVEPOINT",     "RELEASE",       "TO",          
123702   "TABLE",         "CREATE",        "IF",            "NOT",         
123703   "EXISTS",        "TEMP",          "LP",            "RP",          
123704   "AS",            "WITHOUT",       "COMMA",         "ID",          
123705   "INDEXED",       "ABORT",         "ACTION",        "AFTER",       
123706   "ANALYZE",       "ASC",           "ATTACH",        "BEFORE",      
123707   "BY",            "CASCADE",       "CAST",          "COLUMNKW",    
123708   "CONFLICT",      "DATABASE",      "DESC",          "DETACH",      
123709   "EACH",          "FAIL",          "FOR",           "IGNORE",      
123710   "INITIALLY",     "INSTEAD",       "LIKE_KW",       "MATCH",       
123711   "NO",            "KEY",           "OF",            "OFFSET",      
123712   "PRAGMA",        "RAISE",         "RECURSIVE",     "REPLACE",     
123713   "RESTRICT",      "ROW",           "TRIGGER",       "VACUUM",      
123714   "VIEW",          "VIRTUAL",       "WITH",          "REINDEX",     
123715   "RENAME",        "CTIME_KW",      "ANY",           "OR",          
123716   "AND",           "IS",            "BETWEEN",       "IN",          
123717   "ISNULL",        "NOTNULL",       "NE",            "EQ",          
123718   "GT",            "LE",            "LT",            "GE",          
123719   "ESCAPE",        "BITAND",        "BITOR",         "LSHIFT",      
123720   "RSHIFT",        "PLUS",          "MINUS",         "STAR",        
123721   "SLASH",         "REM",           "CONCAT",        "COLLATE",     
123722   "BITNOT",        "STRING",        "JOIN_KW",       "CONSTRAINT",  
123723   "DEFAULT",       "NULL",          "PRIMARY",       "UNIQUE",      
123724   "CHECK",         "REFERENCES",    "AUTOINCR",      "ON",          
123725   "INSERT",        "DELETE",        "UPDATE",        "SET",         
123726   "DEFERRABLE",    "FOREIGN",       "DROP",          "UNION",       
123727   "ALL",           "EXCEPT",        "INTERSECT",     "SELECT",      
123728   "VALUES",        "DISTINCT",      "DOT",           "FROM",        
123729   "JOIN",          "USING",         "ORDER",         "GROUP",       
123730   "HAVING",        "LIMIT",         "WHERE",         "INTO",        
123731   "INTEGER",       "FLOAT",         "BLOB",          "VARIABLE",    
123732   "CASE",          "WHEN",          "THEN",          "ELSE",        
123733   "INDEX",         "ALTER",         "ADD",           "error",       
123734   "input",         "cmdlist",       "ecmd",          "explain",     
123735   "cmdx",          "cmd",           "transtype",     "trans_opt",   
123736   "nm",            "savepoint_opt",  "create_table",  "create_table_args",
123737   "createkw",      "temp",          "ifnotexists",   "dbnm",        
123738   "columnlist",    "conslist_opt",  "table_options",  "select",      
123739   "column",        "columnid",      "type",          "carglist",    
123740   "typetoken",     "typename",      "signed",        "plus_num",    
123741   "minus_num",     "ccons",         "term",          "expr",        
123742   "onconf",        "sortorder",     "autoinc",       "idxlist_opt", 
123743   "refargs",       "defer_subclause",  "refarg",        "refact",      
123744   "init_deferred_pred_opt",  "conslist",      "tconscomma",    "tcons",       
123745   "idxlist",       "defer_subclause_opt",  "orconf",        "resolvetype", 
123746   "raisetype",     "ifexists",      "fullname",      "selectnowith",
123747   "oneselect",     "with",          "multiselect_op",  "distinct",    
123748   "selcollist",    "from",          "where_opt",     "groupby_opt", 
123749   "having_opt",    "orderby_opt",   "limit_opt",     "values",      
123750   "nexprlist",     "exprlist",      "sclp",          "as",          
123751   "seltablist",    "stl_prefix",    "joinop",        "indexed_opt", 
123752   "on_opt",        "using_opt",     "joinop2",       "idlist",      
123753   "sortlist",      "setlist",       "insert_cmd",    "inscollist_opt",
123754   "likeop",        "between_op",    "in_op",         "case_operand",
123755   "case_exprlist",  "case_else",     "uniqueflag",    "collate",     
123756   "nmnum",         "trigger_decl",  "trigger_cmd_list",  "trigger_time",
123757   "trigger_event",  "foreach_clause",  "when_clause",   "trigger_cmd", 
123758   "trnm",          "tridxby",       "database_kw_opt",  "key_opt",     
123759   "add_column_fullname",  "kwcolumn_opt",  "create_vtab",   "vtabarglist", 
123760   "vtabarg",       "vtabargtoken",  "lp",            "anylist",     
123761   "wqlist",      
123762 };
123763 #endif /* NDEBUG */
123764
123765 #ifndef NDEBUG
123766 /* For tracing reduce actions, the names of all rules are required.
123767 */
123768 static const char *const yyRuleName[] = {
123769  /*   0 */ "input ::= cmdlist",
123770  /*   1 */ "cmdlist ::= cmdlist ecmd",
123771  /*   2 */ "cmdlist ::= ecmd",
123772  /*   3 */ "ecmd ::= SEMI",
123773  /*   4 */ "ecmd ::= explain cmdx SEMI",
123774  /*   5 */ "explain ::=",
123775  /*   6 */ "explain ::= EXPLAIN",
123776  /*   7 */ "explain ::= EXPLAIN QUERY PLAN",
123777  /*   8 */ "cmdx ::= cmd",
123778  /*   9 */ "cmd ::= BEGIN transtype trans_opt",
123779  /*  10 */ "trans_opt ::=",
123780  /*  11 */ "trans_opt ::= TRANSACTION",
123781  /*  12 */ "trans_opt ::= TRANSACTION nm",
123782  /*  13 */ "transtype ::=",
123783  /*  14 */ "transtype ::= DEFERRED",
123784  /*  15 */ "transtype ::= IMMEDIATE",
123785  /*  16 */ "transtype ::= EXCLUSIVE",
123786  /*  17 */ "cmd ::= COMMIT trans_opt",
123787  /*  18 */ "cmd ::= END trans_opt",
123788  /*  19 */ "cmd ::= ROLLBACK trans_opt",
123789  /*  20 */ "savepoint_opt ::= SAVEPOINT",
123790  /*  21 */ "savepoint_opt ::=",
123791  /*  22 */ "cmd ::= SAVEPOINT nm",
123792  /*  23 */ "cmd ::= RELEASE savepoint_opt nm",
123793  /*  24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
123794  /*  25 */ "cmd ::= create_table create_table_args",
123795  /*  26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
123796  /*  27 */ "createkw ::= CREATE",
123797  /*  28 */ "ifnotexists ::=",
123798  /*  29 */ "ifnotexists ::= IF NOT EXISTS",
123799  /*  30 */ "temp ::= TEMP",
123800  /*  31 */ "temp ::=",
123801  /*  32 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
123802  /*  33 */ "create_table_args ::= AS select",
123803  /*  34 */ "table_options ::=",
123804  /*  35 */ "table_options ::= WITHOUT nm",
123805  /*  36 */ "columnlist ::= columnlist COMMA column",
123806  /*  37 */ "columnlist ::= column",
123807  /*  38 */ "column ::= columnid type carglist",
123808  /*  39 */ "columnid ::= nm",
123809  /*  40 */ "nm ::= ID|INDEXED",
123810  /*  41 */ "nm ::= STRING",
123811  /*  42 */ "nm ::= JOIN_KW",
123812  /*  43 */ "type ::=",
123813  /*  44 */ "type ::= typetoken",
123814  /*  45 */ "typetoken ::= typename",
123815  /*  46 */ "typetoken ::= typename LP signed RP",
123816  /*  47 */ "typetoken ::= typename LP signed COMMA signed RP",
123817  /*  48 */ "typename ::= ID|STRING",
123818  /*  49 */ "typename ::= typename ID|STRING",
123819  /*  50 */ "signed ::= plus_num",
123820  /*  51 */ "signed ::= minus_num",
123821  /*  52 */ "carglist ::= carglist ccons",
123822  /*  53 */ "carglist ::=",
123823  /*  54 */ "ccons ::= CONSTRAINT nm",
123824  /*  55 */ "ccons ::= DEFAULT term",
123825  /*  56 */ "ccons ::= DEFAULT LP expr RP",
123826  /*  57 */ "ccons ::= DEFAULT PLUS term",
123827  /*  58 */ "ccons ::= DEFAULT MINUS term",
123828  /*  59 */ "ccons ::= DEFAULT ID|INDEXED",
123829  /*  60 */ "ccons ::= NULL onconf",
123830  /*  61 */ "ccons ::= NOT NULL onconf",
123831  /*  62 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
123832  /*  63 */ "ccons ::= UNIQUE onconf",
123833  /*  64 */ "ccons ::= CHECK LP expr RP",
123834  /*  65 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
123835  /*  66 */ "ccons ::= defer_subclause",
123836  /*  67 */ "ccons ::= COLLATE ID|STRING",
123837  /*  68 */ "autoinc ::=",
123838  /*  69 */ "autoinc ::= AUTOINCR",
123839  /*  70 */ "refargs ::=",
123840  /*  71 */ "refargs ::= refargs refarg",
123841  /*  72 */ "refarg ::= MATCH nm",
123842  /*  73 */ "refarg ::= ON INSERT refact",
123843  /*  74 */ "refarg ::= ON DELETE refact",
123844  /*  75 */ "refarg ::= ON UPDATE refact",
123845  /*  76 */ "refact ::= SET NULL",
123846  /*  77 */ "refact ::= SET DEFAULT",
123847  /*  78 */ "refact ::= CASCADE",
123848  /*  79 */ "refact ::= RESTRICT",
123849  /*  80 */ "refact ::= NO ACTION",
123850  /*  81 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
123851  /*  82 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
123852  /*  83 */ "init_deferred_pred_opt ::=",
123853  /*  84 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
123854  /*  85 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
123855  /*  86 */ "conslist_opt ::=",
123856  /*  87 */ "conslist_opt ::= COMMA conslist",
123857  /*  88 */ "conslist ::= conslist tconscomma tcons",
123858  /*  89 */ "conslist ::= tcons",
123859  /*  90 */ "tconscomma ::= COMMA",
123860  /*  91 */ "tconscomma ::=",
123861  /*  92 */ "tcons ::= CONSTRAINT nm",
123862  /*  93 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
123863  /*  94 */ "tcons ::= UNIQUE LP idxlist RP onconf",
123864  /*  95 */ "tcons ::= CHECK LP expr RP onconf",
123865  /*  96 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
123866  /*  97 */ "defer_subclause_opt ::=",
123867  /*  98 */ "defer_subclause_opt ::= defer_subclause",
123868  /*  99 */ "onconf ::=",
123869  /* 100 */ "onconf ::= ON CONFLICT resolvetype",
123870  /* 101 */ "orconf ::=",
123871  /* 102 */ "orconf ::= OR resolvetype",
123872  /* 103 */ "resolvetype ::= raisetype",
123873  /* 104 */ "resolvetype ::= IGNORE",
123874  /* 105 */ "resolvetype ::= REPLACE",
123875  /* 106 */ "cmd ::= DROP TABLE ifexists fullname",
123876  /* 107 */ "ifexists ::= IF EXISTS",
123877  /* 108 */ "ifexists ::=",
123878  /* 109 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
123879  /* 110 */ "cmd ::= DROP VIEW ifexists fullname",
123880  /* 111 */ "cmd ::= select",
123881  /* 112 */ "select ::= with selectnowith",
123882  /* 113 */ "selectnowith ::= oneselect",
123883  /* 114 */ "selectnowith ::= selectnowith multiselect_op oneselect",
123884  /* 115 */ "multiselect_op ::= UNION",
123885  /* 116 */ "multiselect_op ::= UNION ALL",
123886  /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
123887  /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
123888  /* 119 */ "oneselect ::= values",
123889  /* 120 */ "values ::= VALUES LP nexprlist RP",
123890  /* 121 */ "values ::= values COMMA LP exprlist RP",
123891  /* 122 */ "distinct ::= DISTINCT",
123892  /* 123 */ "distinct ::= ALL",
123893  /* 124 */ "distinct ::=",
123894  /* 125 */ "sclp ::= selcollist COMMA",
123895  /* 126 */ "sclp ::=",
123896  /* 127 */ "selcollist ::= sclp expr as",
123897  /* 128 */ "selcollist ::= sclp STAR",
123898  /* 129 */ "selcollist ::= sclp nm DOT STAR",
123899  /* 130 */ "as ::= AS nm",
123900  /* 131 */ "as ::= ID|STRING",
123901  /* 132 */ "as ::=",
123902  /* 133 */ "from ::=",
123903  /* 134 */ "from ::= FROM seltablist",
123904  /* 135 */ "stl_prefix ::= seltablist joinop",
123905  /* 136 */ "stl_prefix ::=",
123906  /* 137 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
123907  /* 138 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
123908  /* 139 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
123909  /* 140 */ "dbnm ::=",
123910  /* 141 */ "dbnm ::= DOT nm",
123911  /* 142 */ "fullname ::= nm dbnm",
123912  /* 143 */ "joinop ::= COMMA|JOIN",
123913  /* 144 */ "joinop ::= JOIN_KW JOIN",
123914  /* 145 */ "joinop ::= JOIN_KW nm JOIN",
123915  /* 146 */ "joinop ::= JOIN_KW nm nm JOIN",
123916  /* 147 */ "on_opt ::= ON expr",
123917  /* 148 */ "on_opt ::=",
123918  /* 149 */ "indexed_opt ::=",
123919  /* 150 */ "indexed_opt ::= INDEXED BY nm",
123920  /* 151 */ "indexed_opt ::= NOT INDEXED",
123921  /* 152 */ "using_opt ::= USING LP idlist RP",
123922  /* 153 */ "using_opt ::=",
123923  /* 154 */ "orderby_opt ::=",
123924  /* 155 */ "orderby_opt ::= ORDER BY sortlist",
123925  /* 156 */ "sortlist ::= sortlist COMMA expr sortorder",
123926  /* 157 */ "sortlist ::= expr sortorder",
123927  /* 158 */ "sortorder ::= ASC",
123928  /* 159 */ "sortorder ::= DESC",
123929  /* 160 */ "sortorder ::=",
123930  /* 161 */ "groupby_opt ::=",
123931  /* 162 */ "groupby_opt ::= GROUP BY nexprlist",
123932  /* 163 */ "having_opt ::=",
123933  /* 164 */ "having_opt ::= HAVING expr",
123934  /* 165 */ "limit_opt ::=",
123935  /* 166 */ "limit_opt ::= LIMIT expr",
123936  /* 167 */ "limit_opt ::= LIMIT expr OFFSET expr",
123937  /* 168 */ "limit_opt ::= LIMIT expr COMMA expr",
123938  /* 169 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
123939  /* 170 */ "where_opt ::=",
123940  /* 171 */ "where_opt ::= WHERE expr",
123941  /* 172 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
123942  /* 173 */ "setlist ::= setlist COMMA nm EQ expr",
123943  /* 174 */ "setlist ::= nm EQ expr",
123944  /* 175 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt select",
123945  /* 176 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
123946  /* 177 */ "insert_cmd ::= INSERT orconf",
123947  /* 178 */ "insert_cmd ::= REPLACE",
123948  /* 179 */ "inscollist_opt ::=",
123949  /* 180 */ "inscollist_opt ::= LP idlist RP",
123950  /* 181 */ "idlist ::= idlist COMMA nm",
123951  /* 182 */ "idlist ::= nm",
123952  /* 183 */ "expr ::= term",
123953  /* 184 */ "expr ::= LP expr RP",
123954  /* 185 */ "term ::= NULL",
123955  /* 186 */ "expr ::= ID|INDEXED",
123956  /* 187 */ "expr ::= JOIN_KW",
123957  /* 188 */ "expr ::= nm DOT nm",
123958  /* 189 */ "expr ::= nm DOT nm DOT nm",
123959  /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
123960  /* 191 */ "term ::= STRING",
123961  /* 192 */ "expr ::= VARIABLE",
123962  /* 193 */ "expr ::= expr COLLATE ID|STRING",
123963  /* 194 */ "expr ::= CAST LP expr AS typetoken RP",
123964  /* 195 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
123965  /* 196 */ "expr ::= ID|INDEXED LP STAR RP",
123966  /* 197 */ "term ::= CTIME_KW",
123967  /* 198 */ "expr ::= expr AND expr",
123968  /* 199 */ "expr ::= expr OR expr",
123969  /* 200 */ "expr ::= expr LT|GT|GE|LE expr",
123970  /* 201 */ "expr ::= expr EQ|NE expr",
123971  /* 202 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
123972  /* 203 */ "expr ::= expr PLUS|MINUS expr",
123973  /* 204 */ "expr ::= expr STAR|SLASH|REM expr",
123974  /* 205 */ "expr ::= expr CONCAT expr",
123975  /* 206 */ "likeop ::= LIKE_KW|MATCH",
123976  /* 207 */ "likeop ::= NOT LIKE_KW|MATCH",
123977  /* 208 */ "expr ::= expr likeop expr",
123978  /* 209 */ "expr ::= expr likeop expr ESCAPE expr",
123979  /* 210 */ "expr ::= expr ISNULL|NOTNULL",
123980  /* 211 */ "expr ::= expr NOT NULL",
123981  /* 212 */ "expr ::= expr IS expr",
123982  /* 213 */ "expr ::= expr IS NOT expr",
123983  /* 214 */ "expr ::= NOT expr",
123984  /* 215 */ "expr ::= BITNOT expr",
123985  /* 216 */ "expr ::= MINUS expr",
123986  /* 217 */ "expr ::= PLUS expr",
123987  /* 218 */ "between_op ::= BETWEEN",
123988  /* 219 */ "between_op ::= NOT BETWEEN",
123989  /* 220 */ "expr ::= expr between_op expr AND expr",
123990  /* 221 */ "in_op ::= IN",
123991  /* 222 */ "in_op ::= NOT IN",
123992  /* 223 */ "expr ::= expr in_op LP exprlist RP",
123993  /* 224 */ "expr ::= LP select RP",
123994  /* 225 */ "expr ::= expr in_op LP select RP",
123995  /* 226 */ "expr ::= expr in_op nm dbnm",
123996  /* 227 */ "expr ::= EXISTS LP select RP",
123997  /* 228 */ "expr ::= CASE case_operand case_exprlist case_else END",
123998  /* 229 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
123999  /* 230 */ "case_exprlist ::= WHEN expr THEN expr",
124000  /* 231 */ "case_else ::= ELSE expr",
124001  /* 232 */ "case_else ::=",
124002  /* 233 */ "case_operand ::= expr",
124003  /* 234 */ "case_operand ::=",
124004  /* 235 */ "exprlist ::= nexprlist",
124005  /* 236 */ "exprlist ::=",
124006  /* 237 */ "nexprlist ::= nexprlist COMMA expr",
124007  /* 238 */ "nexprlist ::= expr",
124008  /* 239 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt",
124009  /* 240 */ "uniqueflag ::= UNIQUE",
124010  /* 241 */ "uniqueflag ::=",
124011  /* 242 */ "idxlist_opt ::=",
124012  /* 243 */ "idxlist_opt ::= LP idxlist RP",
124013  /* 244 */ "idxlist ::= idxlist COMMA nm collate sortorder",
124014  /* 245 */ "idxlist ::= nm collate sortorder",
124015  /* 246 */ "collate ::=",
124016  /* 247 */ "collate ::= COLLATE ID|STRING",
124017  /* 248 */ "cmd ::= DROP INDEX ifexists fullname",
124018  /* 249 */ "cmd ::= VACUUM",
124019  /* 250 */ "cmd ::= VACUUM nm",
124020  /* 251 */ "cmd ::= PRAGMA nm dbnm",
124021  /* 252 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
124022  /* 253 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
124023  /* 254 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
124024  /* 255 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
124025  /* 256 */ "nmnum ::= plus_num",
124026  /* 257 */ "nmnum ::= nm",
124027  /* 258 */ "nmnum ::= ON",
124028  /* 259 */ "nmnum ::= DELETE",
124029  /* 260 */ "nmnum ::= DEFAULT",
124030  /* 261 */ "plus_num ::= PLUS INTEGER|FLOAT",
124031  /* 262 */ "plus_num ::= INTEGER|FLOAT",
124032  /* 263 */ "minus_num ::= MINUS INTEGER|FLOAT",
124033  /* 264 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
124034  /* 265 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
124035  /* 266 */ "trigger_time ::= BEFORE",
124036  /* 267 */ "trigger_time ::= AFTER",
124037  /* 268 */ "trigger_time ::= INSTEAD OF",
124038  /* 269 */ "trigger_time ::=",
124039  /* 270 */ "trigger_event ::= DELETE|INSERT",
124040  /* 271 */ "trigger_event ::= UPDATE",
124041  /* 272 */ "trigger_event ::= UPDATE OF idlist",
124042  /* 273 */ "foreach_clause ::=",
124043  /* 274 */ "foreach_clause ::= FOR EACH ROW",
124044  /* 275 */ "when_clause ::=",
124045  /* 276 */ "when_clause ::= WHEN expr",
124046  /* 277 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
124047  /* 278 */ "trigger_cmd_list ::= trigger_cmd SEMI",
124048  /* 279 */ "trnm ::= nm",
124049  /* 280 */ "trnm ::= nm DOT nm",
124050  /* 281 */ "tridxby ::=",
124051  /* 282 */ "tridxby ::= INDEXED BY nm",
124052  /* 283 */ "tridxby ::= NOT INDEXED",
124053  /* 284 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
124054  /* 285 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
124055  /* 286 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
124056  /* 287 */ "trigger_cmd ::= select",
124057  /* 288 */ "expr ::= RAISE LP IGNORE RP",
124058  /* 289 */ "expr ::= RAISE LP raisetype COMMA nm RP",
124059  /* 290 */ "raisetype ::= ROLLBACK",
124060  /* 291 */ "raisetype ::= ABORT",
124061  /* 292 */ "raisetype ::= FAIL",
124062  /* 293 */ "cmd ::= DROP TRIGGER ifexists fullname",
124063  /* 294 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
124064  /* 295 */ "cmd ::= DETACH database_kw_opt expr",
124065  /* 296 */ "key_opt ::=",
124066  /* 297 */ "key_opt ::= KEY expr",
124067  /* 298 */ "database_kw_opt ::= DATABASE",
124068  /* 299 */ "database_kw_opt ::=",
124069  /* 300 */ "cmd ::= REINDEX",
124070  /* 301 */ "cmd ::= REINDEX nm dbnm",
124071  /* 302 */ "cmd ::= ANALYZE",
124072  /* 303 */ "cmd ::= ANALYZE nm dbnm",
124073  /* 304 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
124074  /* 305 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
124075  /* 306 */ "add_column_fullname ::= fullname",
124076  /* 307 */ "kwcolumn_opt ::=",
124077  /* 308 */ "kwcolumn_opt ::= COLUMNKW",
124078  /* 309 */ "cmd ::= create_vtab",
124079  /* 310 */ "cmd ::= create_vtab LP vtabarglist RP",
124080  /* 311 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
124081  /* 312 */ "vtabarglist ::= vtabarg",
124082  /* 313 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
124083  /* 314 */ "vtabarg ::=",
124084  /* 315 */ "vtabarg ::= vtabarg vtabargtoken",
124085  /* 316 */ "vtabargtoken ::= ANY",
124086  /* 317 */ "vtabargtoken ::= lp anylist RP",
124087  /* 318 */ "lp ::= LP",
124088  /* 319 */ "anylist ::=",
124089  /* 320 */ "anylist ::= anylist LP anylist RP",
124090  /* 321 */ "anylist ::= anylist ANY",
124091  /* 322 */ "with ::=",
124092  /* 323 */ "with ::= WITH wqlist",
124093  /* 324 */ "with ::= WITH RECURSIVE wqlist",
124094  /* 325 */ "wqlist ::= nm idxlist_opt AS LP select RP",
124095  /* 326 */ "wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP",
124096 };
124097 #endif /* NDEBUG */
124098
124099
124100 #if YYSTACKDEPTH<=0
124101 /*
124102 ** Try to increase the size of the parser stack.
124103 */
124104 static void yyGrowStack(yyParser *p){
124105   int newSize;
124106   yyStackEntry *pNew;
124107
124108   newSize = p->yystksz*2 + 100;
124109   pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
124110   if( pNew ){
124111     p->yystack = pNew;
124112     p->yystksz = newSize;
124113 #ifndef NDEBUG
124114     if( yyTraceFILE ){
124115       fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
124116               yyTracePrompt, p->yystksz);
124117     }
124118 #endif
124119   }
124120 }
124121 #endif
124122
124123 /* 
124124 ** This function allocates a new parser.
124125 ** The only argument is a pointer to a function which works like
124126 ** malloc.
124127 **
124128 ** Inputs:
124129 ** A pointer to the function used to allocate memory.
124130 **
124131 ** Outputs:
124132 ** A pointer to a parser.  This pointer is used in subsequent calls
124133 ** to sqlite3Parser and sqlite3ParserFree.
124134 */
124135 SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(u64)){
124136   yyParser *pParser;
124137   pParser = (yyParser*)(*mallocProc)( (u64)sizeof(yyParser) );
124138   if( pParser ){
124139     pParser->yyidx = -1;
124140 #ifdef YYTRACKMAXSTACKDEPTH
124141     pParser->yyidxMax = 0;
124142 #endif
124143 #if YYSTACKDEPTH<=0
124144     pParser->yystack = NULL;
124145     pParser->yystksz = 0;
124146     yyGrowStack(pParser);
124147 #endif
124148   }
124149   return pParser;
124150 }
124151
124152 /* The following function deletes the value associated with a
124153 ** symbol.  The symbol can be either a terminal or nonterminal.
124154 ** "yymajor" is the symbol code, and "yypminor" is a pointer to
124155 ** the value.
124156 */
124157 static void yy_destructor(
124158   yyParser *yypParser,    /* The parser */
124159   YYCODETYPE yymajor,     /* Type code for object to destroy */
124160   YYMINORTYPE *yypminor   /* The object to be destroyed */
124161 ){
124162   sqlite3ParserARG_FETCH;
124163   switch( yymajor ){
124164     /* Here is inserted the actions which take place when a
124165     ** terminal or non-terminal is destroyed.  This can happen
124166     ** when the symbol is popped from the stack during a
124167     ** reduce or during error processing or when a parser is 
124168     ** being destroyed before it is finished parsing.
124169     **
124170     ** Note: during a reduce, the only symbols destroyed are those
124171     ** which appear on the RHS of the rule, but which are not used
124172     ** inside the C code.
124173     */
124174     case 163: /* select */
124175     case 195: /* selectnowith */
124176     case 196: /* oneselect */
124177     case 207: /* values */
124178 {
124179 sqlite3SelectDelete(pParse->db, (yypminor->yy3));
124180 }
124181       break;
124182     case 174: /* term */
124183     case 175: /* expr */
124184 {
124185 sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
124186 }
124187       break;
124188     case 179: /* idxlist_opt */
124189     case 188: /* idxlist */
124190     case 200: /* selcollist */
124191     case 203: /* groupby_opt */
124192     case 205: /* orderby_opt */
124193     case 208: /* nexprlist */
124194     case 209: /* exprlist */
124195     case 210: /* sclp */
124196     case 220: /* sortlist */
124197     case 221: /* setlist */
124198     case 228: /* case_exprlist */
124199 {
124200 sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
124201 }
124202       break;
124203     case 194: /* fullname */
124204     case 201: /* from */
124205     case 212: /* seltablist */
124206     case 213: /* stl_prefix */
124207 {
124208 sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
124209 }
124210       break;
124211     case 197: /* with */
124212     case 252: /* wqlist */
124213 {
124214 sqlite3WithDelete(pParse->db, (yypminor->yy59));
124215 }
124216       break;
124217     case 202: /* where_opt */
124218     case 204: /* having_opt */
124219     case 216: /* on_opt */
124220     case 227: /* case_operand */
124221     case 229: /* case_else */
124222     case 238: /* when_clause */
124223     case 243: /* key_opt */
124224 {
124225 sqlite3ExprDelete(pParse->db, (yypminor->yy132));
124226 }
124227       break;
124228     case 217: /* using_opt */
124229     case 219: /* idlist */
124230     case 223: /* inscollist_opt */
124231 {
124232 sqlite3IdListDelete(pParse->db, (yypminor->yy408));
124233 }
124234       break;
124235     case 234: /* trigger_cmd_list */
124236     case 239: /* trigger_cmd */
124237 {
124238 sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
124239 }
124240       break;
124241     case 236: /* trigger_event */
124242 {
124243 sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
124244 }
124245       break;
124246     default:  break;   /* If no destructor action specified: do nothing */
124247   }
124248 }
124249
124250 /*
124251 ** Pop the parser's stack once.
124252 **
124253 ** If there is a destructor routine associated with the token which
124254 ** is popped from the stack, then call it.
124255 **
124256 ** Return the major token number for the symbol popped.
124257 */
124258 static int yy_pop_parser_stack(yyParser *pParser){
124259   YYCODETYPE yymajor;
124260   yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
124261
124262   /* There is no mechanism by which the parser stack can be popped below
124263   ** empty in SQLite.  */
124264   if( NEVER(pParser->yyidx<0) ) return 0;
124265 #ifndef NDEBUG
124266   if( yyTraceFILE && pParser->yyidx>=0 ){
124267     fprintf(yyTraceFILE,"%sPopping %s\n",
124268       yyTracePrompt,
124269       yyTokenName[yytos->major]);
124270   }
124271 #endif
124272   yymajor = yytos->major;
124273   yy_destructor(pParser, yymajor, &yytos->minor);
124274   pParser->yyidx--;
124275   return yymajor;
124276 }
124277
124278 /* 
124279 ** Deallocate and destroy a parser.  Destructors are all called for
124280 ** all stack elements before shutting the parser down.
124281 **
124282 ** Inputs:
124283 ** <ul>
124284 ** <li>  A pointer to the parser.  This should be a pointer
124285 **       obtained from sqlite3ParserAlloc.
124286 ** <li>  A pointer to a function used to reclaim memory obtained
124287 **       from malloc.
124288 ** </ul>
124289 */
124290 SQLITE_PRIVATE void sqlite3ParserFree(
124291   void *p,                    /* The parser to be deleted */
124292   void (*freeProc)(void*)     /* Function used to reclaim memory */
124293 ){
124294   yyParser *pParser = (yyParser*)p;
124295   /* In SQLite, we never try to destroy a parser that was not successfully
124296   ** created in the first place. */
124297   if( NEVER(pParser==0) ) return;
124298   while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
124299 #if YYSTACKDEPTH<=0
124300   free(pParser->yystack);
124301 #endif
124302   (*freeProc)((void*)pParser);
124303 }
124304
124305 /*
124306 ** Return the peak depth of the stack for a parser.
124307 */
124308 #ifdef YYTRACKMAXSTACKDEPTH
124309 SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
124310   yyParser *pParser = (yyParser*)p;
124311   return pParser->yyidxMax;
124312 }
124313 #endif
124314
124315 /*
124316 ** Find the appropriate action for a parser given the terminal
124317 ** look-ahead token iLookAhead.
124318 **
124319 ** If the look-ahead token is YYNOCODE, then check to see if the action is
124320 ** independent of the look-ahead.  If it is, return the action, otherwise
124321 ** return YY_NO_ACTION.
124322 */
124323 static int yy_find_shift_action(
124324   yyParser *pParser,        /* The parser */
124325   YYCODETYPE iLookAhead     /* The look-ahead token */
124326 ){
124327   int i;
124328   int stateno = pParser->yystack[pParser->yyidx].stateno;
124329  
124330   if( stateno>YY_SHIFT_COUNT
124331    || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
124332     return yy_default[stateno];
124333   }
124334   assert( iLookAhead!=YYNOCODE );
124335   i += iLookAhead;
124336   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
124337     if( iLookAhead>0 ){
124338 #ifdef YYFALLBACK
124339       YYCODETYPE iFallback;            /* Fallback token */
124340       if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
124341              && (iFallback = yyFallback[iLookAhead])!=0 ){
124342 #ifndef NDEBUG
124343         if( yyTraceFILE ){
124344           fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
124345              yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
124346         }
124347 #endif
124348         return yy_find_shift_action(pParser, iFallback);
124349       }
124350 #endif
124351 #ifdef YYWILDCARD
124352       {
124353         int j = i - iLookAhead + YYWILDCARD;
124354         if( 
124355 #if YY_SHIFT_MIN+YYWILDCARD<0
124356           j>=0 &&
124357 #endif
124358 #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
124359           j<YY_ACTTAB_COUNT &&
124360 #endif
124361           yy_lookahead[j]==YYWILDCARD
124362         ){
124363 #ifndef NDEBUG
124364           if( yyTraceFILE ){
124365             fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
124366                yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
124367           }
124368 #endif /* NDEBUG */
124369           return yy_action[j];
124370         }
124371       }
124372 #endif /* YYWILDCARD */
124373     }
124374     return yy_default[stateno];
124375   }else{
124376     return yy_action[i];
124377   }
124378 }
124379
124380 /*
124381 ** Find the appropriate action for a parser given the non-terminal
124382 ** look-ahead token iLookAhead.
124383 **
124384 ** If the look-ahead token is YYNOCODE, then check to see if the action is
124385 ** independent of the look-ahead.  If it is, return the action, otherwise
124386 ** return YY_NO_ACTION.
124387 */
124388 static int yy_find_reduce_action(
124389   int stateno,              /* Current state number */
124390   YYCODETYPE iLookAhead     /* The look-ahead token */
124391 ){
124392   int i;
124393 #ifdef YYERRORSYMBOL
124394   if( stateno>YY_REDUCE_COUNT ){
124395     return yy_default[stateno];
124396   }
124397 #else
124398   assert( stateno<=YY_REDUCE_COUNT );
124399 #endif
124400   i = yy_reduce_ofst[stateno];
124401   assert( i!=YY_REDUCE_USE_DFLT );
124402   assert( iLookAhead!=YYNOCODE );
124403   i += iLookAhead;
124404 #ifdef YYERRORSYMBOL
124405   if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
124406     return yy_default[stateno];
124407   }
124408 #else
124409   assert( i>=0 && i<YY_ACTTAB_COUNT );
124410   assert( yy_lookahead[i]==iLookAhead );
124411 #endif
124412   return yy_action[i];
124413 }
124414
124415 /*
124416 ** The following routine is called if the stack overflows.
124417 */
124418 static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
124419    sqlite3ParserARG_FETCH;
124420    yypParser->yyidx--;
124421 #ifndef NDEBUG
124422    if( yyTraceFILE ){
124423      fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
124424    }
124425 #endif
124426    while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
124427    /* Here code is inserted which will execute if the parser
124428    ** stack every overflows */
124429
124430   UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
124431   sqlite3ErrorMsg(pParse, "parser stack overflow");
124432    sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
124433 }
124434
124435 /*
124436 ** Perform a shift action.
124437 */
124438 static void yy_shift(
124439   yyParser *yypParser,          /* The parser to be shifted */
124440   int yyNewState,               /* The new state to shift in */
124441   int yyMajor,                  /* The major token to shift in */
124442   YYMINORTYPE *yypMinor         /* Pointer to the minor token to shift in */
124443 ){
124444   yyStackEntry *yytos;
124445   yypParser->yyidx++;
124446 #ifdef YYTRACKMAXSTACKDEPTH
124447   if( yypParser->yyidx>yypParser->yyidxMax ){
124448     yypParser->yyidxMax = yypParser->yyidx;
124449   }
124450 #endif
124451 #if YYSTACKDEPTH>0 
124452   if( yypParser->yyidx>=YYSTACKDEPTH ){
124453     yyStackOverflow(yypParser, yypMinor);
124454     return;
124455   }
124456 #else
124457   if( yypParser->yyidx>=yypParser->yystksz ){
124458     yyGrowStack(yypParser);
124459     if( yypParser->yyidx>=yypParser->yystksz ){
124460       yyStackOverflow(yypParser, yypMinor);
124461       return;
124462     }
124463   }
124464 #endif
124465   yytos = &yypParser->yystack[yypParser->yyidx];
124466   yytos->stateno = (YYACTIONTYPE)yyNewState;
124467   yytos->major = (YYCODETYPE)yyMajor;
124468   yytos->minor = *yypMinor;
124469 #ifndef NDEBUG
124470   if( yyTraceFILE && yypParser->yyidx>0 ){
124471     int i;
124472     fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
124473     fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
124474     for(i=1; i<=yypParser->yyidx; i++)
124475       fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
124476     fprintf(yyTraceFILE,"\n");
124477   }
124478 #endif
124479 }
124480
124481 /* The following table contains information about every rule that
124482 ** is used during the reduce.
124483 */
124484 static const struct {
124485   YYCODETYPE lhs;         /* Symbol on the left-hand side of the rule */
124486   unsigned char nrhs;     /* Number of right-hand side symbols in the rule */
124487 } yyRuleInfo[] = {
124488   { 144, 1 },
124489   { 145, 2 },
124490   { 145, 1 },
124491   { 146, 1 },
124492   { 146, 3 },
124493   { 147, 0 },
124494   { 147, 1 },
124495   { 147, 3 },
124496   { 148, 1 },
124497   { 149, 3 },
124498   { 151, 0 },
124499   { 151, 1 },
124500   { 151, 2 },
124501   { 150, 0 },
124502   { 150, 1 },
124503   { 150, 1 },
124504   { 150, 1 },
124505   { 149, 2 },
124506   { 149, 2 },
124507   { 149, 2 },
124508   { 153, 1 },
124509   { 153, 0 },
124510   { 149, 2 },
124511   { 149, 3 },
124512   { 149, 5 },
124513   { 149, 2 },
124514   { 154, 6 },
124515   { 156, 1 },
124516   { 158, 0 },
124517   { 158, 3 },
124518   { 157, 1 },
124519   { 157, 0 },
124520   { 155, 5 },
124521   { 155, 2 },
124522   { 162, 0 },
124523   { 162, 2 },
124524   { 160, 3 },
124525   { 160, 1 },
124526   { 164, 3 },
124527   { 165, 1 },
124528   { 152, 1 },
124529   { 152, 1 },
124530   { 152, 1 },
124531   { 166, 0 },
124532   { 166, 1 },
124533   { 168, 1 },
124534   { 168, 4 },
124535   { 168, 6 },
124536   { 169, 1 },
124537   { 169, 2 },
124538   { 170, 1 },
124539   { 170, 1 },
124540   { 167, 2 },
124541   { 167, 0 },
124542   { 173, 2 },
124543   { 173, 2 },
124544   { 173, 4 },
124545   { 173, 3 },
124546   { 173, 3 },
124547   { 173, 2 },
124548   { 173, 2 },
124549   { 173, 3 },
124550   { 173, 5 },
124551   { 173, 2 },
124552   { 173, 4 },
124553   { 173, 4 },
124554   { 173, 1 },
124555   { 173, 2 },
124556   { 178, 0 },
124557   { 178, 1 },
124558   { 180, 0 },
124559   { 180, 2 },
124560   { 182, 2 },
124561   { 182, 3 },
124562   { 182, 3 },
124563   { 182, 3 },
124564   { 183, 2 },
124565   { 183, 2 },
124566   { 183, 1 },
124567   { 183, 1 },
124568   { 183, 2 },
124569   { 181, 3 },
124570   { 181, 2 },
124571   { 184, 0 },
124572   { 184, 2 },
124573   { 184, 2 },
124574   { 161, 0 },
124575   { 161, 2 },
124576   { 185, 3 },
124577   { 185, 1 },
124578   { 186, 1 },
124579   { 186, 0 },
124580   { 187, 2 },
124581   { 187, 7 },
124582   { 187, 5 },
124583   { 187, 5 },
124584   { 187, 10 },
124585   { 189, 0 },
124586   { 189, 1 },
124587   { 176, 0 },
124588   { 176, 3 },
124589   { 190, 0 },
124590   { 190, 2 },
124591   { 191, 1 },
124592   { 191, 1 },
124593   { 191, 1 },
124594   { 149, 4 },
124595   { 193, 2 },
124596   { 193, 0 },
124597   { 149, 8 },
124598   { 149, 4 },
124599   { 149, 1 },
124600   { 163, 2 },
124601   { 195, 1 },
124602   { 195, 3 },
124603   { 198, 1 },
124604   { 198, 2 },
124605   { 198, 1 },
124606   { 196, 9 },
124607   { 196, 1 },
124608   { 207, 4 },
124609   { 207, 5 },
124610   { 199, 1 },
124611   { 199, 1 },
124612   { 199, 0 },
124613   { 210, 2 },
124614   { 210, 0 },
124615   { 200, 3 },
124616   { 200, 2 },
124617   { 200, 4 },
124618   { 211, 2 },
124619   { 211, 1 },
124620   { 211, 0 },
124621   { 201, 0 },
124622   { 201, 2 },
124623   { 213, 2 },
124624   { 213, 0 },
124625   { 212, 7 },
124626   { 212, 7 },
124627   { 212, 7 },
124628   { 159, 0 },
124629   { 159, 2 },
124630   { 194, 2 },
124631   { 214, 1 },
124632   { 214, 2 },
124633   { 214, 3 },
124634   { 214, 4 },
124635   { 216, 2 },
124636   { 216, 0 },
124637   { 215, 0 },
124638   { 215, 3 },
124639   { 215, 2 },
124640   { 217, 4 },
124641   { 217, 0 },
124642   { 205, 0 },
124643   { 205, 3 },
124644   { 220, 4 },
124645   { 220, 2 },
124646   { 177, 1 },
124647   { 177, 1 },
124648   { 177, 0 },
124649   { 203, 0 },
124650   { 203, 3 },
124651   { 204, 0 },
124652   { 204, 2 },
124653   { 206, 0 },
124654   { 206, 2 },
124655   { 206, 4 },
124656   { 206, 4 },
124657   { 149, 6 },
124658   { 202, 0 },
124659   { 202, 2 },
124660   { 149, 8 },
124661   { 221, 5 },
124662   { 221, 3 },
124663   { 149, 6 },
124664   { 149, 7 },
124665   { 222, 2 },
124666   { 222, 1 },
124667   { 223, 0 },
124668   { 223, 3 },
124669   { 219, 3 },
124670   { 219, 1 },
124671   { 175, 1 },
124672   { 175, 3 },
124673   { 174, 1 },
124674   { 175, 1 },
124675   { 175, 1 },
124676   { 175, 3 },
124677   { 175, 5 },
124678   { 174, 1 },
124679   { 174, 1 },
124680   { 175, 1 },
124681   { 175, 3 },
124682   { 175, 6 },
124683   { 175, 5 },
124684   { 175, 4 },
124685   { 174, 1 },
124686   { 175, 3 },
124687   { 175, 3 },
124688   { 175, 3 },
124689   { 175, 3 },
124690   { 175, 3 },
124691   { 175, 3 },
124692   { 175, 3 },
124693   { 175, 3 },
124694   { 224, 1 },
124695   { 224, 2 },
124696   { 175, 3 },
124697   { 175, 5 },
124698   { 175, 2 },
124699   { 175, 3 },
124700   { 175, 3 },
124701   { 175, 4 },
124702   { 175, 2 },
124703   { 175, 2 },
124704   { 175, 2 },
124705   { 175, 2 },
124706   { 225, 1 },
124707   { 225, 2 },
124708   { 175, 5 },
124709   { 226, 1 },
124710   { 226, 2 },
124711   { 175, 5 },
124712   { 175, 3 },
124713   { 175, 5 },
124714   { 175, 4 },
124715   { 175, 4 },
124716   { 175, 5 },
124717   { 228, 5 },
124718   { 228, 4 },
124719   { 229, 2 },
124720   { 229, 0 },
124721   { 227, 1 },
124722   { 227, 0 },
124723   { 209, 1 },
124724   { 209, 0 },
124725   { 208, 3 },
124726   { 208, 1 },
124727   { 149, 12 },
124728   { 230, 1 },
124729   { 230, 0 },
124730   { 179, 0 },
124731   { 179, 3 },
124732   { 188, 5 },
124733   { 188, 3 },
124734   { 231, 0 },
124735   { 231, 2 },
124736   { 149, 4 },
124737   { 149, 1 },
124738   { 149, 2 },
124739   { 149, 3 },
124740   { 149, 5 },
124741   { 149, 6 },
124742   { 149, 5 },
124743   { 149, 6 },
124744   { 232, 1 },
124745   { 232, 1 },
124746   { 232, 1 },
124747   { 232, 1 },
124748   { 232, 1 },
124749   { 171, 2 },
124750   { 171, 1 },
124751   { 172, 2 },
124752   { 149, 5 },
124753   { 233, 11 },
124754   { 235, 1 },
124755   { 235, 1 },
124756   { 235, 2 },
124757   { 235, 0 },
124758   { 236, 1 },
124759   { 236, 1 },
124760   { 236, 3 },
124761   { 237, 0 },
124762   { 237, 3 },
124763   { 238, 0 },
124764   { 238, 2 },
124765   { 234, 3 },
124766   { 234, 2 },
124767   { 240, 1 },
124768   { 240, 3 },
124769   { 241, 0 },
124770   { 241, 3 },
124771   { 241, 2 },
124772   { 239, 7 },
124773   { 239, 5 },
124774   { 239, 5 },
124775   { 239, 1 },
124776   { 175, 4 },
124777   { 175, 6 },
124778   { 192, 1 },
124779   { 192, 1 },
124780   { 192, 1 },
124781   { 149, 4 },
124782   { 149, 6 },
124783   { 149, 3 },
124784   { 243, 0 },
124785   { 243, 2 },
124786   { 242, 1 },
124787   { 242, 0 },
124788   { 149, 1 },
124789   { 149, 3 },
124790   { 149, 1 },
124791   { 149, 3 },
124792   { 149, 6 },
124793   { 149, 6 },
124794   { 244, 1 },
124795   { 245, 0 },
124796   { 245, 1 },
124797   { 149, 1 },
124798   { 149, 4 },
124799   { 246, 8 },
124800   { 247, 1 },
124801   { 247, 3 },
124802   { 248, 0 },
124803   { 248, 2 },
124804   { 249, 1 },
124805   { 249, 3 },
124806   { 250, 1 },
124807   { 251, 0 },
124808   { 251, 4 },
124809   { 251, 2 },
124810   { 197, 0 },
124811   { 197, 2 },
124812   { 197, 3 },
124813   { 252, 6 },
124814   { 252, 8 },
124815 };
124816
124817 static void yy_accept(yyParser*);  /* Forward Declaration */
124818
124819 /*
124820 ** Perform a reduce action and the shift that must immediately
124821 ** follow the reduce.
124822 */
124823 static void yy_reduce(
124824   yyParser *yypParser,         /* The parser */
124825   int yyruleno                 /* Number of the rule by which to reduce */
124826 ){
124827   int yygoto;                     /* The next state */
124828   int yyact;                      /* The next action */
124829   YYMINORTYPE yygotominor;        /* The LHS of the rule reduced */
124830   yyStackEntry *yymsp;            /* The top of the parser's stack */
124831   int yysize;                     /* Amount to pop the stack */
124832   sqlite3ParserARG_FETCH;
124833   yymsp = &yypParser->yystack[yypParser->yyidx];
124834 #ifndef NDEBUG
124835   if( yyTraceFILE && yyruleno>=0 
124836         && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
124837     fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
124838       yyRuleName[yyruleno]);
124839   }
124840 #endif /* NDEBUG */
124841
124842   /* Silence complaints from purify about yygotominor being uninitialized
124843   ** in some cases when it is copied into the stack after the following
124844   ** switch.  yygotominor is uninitialized when a rule reduces that does
124845   ** not set the value of its left-hand side nonterminal.  Leaving the
124846   ** value of the nonterminal uninitialized is utterly harmless as long
124847   ** as the value is never used.  So really the only thing this code
124848   ** accomplishes is to quieten purify.  
124849   **
124850   ** 2007-01-16:  The wireshark project (www.wireshark.org) reports that
124851   ** without this code, their parser segfaults.  I'm not sure what there
124852   ** parser is doing to make this happen.  This is the second bug report
124853   ** from wireshark this week.  Clearly they are stressing Lemon in ways
124854   ** that it has not been previously stressed...  (SQLite ticket #2172)
124855   */
124856   /*memset(&yygotominor, 0, sizeof(yygotominor));*/
124857   yygotominor = yyzerominor;
124858
124859
124860   switch( yyruleno ){
124861   /* Beginning here are the reduction cases.  A typical example
124862   ** follows:
124863   **   case 0:
124864   **  #line <lineno> <grammarfile>
124865   **     { ... }           // User supplied code
124866   **  #line <lineno> <thisfile>
124867   **     break;
124868   */
124869       case 5: /* explain ::= */
124870 { sqlite3BeginParse(pParse, 0); }
124871         break;
124872       case 6: /* explain ::= EXPLAIN */
124873 { sqlite3BeginParse(pParse, 1); }
124874         break;
124875       case 7: /* explain ::= EXPLAIN QUERY PLAN */
124876 { sqlite3BeginParse(pParse, 2); }
124877         break;
124878       case 8: /* cmdx ::= cmd */
124879 { sqlite3FinishCoding(pParse); }
124880         break;
124881       case 9: /* cmd ::= BEGIN transtype trans_opt */
124882 {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
124883         break;
124884       case 13: /* transtype ::= */
124885 {yygotominor.yy328 = TK_DEFERRED;}
124886         break;
124887       case 14: /* transtype ::= DEFERRED */
124888       case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
124889       case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
124890       case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
124891       case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
124892 {yygotominor.yy328 = yymsp[0].major;}
124893         break;
124894       case 17: /* cmd ::= COMMIT trans_opt */
124895       case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
124896 {sqlite3CommitTransaction(pParse);}
124897         break;
124898       case 19: /* cmd ::= ROLLBACK trans_opt */
124899 {sqlite3RollbackTransaction(pParse);}
124900         break;
124901       case 22: /* cmd ::= SAVEPOINT nm */
124902 {
124903   sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
124904 }
124905         break;
124906       case 23: /* cmd ::= RELEASE savepoint_opt nm */
124907 {
124908   sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
124909 }
124910         break;
124911       case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
124912 {
124913   sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
124914 }
124915         break;
124916       case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
124917 {
124918    sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
124919 }
124920         break;
124921       case 27: /* createkw ::= CREATE */
124922 {
124923   pParse->db->lookaside.bEnabled = 0;
124924   yygotominor.yy0 = yymsp[0].minor.yy0;
124925 }
124926         break;
124927       case 28: /* ifnotexists ::= */
124928       case 31: /* temp ::= */ yytestcase(yyruleno==31);
124929       case 68: /* autoinc ::= */ yytestcase(yyruleno==68);
124930       case 81: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==81);
124931       case 83: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==83);
124932       case 85: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==85);
124933       case 97: /* defer_subclause_opt ::= */ yytestcase(yyruleno==97);
124934       case 108: /* ifexists ::= */ yytestcase(yyruleno==108);
124935       case 218: /* between_op ::= BETWEEN */ yytestcase(yyruleno==218);
124936       case 221: /* in_op ::= IN */ yytestcase(yyruleno==221);
124937 {yygotominor.yy328 = 0;}
124938         break;
124939       case 29: /* ifnotexists ::= IF NOT EXISTS */
124940       case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
124941       case 69: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==69);
124942       case 84: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==84);
124943       case 107: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==107);
124944       case 219: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==219);
124945       case 222: /* in_op ::= NOT IN */ yytestcase(yyruleno==222);
124946 {yygotominor.yy328 = 1;}
124947         break;
124948       case 32: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
124949 {
124950   sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy186,0);
124951 }
124952         break;
124953       case 33: /* create_table_args ::= AS select */
124954 {
124955   sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy3);
124956   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
124957 }
124958         break;
124959       case 34: /* table_options ::= */
124960 {yygotominor.yy186 = 0;}
124961         break;
124962       case 35: /* table_options ::= WITHOUT nm */
124963 {
124964   if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
124965     yygotominor.yy186 = TF_WithoutRowid;
124966   }else{
124967     yygotominor.yy186 = 0;
124968     sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
124969   }
124970 }
124971         break;
124972       case 38: /* column ::= columnid type carglist */
124973 {
124974   yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
124975   yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
124976 }
124977         break;
124978       case 39: /* columnid ::= nm */
124979 {
124980   sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
124981   yygotominor.yy0 = yymsp[0].minor.yy0;
124982   pParse->constraintName.n = 0;
124983 }
124984         break;
124985       case 40: /* nm ::= ID|INDEXED */
124986       case 41: /* nm ::= STRING */ yytestcase(yyruleno==41);
124987       case 42: /* nm ::= JOIN_KW */ yytestcase(yyruleno==42);
124988       case 45: /* typetoken ::= typename */ yytestcase(yyruleno==45);
124989       case 48: /* typename ::= ID|STRING */ yytestcase(yyruleno==48);
124990       case 130: /* as ::= AS nm */ yytestcase(yyruleno==130);
124991       case 131: /* as ::= ID|STRING */ yytestcase(yyruleno==131);
124992       case 141: /* dbnm ::= DOT nm */ yytestcase(yyruleno==141);
124993       case 150: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==150);
124994       case 247: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==247);
124995       case 256: /* nmnum ::= plus_num */ yytestcase(yyruleno==256);
124996       case 257: /* nmnum ::= nm */ yytestcase(yyruleno==257);
124997       case 258: /* nmnum ::= ON */ yytestcase(yyruleno==258);
124998       case 259: /* nmnum ::= DELETE */ yytestcase(yyruleno==259);
124999       case 260: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==260);
125000       case 261: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==261);
125001       case 262: /* plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==262);
125002       case 263: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==263);
125003       case 279: /* trnm ::= nm */ yytestcase(yyruleno==279);
125004 {yygotominor.yy0 = yymsp[0].minor.yy0;}
125005         break;
125006       case 44: /* type ::= typetoken */
125007 {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
125008         break;
125009       case 46: /* typetoken ::= typename LP signed RP */
125010 {
125011   yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
125012   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
125013 }
125014         break;
125015       case 47: /* typetoken ::= typename LP signed COMMA signed RP */
125016 {
125017   yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
125018   yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
125019 }
125020         break;
125021       case 49: /* typename ::= typename ID|STRING */
125022 {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);}
125023         break;
125024       case 54: /* ccons ::= CONSTRAINT nm */
125025       case 92: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==92);
125026 {pParse->constraintName = yymsp[0].minor.yy0;}
125027         break;
125028       case 55: /* ccons ::= DEFAULT term */
125029       case 57: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==57);
125030 {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
125031         break;
125032       case 56: /* ccons ::= DEFAULT LP expr RP */
125033 {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
125034         break;
125035       case 58: /* ccons ::= DEFAULT MINUS term */
125036 {
125037   ExprSpan v;
125038   v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
125039   v.zStart = yymsp[-1].minor.yy0.z;
125040   v.zEnd = yymsp[0].minor.yy346.zEnd;
125041   sqlite3AddDefaultValue(pParse,&v);
125042 }
125043         break;
125044       case 59: /* ccons ::= DEFAULT ID|INDEXED */
125045 {
125046   ExprSpan v;
125047   spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
125048   sqlite3AddDefaultValue(pParse,&v);
125049 }
125050         break;
125051       case 61: /* ccons ::= NOT NULL onconf */
125052 {sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
125053         break;
125054       case 62: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
125055 {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
125056         break;
125057       case 63: /* ccons ::= UNIQUE onconf */
125058 {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
125059         break;
125060       case 64: /* ccons ::= CHECK LP expr RP */
125061 {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
125062         break;
125063       case 65: /* ccons ::= REFERENCES nm idxlist_opt refargs */
125064 {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
125065         break;
125066       case 66: /* ccons ::= defer_subclause */
125067 {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
125068         break;
125069       case 67: /* ccons ::= COLLATE ID|STRING */
125070 {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
125071         break;
125072       case 70: /* refargs ::= */
125073 { yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
125074         break;
125075       case 71: /* refargs ::= refargs refarg */
125076 { yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
125077         break;
125078       case 72: /* refarg ::= MATCH nm */
125079       case 73: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==73);
125080 { yygotominor.yy429.value = 0;     yygotominor.yy429.mask = 0x000000; }
125081         break;
125082       case 74: /* refarg ::= ON DELETE refact */
125083 { yygotominor.yy429.value = yymsp[0].minor.yy328;     yygotominor.yy429.mask = 0x0000ff; }
125084         break;
125085       case 75: /* refarg ::= ON UPDATE refact */
125086 { yygotominor.yy429.value = yymsp[0].minor.yy328<<8;  yygotominor.yy429.mask = 0x00ff00; }
125087         break;
125088       case 76: /* refact ::= SET NULL */
125089 { yygotominor.yy328 = OE_SetNull;  /* EV: R-33326-45252 */}
125090         break;
125091       case 77: /* refact ::= SET DEFAULT */
125092 { yygotominor.yy328 = OE_SetDflt;  /* EV: R-33326-45252 */}
125093         break;
125094       case 78: /* refact ::= CASCADE */
125095 { yygotominor.yy328 = OE_Cascade;  /* EV: R-33326-45252 */}
125096         break;
125097       case 79: /* refact ::= RESTRICT */
125098 { yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
125099         break;
125100       case 80: /* refact ::= NO ACTION */
125101 { yygotominor.yy328 = OE_None;     /* EV: R-33326-45252 */}
125102         break;
125103       case 82: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
125104       case 98: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==98);
125105       case 100: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==100);
125106       case 103: /* resolvetype ::= raisetype */ yytestcase(yyruleno==103);
125107 {yygotominor.yy328 = yymsp[0].minor.yy328;}
125108         break;
125109       case 86: /* conslist_opt ::= */
125110 {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
125111         break;
125112       case 87: /* conslist_opt ::= COMMA conslist */
125113 {yygotominor.yy0 = yymsp[-1].minor.yy0;}
125114         break;
125115       case 90: /* tconscomma ::= COMMA */
125116 {pParse->constraintName.n = 0;}
125117         break;
125118       case 93: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
125119 {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
125120         break;
125121       case 94: /* tcons ::= UNIQUE LP idxlist RP onconf */
125122 {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
125123         break;
125124       case 95: /* tcons ::= CHECK LP expr RP onconf */
125125 {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
125126         break;
125127       case 96: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
125128 {
125129     sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
125130     sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
125131 }
125132         break;
125133       case 99: /* onconf ::= */
125134 {yygotominor.yy328 = OE_Default;}
125135         break;
125136       case 101: /* orconf ::= */
125137 {yygotominor.yy186 = OE_Default;}
125138         break;
125139       case 102: /* orconf ::= OR resolvetype */
125140 {yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
125141         break;
125142       case 104: /* resolvetype ::= IGNORE */
125143 {yygotominor.yy328 = OE_Ignore;}
125144         break;
125145       case 105: /* resolvetype ::= REPLACE */
125146 {yygotominor.yy328 = OE_Replace;}
125147         break;
125148       case 106: /* cmd ::= DROP TABLE ifexists fullname */
125149 {
125150   sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
125151 }
125152         break;
125153       case 109: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
125154 {
125155   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);
125156 }
125157         break;
125158       case 110: /* cmd ::= DROP VIEW ifexists fullname */
125159 {
125160   sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
125161 }
125162         break;
125163       case 111: /* cmd ::= select */
125164 {
125165   SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
125166   sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
125167   sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
125168 }
125169         break;
125170       case 112: /* select ::= with selectnowith */
125171 {
125172   Select *p = yymsp[0].minor.yy3, *pNext, *pLoop;
125173   if( p ){
125174     int cnt = 0, mxSelect;
125175     p->pWith = yymsp[-1].minor.yy59;
125176     if( p->pPrior ){
125177       u16 allValues = SF_Values;
125178       pNext = 0;
125179       for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
125180         pLoop->pNext = pNext;
125181         pLoop->selFlags |= SF_Compound;
125182         allValues &= pLoop->selFlags;
125183       }
125184       if( allValues ){
125185         p->selFlags |= SF_AllValues;
125186       }else if(
125187         (mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT])>0
125188         && cnt>mxSelect
125189       ){
125190         sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
125191       }
125192     }
125193   }else{
125194     sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy59);
125195   }
125196   yygotominor.yy3 = p;
125197 }
125198         break;
125199       case 113: /* selectnowith ::= oneselect */
125200       case 119: /* oneselect ::= values */ yytestcase(yyruleno==119);
125201 {yygotominor.yy3 = yymsp[0].minor.yy3;}
125202         break;
125203       case 114: /* selectnowith ::= selectnowith multiselect_op oneselect */
125204 {
125205   Select *pRhs = yymsp[0].minor.yy3;
125206   if( pRhs && pRhs->pPrior ){
125207     SrcList *pFrom;
125208     Token x;
125209     x.n = 0;
125210     pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
125211     pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
125212   }
125213   if( pRhs ){
125214     pRhs->op = (u8)yymsp[-1].minor.yy328;
125215     pRhs->pPrior = yymsp[-2].minor.yy3;
125216     if( yymsp[-1].minor.yy328!=TK_ALL ) pParse->hasCompound = 1;
125217   }else{
125218     sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy3);
125219   }
125220   yygotominor.yy3 = pRhs;
125221 }
125222         break;
125223       case 116: /* multiselect_op ::= UNION ALL */
125224 {yygotominor.yy328 = TK_ALL;}
125225         break;
125226       case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
125227 {
125228   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.yy381,yymsp[0].minor.yy476.pLimit,yymsp[0].minor.yy476.pOffset);
125229 #if SELECTTRACE_ENABLED
125230   /* Populate the Select.zSelName[] string that is used to help with
125231   ** query planner debugging, to differentiate between multiple Select
125232   ** objects in a complex query.
125233   **
125234   ** If the SELECT keyword is immediately followed by a C-style comment
125235   ** then extract the first few alphanumeric characters from within that
125236   ** comment to be the zSelName value.  Otherwise, the label is #N where
125237   ** is an integer that is incremented with each SELECT statement seen.
125238   */
125239   if( yygotominor.yy3!=0 ){
125240     const char *z = yymsp[-8].minor.yy0.z+6;
125241     int i;
125242     sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "#%d",
125243                      ++pParse->nSelect);
125244     while( z[0]==' ' ) z++;
125245     if( z[0]=='/' && z[1]=='*' ){
125246       z += 2;
125247       while( z[0]==' ' ) z++;
125248       for(i=0; sqlite3Isalnum(z[i]); i++){}
125249       sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "%.*s", i, z);
125250     }
125251   }
125252 #endif /* SELECTRACE_ENABLED */
125253 }
125254         break;
125255       case 120: /* values ::= VALUES LP nexprlist RP */
125256 {
125257   yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
125258 }
125259         break;
125260       case 121: /* values ::= values COMMA LP exprlist RP */
125261 {
125262   Select *pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
125263   if( pRight ){
125264     pRight->op = TK_ALL;
125265     pRight->pPrior = yymsp[-4].minor.yy3;
125266     yygotominor.yy3 = pRight;
125267   }else{
125268     yygotominor.yy3 = yymsp[-4].minor.yy3;
125269   }
125270 }
125271         break;
125272       case 122: /* distinct ::= DISTINCT */
125273 {yygotominor.yy381 = SF_Distinct;}
125274         break;
125275       case 123: /* distinct ::= ALL */
125276       case 124: /* distinct ::= */ yytestcase(yyruleno==124);
125277 {yygotominor.yy381 = 0;}
125278         break;
125279       case 125: /* sclp ::= selcollist COMMA */
125280       case 243: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==243);
125281 {yygotominor.yy14 = yymsp[-1].minor.yy14;}
125282         break;
125283       case 126: /* sclp ::= */
125284       case 154: /* orderby_opt ::= */ yytestcase(yyruleno==154);
125285       case 161: /* groupby_opt ::= */ yytestcase(yyruleno==161);
125286       case 236: /* exprlist ::= */ yytestcase(yyruleno==236);
125287       case 242: /* idxlist_opt ::= */ yytestcase(yyruleno==242);
125288 {yygotominor.yy14 = 0;}
125289         break;
125290       case 127: /* selcollist ::= sclp expr as */
125291 {
125292    yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
125293    if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
125294    sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
125295 }
125296         break;
125297       case 128: /* selcollist ::= sclp STAR */
125298 {
125299   Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
125300   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
125301 }
125302         break;
125303       case 129: /* selcollist ::= sclp nm DOT STAR */
125304 {
125305   Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
125306   Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
125307   Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
125308   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
125309 }
125310         break;
125311       case 132: /* as ::= */
125312 {yygotominor.yy0.n = 0;}
125313         break;
125314       case 133: /* from ::= */
125315 {yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
125316         break;
125317       case 134: /* from ::= FROM seltablist */
125318 {
125319   yygotominor.yy65 = yymsp[0].minor.yy65;
125320   sqlite3SrcListShiftJoinType(yygotominor.yy65);
125321 }
125322         break;
125323       case 135: /* stl_prefix ::= seltablist joinop */
125324 {
125325    yygotominor.yy65 = yymsp[-1].minor.yy65;
125326    if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].jointype = (u8)yymsp[0].minor.yy328;
125327 }
125328         break;
125329       case 136: /* stl_prefix ::= */
125330 {yygotominor.yy65 = 0;}
125331         break;
125332       case 137: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
125333 {
125334   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);
125335   sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
125336 }
125337         break;
125338       case 138: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
125339 {
125340     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);
125341   }
125342         break;
125343       case 139: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
125344 {
125345     if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
125346       yygotominor.yy65 = yymsp[-4].minor.yy65;
125347     }else if( yymsp[-4].minor.yy65->nSrc==1 ){
125348       yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
125349       if( yygotominor.yy65 ){
125350         struct SrcList_item *pNew = &yygotominor.yy65->a[yygotominor.yy65->nSrc-1];
125351         struct SrcList_item *pOld = yymsp[-4].minor.yy65->a;
125352         pNew->zName = pOld->zName;
125353         pNew->zDatabase = pOld->zDatabase;
125354         pNew->pSelect = pOld->pSelect;
125355         pOld->zName = pOld->zDatabase = 0;
125356         pOld->pSelect = 0;
125357       }
125358       sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy65);
125359     }else{
125360       Select *pSubquery;
125361       sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
125362       pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,SF_NestedFrom,0,0);
125363       yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
125364     }
125365   }
125366         break;
125367       case 140: /* dbnm ::= */
125368       case 149: /* indexed_opt ::= */ yytestcase(yyruleno==149);
125369 {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
125370         break;
125371       case 142: /* fullname ::= nm dbnm */
125372 {yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
125373         break;
125374       case 143: /* joinop ::= COMMA|JOIN */
125375 { yygotominor.yy328 = JT_INNER; }
125376         break;
125377       case 144: /* joinop ::= JOIN_KW JOIN */
125378 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
125379         break;
125380       case 145: /* joinop ::= JOIN_KW nm JOIN */
125381 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
125382         break;
125383       case 146: /* joinop ::= JOIN_KW nm nm JOIN */
125384 { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
125385         break;
125386       case 147: /* on_opt ::= ON expr */
125387       case 164: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==164);
125388       case 171: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==171);
125389       case 231: /* case_else ::= ELSE expr */ yytestcase(yyruleno==231);
125390       case 233: /* case_operand ::= expr */ yytestcase(yyruleno==233);
125391 {yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
125392         break;
125393       case 148: /* on_opt ::= */
125394       case 163: /* having_opt ::= */ yytestcase(yyruleno==163);
125395       case 170: /* where_opt ::= */ yytestcase(yyruleno==170);
125396       case 232: /* case_else ::= */ yytestcase(yyruleno==232);
125397       case 234: /* case_operand ::= */ yytestcase(yyruleno==234);
125398 {yygotominor.yy132 = 0;}
125399         break;
125400       case 151: /* indexed_opt ::= NOT INDEXED */
125401 {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
125402         break;
125403       case 152: /* using_opt ::= USING LP idlist RP */
125404       case 180: /* inscollist_opt ::= LP idlist RP */ yytestcase(yyruleno==180);
125405 {yygotominor.yy408 = yymsp[-1].minor.yy408;}
125406         break;
125407       case 153: /* using_opt ::= */
125408       case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
125409 {yygotominor.yy408 = 0;}
125410         break;
125411       case 155: /* orderby_opt ::= ORDER BY sortlist */
125412       case 162: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==162);
125413       case 235: /* exprlist ::= nexprlist */ yytestcase(yyruleno==235);
125414 {yygotominor.yy14 = yymsp[0].minor.yy14;}
125415         break;
125416       case 156: /* sortlist ::= sortlist COMMA expr sortorder */
125417 {
125418   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy346.pExpr);
125419   if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
125420 }
125421         break;
125422       case 157: /* sortlist ::= expr sortorder */
125423 {
125424   yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy346.pExpr);
125425   if( yygotominor.yy14 && ALWAYS(yygotominor.yy14->a) ) yygotominor.yy14->a[0].sortOrder = (u8)yymsp[0].minor.yy328;
125426 }
125427         break;
125428       case 158: /* sortorder ::= ASC */
125429       case 160: /* sortorder ::= */ yytestcase(yyruleno==160);
125430 {yygotominor.yy328 = SQLITE_SO_ASC;}
125431         break;
125432       case 159: /* sortorder ::= DESC */
125433 {yygotominor.yy328 = SQLITE_SO_DESC;}
125434         break;
125435       case 165: /* limit_opt ::= */
125436 {yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
125437         break;
125438       case 166: /* limit_opt ::= LIMIT expr */
125439 {yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
125440         break;
125441       case 167: /* limit_opt ::= LIMIT expr OFFSET expr */
125442 {yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
125443         break;
125444       case 168: /* limit_opt ::= LIMIT expr COMMA expr */
125445 {yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
125446         break;
125447       case 169: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
125448 {
125449   sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
125450   sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
125451   sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
125452 }
125453         break;
125454       case 172: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
125455 {
125456   sqlite3WithPush(pParse, yymsp[-7].minor.yy59, 1);
125457   sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
125458   sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list"); 
125459   sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
125460 }
125461         break;
125462       case 173: /* setlist ::= setlist COMMA nm EQ expr */
125463 {
125464   yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
125465   sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
125466 }
125467         break;
125468       case 174: /* setlist ::= nm EQ expr */
125469 {
125470   yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
125471   sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
125472 }
125473         break;
125474       case 175: /* cmd ::= with insert_cmd INTO fullname inscollist_opt select */
125475 {
125476   sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
125477   sqlite3Insert(pParse, yymsp[-2].minor.yy65, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);
125478 }
125479         break;
125480       case 176: /* cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
125481 {
125482   sqlite3WithPush(pParse, yymsp[-6].minor.yy59, 1);
125483   sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);
125484 }
125485         break;
125486       case 177: /* insert_cmd ::= INSERT orconf */
125487 {yygotominor.yy186 = yymsp[0].minor.yy186;}
125488         break;
125489       case 178: /* insert_cmd ::= REPLACE */
125490 {yygotominor.yy186 = OE_Replace;}
125491         break;
125492       case 181: /* idlist ::= idlist COMMA nm */
125493 {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
125494         break;
125495       case 182: /* idlist ::= nm */
125496 {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
125497         break;
125498       case 183: /* expr ::= term */
125499 {yygotominor.yy346 = yymsp[0].minor.yy346;}
125500         break;
125501       case 184: /* expr ::= LP expr RP */
125502 {yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
125503         break;
125504       case 185: /* term ::= NULL */
125505       case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
125506       case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
125507 {spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
125508         break;
125509       case 186: /* expr ::= ID|INDEXED */
125510       case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
125511 {spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
125512         break;
125513       case 188: /* expr ::= nm DOT nm */
125514 {
125515   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
125516   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
125517   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
125518   spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
125519 }
125520         break;
125521       case 189: /* expr ::= nm DOT nm DOT nm */
125522 {
125523   Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
125524   Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
125525   Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
125526   Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
125527   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
125528   spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
125529 }
125530         break;
125531       case 192: /* expr ::= VARIABLE */
125532 {
125533   if( yymsp[0].minor.yy0.n>=2 && yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1]) ){
125534     /* When doing a nested parse, one can include terms in an expression
125535     ** that look like this:   #1 #2 ...  These terms refer to registers
125536     ** in the virtual machine.  #N is the N-th register. */
125537     if( pParse->nested==0 ){
125538       sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
125539       yygotominor.yy346.pExpr = 0;
125540     }else{
125541       yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
125542       if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
125543     }
125544   }else{
125545     spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
125546     sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
125547   }
125548   spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
125549 }
125550         break;
125551       case 193: /* expr ::= expr COLLATE ID|STRING */
125552 {
125553   yygotominor.yy346.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0, 1);
125554   yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
125555   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
125556 }
125557         break;
125558       case 194: /* expr ::= CAST LP expr AS typetoken RP */
125559 {
125560   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
125561   spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
125562 }
125563         break;
125564       case 195: /* expr ::= ID|INDEXED LP distinct exprlist RP */
125565 {
125566   if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
125567     sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
125568   }
125569   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
125570   spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
125571   if( yymsp[-2].minor.yy381 && yygotominor.yy346.pExpr ){
125572     yygotominor.yy346.pExpr->flags |= EP_Distinct;
125573   }
125574 }
125575         break;
125576       case 196: /* expr ::= ID|INDEXED LP STAR RP */
125577 {
125578   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
125579   spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
125580 }
125581         break;
125582       case 197: /* term ::= CTIME_KW */
125583 {
125584   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
125585   spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
125586 }
125587         break;
125588       case 198: /* expr ::= expr AND expr */
125589       case 199: /* expr ::= expr OR expr */ yytestcase(yyruleno==199);
125590       case 200: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==200);
125591       case 201: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==201);
125592       case 202: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==202);
125593       case 203: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==203);
125594       case 204: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==204);
125595       case 205: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==205);
125596 {spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
125597         break;
125598       case 206: /* likeop ::= LIKE_KW|MATCH */
125599 {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 0;}
125600         break;
125601       case 207: /* likeop ::= NOT LIKE_KW|MATCH */
125602 {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 1;}
125603         break;
125604       case 208: /* expr ::= expr likeop expr */
125605 {
125606   ExprList *pList;
125607   pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy346.pExpr);
125608   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy346.pExpr);
125609   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy96.eOperator);
125610   if( yymsp[-1].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
125611   yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
125612   yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
125613   if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
125614 }
125615         break;
125616       case 209: /* expr ::= expr likeop expr ESCAPE expr */
125617 {
125618   ExprList *pList;
125619   pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
125620   pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy346.pExpr);
125621   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
125622   yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy96.eOperator);
125623   if( yymsp[-3].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
125624   yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
125625   yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
125626   if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
125627 }
125628         break;
125629       case 210: /* expr ::= expr ISNULL|NOTNULL */
125630 {spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
125631         break;
125632       case 211: /* expr ::= expr NOT NULL */
125633 {spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
125634         break;
125635       case 212: /* expr ::= expr IS expr */
125636 {
125637   spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
125638   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
125639 }
125640         break;
125641       case 213: /* expr ::= expr IS NOT expr */
125642 {
125643   spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
125644   binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
125645 }
125646         break;
125647       case 214: /* expr ::= NOT expr */
125648       case 215: /* expr ::= BITNOT expr */ yytestcase(yyruleno==215);
125649 {spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
125650         break;
125651       case 216: /* expr ::= MINUS expr */
125652 {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
125653         break;
125654       case 217: /* expr ::= PLUS expr */
125655 {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
125656         break;
125657       case 220: /* expr ::= expr between_op expr AND expr */
125658 {
125659   ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
125660   pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
125661   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
125662   if( yygotominor.yy346.pExpr ){
125663     yygotominor.yy346.pExpr->x.pList = pList;
125664   }else{
125665     sqlite3ExprListDelete(pParse->db, pList);
125666   } 
125667   if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
125668   yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
125669   yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
125670 }
125671         break;
125672       case 223: /* expr ::= expr in_op LP exprlist RP */
125673 {
125674     if( yymsp[-1].minor.yy14==0 ){
125675       /* Expressions of the form
125676       **
125677       **      expr1 IN ()
125678       **      expr1 NOT IN ()
125679       **
125680       ** simplify to constants 0 (false) and 1 (true), respectively,
125681       ** regardless of the value of expr1.
125682       */
125683       yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy328]);
125684       sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy346.pExpr);
125685     }else if( yymsp[-1].minor.yy14->nExpr==1 ){
125686       /* Expressions of the form:
125687       **
125688       **      expr1 IN (?1)
125689       **      expr1 NOT IN (?2)
125690       **
125691       ** with exactly one value on the RHS can be simplified to something
125692       ** like this:
125693       **
125694       **      expr1 == ?1
125695       **      expr1 <> ?2
125696       **
125697       ** But, the RHS of the == or <> is marked with the EP_Generic flag
125698       ** so that it may not contribute to the computation of comparison
125699       ** affinity or the collating sequence to use for comparison.  Otherwise,
125700       ** the semantics would be subtly different from IN or NOT IN.
125701       */
125702       Expr *pRHS = yymsp[-1].minor.yy14->a[0].pExpr;
125703       yymsp[-1].minor.yy14->a[0].pExpr = 0;
125704       sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
125705       /* pRHS cannot be NULL because a malloc error would have been detected
125706       ** before now and control would have never reached this point */
125707       if( ALWAYS(pRHS) ){
125708         pRHS->flags &= ~EP_Collate;
125709         pRHS->flags |= EP_Generic;
125710       }
125711       yygotominor.yy346.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy328 ? TK_NE : TK_EQ, yymsp[-4].minor.yy346.pExpr, pRHS, 0);
125712     }else{
125713       yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
125714       if( yygotominor.yy346.pExpr ){
125715         yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
125716         sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
125717       }else{
125718         sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
125719       }
125720       if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
125721     }
125722     yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
125723     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
125724   }
125725         break;
125726       case 224: /* expr ::= LP select RP */
125727 {
125728     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
125729     if( yygotominor.yy346.pExpr ){
125730       yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
125731       ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect|EP_Subquery);
125732       sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
125733     }else{
125734       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
125735     }
125736     yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
125737     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
125738   }
125739         break;
125740       case 225: /* expr ::= expr in_op LP select RP */
125741 {
125742     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
125743     if( yygotominor.yy346.pExpr ){
125744       yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
125745       ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect|EP_Subquery);
125746       sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
125747     }else{
125748       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
125749     }
125750     if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
125751     yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
125752     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
125753   }
125754         break;
125755       case 226: /* expr ::= expr in_op nm dbnm */
125756 {
125757     SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
125758     yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
125759     if( yygotominor.yy346.pExpr ){
125760       yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
125761       ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect|EP_Subquery);
125762       sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
125763     }else{
125764       sqlite3SrcListDelete(pParse->db, pSrc);
125765     }
125766     if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
125767     yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
125768     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];
125769   }
125770         break;
125771       case 227: /* expr ::= EXISTS LP select RP */
125772 {
125773     Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
125774     if( p ){
125775       p->x.pSelect = yymsp[-1].minor.yy3;
125776       ExprSetProperty(p, EP_xIsSelect|EP_Subquery);
125777       sqlite3ExprSetHeightAndFlags(pParse, p);
125778     }else{
125779       sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
125780     }
125781     yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
125782     yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
125783   }
125784         break;
125785       case 228: /* expr ::= CASE case_operand case_exprlist case_else END */
125786 {
125787   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, 0, 0);
125788   if( yygotominor.yy346.pExpr ){
125789     yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy132 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[-1].minor.yy132) : yymsp[-2].minor.yy14;
125790     sqlite3ExprSetHeightAndFlags(pParse, yygotominor.yy346.pExpr);
125791   }else{
125792     sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
125793     sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy132);
125794   }
125795   yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
125796   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
125797 }
125798         break;
125799       case 229: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
125800 {
125801   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
125802   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
125803 }
125804         break;
125805       case 230: /* case_exprlist ::= WHEN expr THEN expr */
125806 {
125807   yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
125808   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
125809 }
125810         break;
125811       case 237: /* nexprlist ::= nexprlist COMMA expr */
125812 {yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
125813         break;
125814       case 238: /* nexprlist ::= expr */
125815 {yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
125816         break;
125817       case 239: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt */
125818 {
125819   sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, 
125820                      sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy14, yymsp[-10].minor.yy328,
125821                       &yymsp[-11].minor.yy0, yymsp[0].minor.yy132, SQLITE_SO_ASC, yymsp[-8].minor.yy328);
125822 }
125823         break;
125824       case 240: /* uniqueflag ::= UNIQUE */
125825       case 291: /* raisetype ::= ABORT */ yytestcase(yyruleno==291);
125826 {yygotominor.yy328 = OE_Abort;}
125827         break;
125828       case 241: /* uniqueflag ::= */
125829 {yygotominor.yy328 = OE_None;}
125830         break;
125831       case 244: /* idxlist ::= idxlist COMMA nm collate sortorder */
125832 {
125833   Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0, 1);
125834   yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, p);
125835   sqlite3ExprListSetName(pParse,yygotominor.yy14,&yymsp[-2].minor.yy0,1);
125836   sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
125837   if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
125838 }
125839         break;
125840       case 245: /* idxlist ::= nm collate sortorder */
125841 {
125842   Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0, 1);
125843   yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, p);
125844   sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
125845   sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
125846   if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
125847 }
125848         break;
125849       case 246: /* collate ::= */
125850 {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
125851         break;
125852       case 248: /* cmd ::= DROP INDEX ifexists fullname */
125853 {sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
125854         break;
125855       case 249: /* cmd ::= VACUUM */
125856       case 250: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==250);
125857 {sqlite3Vacuum(pParse);}
125858         break;
125859       case 251: /* cmd ::= PRAGMA nm dbnm */
125860 {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
125861         break;
125862       case 252: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
125863 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
125864         break;
125865       case 253: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
125866 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
125867         break;
125868       case 254: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
125869 {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
125870         break;
125871       case 255: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
125872 {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
125873         break;
125874       case 264: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
125875 {
125876   Token all;
125877   all.z = yymsp[-3].minor.yy0.z;
125878   all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
125879   sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
125880 }
125881         break;
125882       case 265: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
125883 {
125884   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);
125885   yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
125886 }
125887         break;
125888       case 266: /* trigger_time ::= BEFORE */
125889       case 269: /* trigger_time ::= */ yytestcase(yyruleno==269);
125890 { yygotominor.yy328 = TK_BEFORE; }
125891         break;
125892       case 267: /* trigger_time ::= AFTER */
125893 { yygotominor.yy328 = TK_AFTER;  }
125894         break;
125895       case 268: /* trigger_time ::= INSTEAD OF */
125896 { yygotominor.yy328 = TK_INSTEAD;}
125897         break;
125898       case 270: /* trigger_event ::= DELETE|INSERT */
125899       case 271: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==271);
125900 {yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
125901         break;
125902       case 272: /* trigger_event ::= UPDATE OF idlist */
125903 {yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
125904         break;
125905       case 275: /* when_clause ::= */
125906       case 296: /* key_opt ::= */ yytestcase(yyruleno==296);
125907 { yygotominor.yy132 = 0; }
125908         break;
125909       case 276: /* when_clause ::= WHEN expr */
125910       case 297: /* key_opt ::= KEY expr */ yytestcase(yyruleno==297);
125911 { yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
125912         break;
125913       case 277: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
125914 {
125915   assert( yymsp[-2].minor.yy473!=0 );
125916   yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
125917   yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
125918   yygotominor.yy473 = yymsp[-2].minor.yy473;
125919 }
125920         break;
125921       case 278: /* trigger_cmd_list ::= trigger_cmd SEMI */
125922
125923   assert( yymsp[-1].minor.yy473!=0 );
125924   yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
125925   yygotominor.yy473 = yymsp[-1].minor.yy473;
125926 }
125927         break;
125928       case 280: /* trnm ::= nm DOT nm */
125929 {
125930   yygotominor.yy0 = yymsp[0].minor.yy0;
125931   sqlite3ErrorMsg(pParse, 
125932         "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
125933         "statements within triggers");
125934 }
125935         break;
125936       case 282: /* tridxby ::= INDEXED BY nm */
125937 {
125938   sqlite3ErrorMsg(pParse,
125939         "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
125940         "within triggers");
125941 }
125942         break;
125943       case 283: /* tridxby ::= NOT INDEXED */
125944 {
125945   sqlite3ErrorMsg(pParse,
125946         "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
125947         "within triggers");
125948 }
125949         break;
125950       case 284: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
125951 { yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
125952         break;
125953       case 285: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
125954 {yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
125955         break;
125956       case 286: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
125957 {yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
125958         break;
125959       case 287: /* trigger_cmd ::= select */
125960 {yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
125961         break;
125962       case 288: /* expr ::= RAISE LP IGNORE RP */
125963 {
125964   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0); 
125965   if( yygotominor.yy346.pExpr ){
125966     yygotominor.yy346.pExpr->affinity = OE_Ignore;
125967   }
125968   yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
125969   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
125970 }
125971         break;
125972       case 289: /* expr ::= RAISE LP raisetype COMMA nm RP */
125973 {
125974   yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0); 
125975   if( yygotominor.yy346.pExpr ) {
125976     yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
125977   }
125978   yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
125979   yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
125980 }
125981         break;
125982       case 290: /* raisetype ::= ROLLBACK */
125983 {yygotominor.yy328 = OE_Rollback;}
125984         break;
125985       case 292: /* raisetype ::= FAIL */
125986 {yygotominor.yy328 = OE_Fail;}
125987         break;
125988       case 293: /* cmd ::= DROP TRIGGER ifexists fullname */
125989 {
125990   sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
125991 }
125992         break;
125993       case 294: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
125994 {
125995   sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
125996 }
125997         break;
125998       case 295: /* cmd ::= DETACH database_kw_opt expr */
125999 {
126000   sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
126001 }
126002         break;
126003       case 300: /* cmd ::= REINDEX */
126004 {sqlite3Reindex(pParse, 0, 0);}
126005         break;
126006       case 301: /* cmd ::= REINDEX nm dbnm */
126007 {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
126008         break;
126009       case 302: /* cmd ::= ANALYZE */
126010 {sqlite3Analyze(pParse, 0, 0);}
126011         break;
126012       case 303: /* cmd ::= ANALYZE nm dbnm */
126013 {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
126014         break;
126015       case 304: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
126016 {
126017   sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
126018 }
126019         break;
126020       case 305: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
126021 {
126022   sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
126023 }
126024         break;
126025       case 306: /* add_column_fullname ::= fullname */
126026 {
126027   pParse->db->lookaside.bEnabled = 0;
126028   sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
126029 }
126030         break;
126031       case 309: /* cmd ::= create_vtab */
126032 {sqlite3VtabFinishParse(pParse,0);}
126033         break;
126034       case 310: /* cmd ::= create_vtab LP vtabarglist RP */
126035 {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
126036         break;
126037       case 311: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
126038 {
126039     sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy328);
126040 }
126041         break;
126042       case 314: /* vtabarg ::= */
126043 {sqlite3VtabArgInit(pParse);}
126044         break;
126045       case 316: /* vtabargtoken ::= ANY */
126046       case 317: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==317);
126047       case 318: /* lp ::= LP */ yytestcase(yyruleno==318);
126048 {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
126049         break;
126050       case 322: /* with ::= */
126051 {yygotominor.yy59 = 0;}
126052         break;
126053       case 323: /* with ::= WITH wqlist */
126054       case 324: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==324);
126055 { yygotominor.yy59 = yymsp[0].minor.yy59; }
126056         break;
126057       case 325: /* wqlist ::= nm idxlist_opt AS LP select RP */
126058 {
126059   yygotominor.yy59 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
126060 }
126061         break;
126062       case 326: /* wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP */
126063 {
126064   yygotominor.yy59 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy59, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
126065 }
126066         break;
126067       default:
126068       /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
126069       /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
126070       /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
126071       /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
126072       /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
126073       /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
126074       /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
126075       /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
126076       /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
126077       /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
126078       /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
126079       /* (36) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==36);
126080       /* (37) columnlist ::= column */ yytestcase(yyruleno==37);
126081       /* (43) type ::= */ yytestcase(yyruleno==43);
126082       /* (50) signed ::= plus_num */ yytestcase(yyruleno==50);
126083       /* (51) signed ::= minus_num */ yytestcase(yyruleno==51);
126084       /* (52) carglist ::= carglist ccons */ yytestcase(yyruleno==52);
126085       /* (53) carglist ::= */ yytestcase(yyruleno==53);
126086       /* (60) ccons ::= NULL onconf */ yytestcase(yyruleno==60);
126087       /* (88) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==88);
126088       /* (89) conslist ::= tcons */ yytestcase(yyruleno==89);
126089       /* (91) tconscomma ::= */ yytestcase(yyruleno==91);
126090       /* (273) foreach_clause ::= */ yytestcase(yyruleno==273);
126091       /* (274) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==274);
126092       /* (281) tridxby ::= */ yytestcase(yyruleno==281);
126093       /* (298) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==298);
126094       /* (299) database_kw_opt ::= */ yytestcase(yyruleno==299);
126095       /* (307) kwcolumn_opt ::= */ yytestcase(yyruleno==307);
126096       /* (308) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==308);
126097       /* (312) vtabarglist ::= vtabarg */ yytestcase(yyruleno==312);
126098       /* (313) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==313);
126099       /* (315) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==315);
126100       /* (319) anylist ::= */ yytestcase(yyruleno==319);
126101       /* (320) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==320);
126102       /* (321) anylist ::= anylist ANY */ yytestcase(yyruleno==321);
126103         break;
126104   };
126105   assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
126106   yygoto = yyRuleInfo[yyruleno].lhs;
126107   yysize = yyRuleInfo[yyruleno].nrhs;
126108   yypParser->yyidx -= yysize;
126109   yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
126110   if( yyact < YYNSTATE ){
126111 #ifdef NDEBUG
126112     /* If we are not debugging and the reduce action popped at least
126113     ** one element off the stack, then we can push the new element back
126114     ** onto the stack here, and skip the stack overflow test in yy_shift().
126115     ** That gives a significant speed improvement. */
126116     if( yysize ){
126117       yypParser->yyidx++;
126118       yymsp -= yysize-1;
126119       yymsp->stateno = (YYACTIONTYPE)yyact;
126120       yymsp->major = (YYCODETYPE)yygoto;
126121       yymsp->minor = yygotominor;
126122     }else
126123 #endif
126124     {
126125       yy_shift(yypParser,yyact,yygoto,&yygotominor);
126126     }
126127   }else{
126128     assert( yyact == YYNSTATE + YYNRULE + 1 );
126129     yy_accept(yypParser);
126130   }
126131 }
126132
126133 /*
126134 ** The following code executes when the parse fails
126135 */
126136 #ifndef YYNOERRORRECOVERY
126137 static void yy_parse_failed(
126138   yyParser *yypParser           /* The parser */
126139 ){
126140   sqlite3ParserARG_FETCH;
126141 #ifndef NDEBUG
126142   if( yyTraceFILE ){
126143     fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
126144   }
126145 #endif
126146   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
126147   /* Here code is inserted which will be executed whenever the
126148   ** parser fails */
126149   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
126150 }
126151 #endif /* YYNOERRORRECOVERY */
126152
126153 /*
126154 ** The following code executes when a syntax error first occurs.
126155 */
126156 static void yy_syntax_error(
126157   yyParser *yypParser,           /* The parser */
126158   int yymajor,                   /* The major type of the error token */
126159   YYMINORTYPE yyminor            /* The minor type of the error token */
126160 ){
126161   sqlite3ParserARG_FETCH;
126162 #define TOKEN (yyminor.yy0)
126163
126164   UNUSED_PARAMETER(yymajor);  /* Silence some compiler warnings */
126165   assert( TOKEN.z[0] );  /* The tokenizer always gives us a token */
126166   sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
126167   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
126168 }
126169
126170 /*
126171 ** The following is executed when the parser accepts
126172 */
126173 static void yy_accept(
126174   yyParser *yypParser           /* The parser */
126175 ){
126176   sqlite3ParserARG_FETCH;
126177 #ifndef NDEBUG
126178   if( yyTraceFILE ){
126179     fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
126180   }
126181 #endif
126182   while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
126183   /* Here code is inserted which will be executed whenever the
126184   ** parser accepts */
126185   sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
126186 }
126187
126188 /* The main parser program.
126189 ** The first argument is a pointer to a structure obtained from
126190 ** "sqlite3ParserAlloc" which describes the current state of the parser.
126191 ** The second argument is the major token number.  The third is
126192 ** the minor token.  The fourth optional argument is whatever the
126193 ** user wants (and specified in the grammar) and is available for
126194 ** use by the action routines.
126195 **
126196 ** Inputs:
126197 ** <ul>
126198 ** <li> A pointer to the parser (an opaque structure.)
126199 ** <li> The major token number.
126200 ** <li> The minor token number.
126201 ** <li> An option argument of a grammar-specified type.
126202 ** </ul>
126203 **
126204 ** Outputs:
126205 ** None.
126206 */
126207 SQLITE_PRIVATE void sqlite3Parser(
126208   void *yyp,                   /* The parser */
126209   int yymajor,                 /* The major token code number */
126210   sqlite3ParserTOKENTYPE yyminor       /* The value for the token */
126211   sqlite3ParserARG_PDECL               /* Optional %extra_argument parameter */
126212 ){
126213   YYMINORTYPE yyminorunion;
126214   int yyact;            /* The parser action. */
126215 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
126216   int yyendofinput;     /* True if we are at the end of input */
126217 #endif
126218 #ifdef YYERRORSYMBOL
126219   int yyerrorhit = 0;   /* True if yymajor has invoked an error */
126220 #endif
126221   yyParser *yypParser;  /* The parser */
126222
126223   /* (re)initialize the parser, if necessary */
126224   yypParser = (yyParser*)yyp;
126225   if( yypParser->yyidx<0 ){
126226 #if YYSTACKDEPTH<=0
126227     if( yypParser->yystksz <=0 ){
126228       /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
126229       yyminorunion = yyzerominor;
126230       yyStackOverflow(yypParser, &yyminorunion);
126231       return;
126232     }
126233 #endif
126234     yypParser->yyidx = 0;
126235     yypParser->yyerrcnt = -1;
126236     yypParser->yystack[0].stateno = 0;
126237     yypParser->yystack[0].major = 0;
126238   }
126239   yyminorunion.yy0 = yyminor;
126240 #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
126241   yyendofinput = (yymajor==0);
126242 #endif
126243   sqlite3ParserARG_STORE;
126244
126245 #ifndef NDEBUG
126246   if( yyTraceFILE ){
126247     fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
126248   }
126249 #endif
126250
126251   do{
126252     yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
126253     if( yyact<YYNSTATE ){
126254       yy_shift(yypParser,yyact,yymajor,&yyminorunion);
126255       yypParser->yyerrcnt--;
126256       yymajor = YYNOCODE;
126257     }else if( yyact < YYNSTATE + YYNRULE ){
126258       yy_reduce(yypParser,yyact-YYNSTATE);
126259     }else{
126260       assert( yyact == YY_ERROR_ACTION );
126261 #ifdef YYERRORSYMBOL
126262       int yymx;
126263 #endif
126264 #ifndef NDEBUG
126265       if( yyTraceFILE ){
126266         fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
126267       }
126268 #endif
126269 #ifdef YYERRORSYMBOL
126270       /* A syntax error has occurred.
126271       ** The response to an error depends upon whether or not the
126272       ** grammar defines an error token "ERROR".  
126273       **
126274       ** This is what we do if the grammar does define ERROR:
126275       **
126276       **  * Call the %syntax_error function.
126277       **
126278       **  * Begin popping the stack until we enter a state where
126279       **    it is legal to shift the error symbol, then shift
126280       **    the error symbol.
126281       **
126282       **  * Set the error count to three.
126283       **
126284       **  * Begin accepting and shifting new tokens.  No new error
126285       **    processing will occur until three tokens have been
126286       **    shifted successfully.
126287       **
126288       */
126289       if( yypParser->yyerrcnt<0 ){
126290         yy_syntax_error(yypParser,yymajor,yyminorunion);
126291       }
126292       yymx = yypParser->yystack[yypParser->yyidx].major;
126293       if( yymx==YYERRORSYMBOL || yyerrorhit ){
126294 #ifndef NDEBUG
126295         if( yyTraceFILE ){
126296           fprintf(yyTraceFILE,"%sDiscard input token %s\n",
126297              yyTracePrompt,yyTokenName[yymajor]);
126298         }
126299 #endif
126300         yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
126301         yymajor = YYNOCODE;
126302       }else{
126303          while(
126304           yypParser->yyidx >= 0 &&
126305           yymx != YYERRORSYMBOL &&
126306           (yyact = yy_find_reduce_action(
126307                         yypParser->yystack[yypParser->yyidx].stateno,
126308                         YYERRORSYMBOL)) >= YYNSTATE
126309         ){
126310           yy_pop_parser_stack(yypParser);
126311         }
126312         if( yypParser->yyidx < 0 || yymajor==0 ){
126313           yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
126314           yy_parse_failed(yypParser);
126315           yymajor = YYNOCODE;
126316         }else if( yymx!=YYERRORSYMBOL ){
126317           YYMINORTYPE u2;
126318           u2.YYERRSYMDT = 0;
126319           yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
126320         }
126321       }
126322       yypParser->yyerrcnt = 3;
126323       yyerrorhit = 1;
126324 #elif defined(YYNOERRORRECOVERY)
126325       /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
126326       ** do any kind of error recovery.  Instead, simply invoke the syntax
126327       ** error routine and continue going as if nothing had happened.
126328       **
126329       ** Applications can set this macro (for example inside %include) if
126330       ** they intend to abandon the parse upon the first syntax error seen.
126331       */
126332       yy_syntax_error(yypParser,yymajor,yyminorunion);
126333       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
126334       yymajor = YYNOCODE;
126335       
126336 #else  /* YYERRORSYMBOL is not defined */
126337       /* This is what we do if the grammar does not define ERROR:
126338       **
126339       **  * Report an error message, and throw away the input token.
126340       **
126341       **  * If the input token is $, then fail the parse.
126342       **
126343       ** As before, subsequent error messages are suppressed until
126344       ** three input tokens have been successfully shifted.
126345       */
126346       if( yypParser->yyerrcnt<=0 ){
126347         yy_syntax_error(yypParser,yymajor,yyminorunion);
126348       }
126349       yypParser->yyerrcnt = 3;
126350       yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
126351       if( yyendofinput ){
126352         yy_parse_failed(yypParser);
126353       }
126354       yymajor = YYNOCODE;
126355 #endif
126356     }
126357   }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
126358   return;
126359 }
126360
126361 /************** End of parse.c ***********************************************/
126362 /************** Begin file tokenize.c ****************************************/
126363 /*
126364 ** 2001 September 15
126365 **
126366 ** The author disclaims copyright to this source code.  In place of
126367 ** a legal notice, here is a blessing:
126368 **
126369 **    May you do good and not evil.
126370 **    May you find forgiveness for yourself and forgive others.
126371 **    May you share freely, never taking more than you give.
126372 **
126373 *************************************************************************
126374 ** An tokenizer for SQL
126375 **
126376 ** This file contains C code that splits an SQL input string up into
126377 ** individual tokens and sends those tokens one-by-one over to the
126378 ** parser for analysis.
126379 */
126380 /* #include <stdlib.h> */
126381
126382 /*
126383 ** The charMap() macro maps alphabetic characters into their
126384 ** lower-case ASCII equivalent.  On ASCII machines, this is just
126385 ** an upper-to-lower case map.  On EBCDIC machines we also need
126386 ** to adjust the encoding.  Only alphabetic characters and underscores
126387 ** need to be translated.
126388 */
126389 #ifdef SQLITE_ASCII
126390 # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
126391 #endif
126392 #ifdef SQLITE_EBCDIC
126393 # define charMap(X) ebcdicToAscii[(unsigned char)X]
126394 const unsigned char ebcdicToAscii[] = {
126395 /* 0   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F */
126396    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 0x */
126397    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 1x */
126398    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 2x */
126399    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 3x */
126400    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 4x */
126401    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 5x */
126402    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0, 95,  0,  0,  /* 6x */
126403    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* 7x */
126404    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* 8x */
126405    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* 9x */
126406    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ax */
126407    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Bx */
126408    0, 97, 98, 99,100,101,102,103,104,105,  0,  0,  0,  0,  0,  0,  /* Cx */
126409    0,106,107,108,109,110,111,112,113,114,  0,  0,  0,  0,  0,  0,  /* Dx */
126410    0,  0,115,116,117,118,119,120,121,122,  0,  0,  0,  0,  0,  0,  /* Ex */
126411    0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  /* Fx */
126412 };
126413 #endif
126414
126415 /*
126416 ** The sqlite3KeywordCode function looks up an identifier to determine if
126417 ** it is a keyword.  If it is a keyword, the token code of that keyword is 
126418 ** returned.  If the input is not a keyword, TK_ID is returned.
126419 **
126420 ** The implementation of this routine was generated by a program,
126421 ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
126422 ** The output of the mkkeywordhash.c program is written into a file
126423 ** named keywordhash.h and then included into this source file by
126424 ** the #include below.
126425 */
126426 /************** Include keywordhash.h in the middle of tokenize.c ************/
126427 /************** Begin file keywordhash.h *************************************/
126428 /***** This file contains automatically generated code ******
126429 **
126430 ** The code in this file has been automatically generated by
126431 **
126432 **   sqlite/tool/mkkeywordhash.c
126433 **
126434 ** The code in this file implements a function that determines whether
126435 ** or not a given identifier is really an SQL keyword.  The same thing
126436 ** might be implemented more directly using a hand-written hash table.
126437 ** But by using this automatically generated code, the size of the code
126438 ** is substantially reduced.  This is important for embedded applications
126439 ** on platforms with limited memory.
126440 */
126441 /* Hash score: 182 */
126442 static int keywordCode(const char *z, int n){
126443   /* zText[] encodes 834 bytes of keywords in 554 bytes */
126444   /*   REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT       */
126445   /*   ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE         */
126446   /*   XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY         */
126447   /*   UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE         */
126448   /*   BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH     */
126449   /*   IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN     */
126450   /*   WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT         */
126451   /*   CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL        */
126452   /*   FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING        */
126453   /*   VACUUMVIEWINITIALLY                                                */
126454   static const char zText[553] = {
126455     'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
126456     'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
126457     'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
126458     'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
126459     'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
126460     'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
126461     'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
126462     'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
126463     'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
126464     'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
126465     'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
126466     'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
126467     'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
126468     'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
126469     'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
126470     'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
126471     'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
126472     'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
126473     'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
126474     'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
126475     'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
126476     'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
126477     'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
126478     'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
126479     'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
126480     'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
126481     'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
126482     'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
126483     'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
126484     'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
126485     'V','I','E','W','I','N','I','T','I','A','L','L','Y',
126486   };
126487   static const unsigned char aHash[127] = {
126488       76, 105, 117,  74,   0,  45,   0,   0,  82,   0,  77,   0,   0,
126489       42,  12,  78,  15,   0, 116,  85,  54, 112,   0,  19,   0,   0,
126490      121,   0, 119, 115,   0,  22,  93,   0,   9,   0,   0,  70,  71,
126491        0,  69,   6,   0,  48,  90, 102,   0, 118, 101,   0,   0,  44,
126492        0, 103,  24,   0,  17,   0, 122,  53,  23,   0,   5, 110,  25,
126493       96,   0,   0, 124, 106,  60, 123,  57,  28,  55,   0,  91,   0,
126494      100,  26,   0,  99,   0,   0,   0,  95,  92,  97,  88, 109,  14,
126495       39, 108,   0,  81,   0,  18,  89, 111,  32,   0, 120,  80, 113,
126496       62,  46,  84,   0,   0,  94,  40,  59, 114,   0,  36,   0,   0,
126497       29,   0,  86,  63,  64,   0,  20,  61,   0,  56,
126498   };
126499   static const unsigned char aNext[124] = {
126500        0,   0,   0,   0,   4,   0,   0,   0,   0,   0,   0,   0,   0,
126501        0,   2,   0,   0,   0,   0,   0,   0,  13,   0,   0,   0,   0,
126502        0,   7,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,   0,
126503        0,   0,   0,   0,  33,   0,  21,   0,   0,   0,   0,   0,  50,
126504        0,  43,   3,  47,   0,   0,   0,   0,  30,   0,  58,   0,  38,
126505        0,   0,   0,   1,  66,   0,   0,  67,   0,  41,   0,   0,   0,
126506        0,   0,   0,  49,  65,   0,   0,   0,   0,  31,  52,  16,  34,
126507       10,   0,   0,   0,   0,   0,   0,   0,  11,  72,  79,   0,   8,
126508        0, 104,  98,   0, 107,   0,  87,   0,  75,  51,   0,  27,  37,
126509       73,  83,   0,  35,  68,   0,   0,
126510   };
126511   static const unsigned char aLen[124] = {
126512        7,   7,   5,   4,   6,   4,   5,   3,   6,   7,   3,   6,   6,
126513        7,   7,   3,   8,   2,   6,   5,   4,   4,   3,  10,   4,   6,
126514       11,   6,   2,   7,   5,   5,   9,   6,   9,   9,   7,  10,  10,
126515        4,   6,   2,   3,   9,   4,   2,   6,   5,   7,   4,   5,   7,
126516        6,   6,   5,   6,   5,   5,   9,   7,   7,   3,   2,   4,   4,
126517        7,   3,   6,   4,   7,   6,  12,   6,   9,   4,   6,   5,   4,
126518        7,   6,   5,   6,   7,   5,   4,   5,   6,   5,   7,   3,   7,
126519       13,   2,   2,   4,   6,   6,   8,   5,  17,  12,   7,   8,   8,
126520        2,   4,   4,   4,   4,   4,   2,   2,   6,   5,   8,   5,   8,
126521        3,   5,   5,   6,   4,   9,   3,
126522   };
126523   static const unsigned short int aOffset[124] = {
126524        0,   2,   2,   8,   9,  14,  16,  20,  23,  25,  25,  29,  33,
126525       36,  41,  46,  48,  53,  54,  59,  62,  65,  67,  69,  78,  81,
126526       86,  91,  95,  96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
126527      159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
126528      199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
126529      250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
126530      320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
126531      387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
126532      460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
126533      521, 524, 529, 534, 540, 544, 549,
126534   };
126535   static const unsigned char aCode[124] = {
126536     TK_REINDEX,    TK_INDEXED,    TK_INDEX,      TK_DESC,       TK_ESCAPE,     
126537     TK_EACH,       TK_CHECK,      TK_KEY,        TK_BEFORE,     TK_FOREIGN,    
126538     TK_FOR,        TK_IGNORE,     TK_LIKE_KW,    TK_EXPLAIN,    TK_INSTEAD,    
126539     TK_ADD,        TK_DATABASE,   TK_AS,         TK_SELECT,     TK_TABLE,      
126540     TK_JOIN_KW,    TK_THEN,       TK_END,        TK_DEFERRABLE, TK_ELSE,       
126541     TK_EXCEPT,     TK_TRANSACTION,TK_ACTION,     TK_ON,         TK_JOIN_KW,    
126542     TK_ALTER,      TK_RAISE,      TK_EXCLUSIVE,  TK_EXISTS,     TK_SAVEPOINT,  
126543     TK_INTERSECT,  TK_TRIGGER,    TK_REFERENCES, TK_CONSTRAINT, TK_INTO,       
126544     TK_OFFSET,     TK_OF,         TK_SET,        TK_TEMP,       TK_TEMP,       
126545     TK_OR,         TK_UNIQUE,     TK_QUERY,      TK_WITHOUT,    TK_WITH,       
126546     TK_JOIN_KW,    TK_RELEASE,    TK_ATTACH,     TK_HAVING,     TK_GROUP,      
126547     TK_UPDATE,     TK_BEGIN,      TK_JOIN_KW,    TK_RECURSIVE,  TK_BETWEEN,    
126548     TK_NOTNULL,    TK_NOT,        TK_NO,         TK_NULL,       TK_LIKE_KW,    
126549     TK_CASCADE,    TK_ASC,        TK_DELETE,     TK_CASE,       TK_COLLATE,    
126550     TK_CREATE,     TK_CTIME_KW,   TK_DETACH,     TK_IMMEDIATE,  TK_JOIN,       
126551     TK_INSERT,     TK_MATCH,      TK_PLAN,       TK_ANALYZE,    TK_PRAGMA,     
126552     TK_ABORT,      TK_VALUES,     TK_VIRTUAL,    TK_LIMIT,      TK_WHEN,       
126553     TK_WHERE,      TK_RENAME,     TK_AFTER,      TK_REPLACE,    TK_AND,        
126554     TK_DEFAULT,    TK_AUTOINCR,   TK_TO,         TK_IN,         TK_CAST,       
126555     TK_COLUMNKW,   TK_COMMIT,     TK_CONFLICT,   TK_JOIN_KW,    TK_CTIME_KW,   
126556     TK_CTIME_KW,   TK_PRIMARY,    TK_DEFERRED,   TK_DISTINCT,   TK_IS,         
126557     TK_DROP,       TK_FAIL,       TK_FROM,       TK_JOIN_KW,    TK_LIKE_KW,    
126558     TK_BY,         TK_IF,         TK_ISNULL,     TK_ORDER,      TK_RESTRICT,   
126559     TK_JOIN_KW,    TK_ROLLBACK,   TK_ROW,        TK_UNION,      TK_USING,      
126560     TK_VACUUM,     TK_VIEW,       TK_INITIALLY,  TK_ALL,        
126561   };
126562   int h, i;
126563   if( n<2 ) return TK_ID;
126564   h = ((charMap(z[0])*4) ^
126565       (charMap(z[n-1])*3) ^
126566       n) % 127;
126567   for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
126568     if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
126569       testcase( i==0 ); /* REINDEX */
126570       testcase( i==1 ); /* INDEXED */
126571       testcase( i==2 ); /* INDEX */
126572       testcase( i==3 ); /* DESC */
126573       testcase( i==4 ); /* ESCAPE */
126574       testcase( i==5 ); /* EACH */
126575       testcase( i==6 ); /* CHECK */
126576       testcase( i==7 ); /* KEY */
126577       testcase( i==8 ); /* BEFORE */
126578       testcase( i==9 ); /* FOREIGN */
126579       testcase( i==10 ); /* FOR */
126580       testcase( i==11 ); /* IGNORE */
126581       testcase( i==12 ); /* REGEXP */
126582       testcase( i==13 ); /* EXPLAIN */
126583       testcase( i==14 ); /* INSTEAD */
126584       testcase( i==15 ); /* ADD */
126585       testcase( i==16 ); /* DATABASE */
126586       testcase( i==17 ); /* AS */
126587       testcase( i==18 ); /* SELECT */
126588       testcase( i==19 ); /* TABLE */
126589       testcase( i==20 ); /* LEFT */
126590       testcase( i==21 ); /* THEN */
126591       testcase( i==22 ); /* END */
126592       testcase( i==23 ); /* DEFERRABLE */
126593       testcase( i==24 ); /* ELSE */
126594       testcase( i==25 ); /* EXCEPT */
126595       testcase( i==26 ); /* TRANSACTION */
126596       testcase( i==27 ); /* ACTION */
126597       testcase( i==28 ); /* ON */
126598       testcase( i==29 ); /* NATURAL */
126599       testcase( i==30 ); /* ALTER */
126600       testcase( i==31 ); /* RAISE */
126601       testcase( i==32 ); /* EXCLUSIVE */
126602       testcase( i==33 ); /* EXISTS */
126603       testcase( i==34 ); /* SAVEPOINT */
126604       testcase( i==35 ); /* INTERSECT */
126605       testcase( i==36 ); /* TRIGGER */
126606       testcase( i==37 ); /* REFERENCES */
126607       testcase( i==38 ); /* CONSTRAINT */
126608       testcase( i==39 ); /* INTO */
126609       testcase( i==40 ); /* OFFSET */
126610       testcase( i==41 ); /* OF */
126611       testcase( i==42 ); /* SET */
126612       testcase( i==43 ); /* TEMPORARY */
126613       testcase( i==44 ); /* TEMP */
126614       testcase( i==45 ); /* OR */
126615       testcase( i==46 ); /* UNIQUE */
126616       testcase( i==47 ); /* QUERY */
126617       testcase( i==48 ); /* WITHOUT */
126618       testcase( i==49 ); /* WITH */
126619       testcase( i==50 ); /* OUTER */
126620       testcase( i==51 ); /* RELEASE */
126621       testcase( i==52 ); /* ATTACH */
126622       testcase( i==53 ); /* HAVING */
126623       testcase( i==54 ); /* GROUP */
126624       testcase( i==55 ); /* UPDATE */
126625       testcase( i==56 ); /* BEGIN */
126626       testcase( i==57 ); /* INNER */
126627       testcase( i==58 ); /* RECURSIVE */
126628       testcase( i==59 ); /* BETWEEN */
126629       testcase( i==60 ); /* NOTNULL */
126630       testcase( i==61 ); /* NOT */
126631       testcase( i==62 ); /* NO */
126632       testcase( i==63 ); /* NULL */
126633       testcase( i==64 ); /* LIKE */
126634       testcase( i==65 ); /* CASCADE */
126635       testcase( i==66 ); /* ASC */
126636       testcase( i==67 ); /* DELETE */
126637       testcase( i==68 ); /* CASE */
126638       testcase( i==69 ); /* COLLATE */
126639       testcase( i==70 ); /* CREATE */
126640       testcase( i==71 ); /* CURRENT_DATE */
126641       testcase( i==72 ); /* DETACH */
126642       testcase( i==73 ); /* IMMEDIATE */
126643       testcase( i==74 ); /* JOIN */
126644       testcase( i==75 ); /* INSERT */
126645       testcase( i==76 ); /* MATCH */
126646       testcase( i==77 ); /* PLAN */
126647       testcase( i==78 ); /* ANALYZE */
126648       testcase( i==79 ); /* PRAGMA */
126649       testcase( i==80 ); /* ABORT */
126650       testcase( i==81 ); /* VALUES */
126651       testcase( i==82 ); /* VIRTUAL */
126652       testcase( i==83 ); /* LIMIT */
126653       testcase( i==84 ); /* WHEN */
126654       testcase( i==85 ); /* WHERE */
126655       testcase( i==86 ); /* RENAME */
126656       testcase( i==87 ); /* AFTER */
126657       testcase( i==88 ); /* REPLACE */
126658       testcase( i==89 ); /* AND */
126659       testcase( i==90 ); /* DEFAULT */
126660       testcase( i==91 ); /* AUTOINCREMENT */
126661       testcase( i==92 ); /* TO */
126662       testcase( i==93 ); /* IN */
126663       testcase( i==94 ); /* CAST */
126664       testcase( i==95 ); /* COLUMN */
126665       testcase( i==96 ); /* COMMIT */
126666       testcase( i==97 ); /* CONFLICT */
126667       testcase( i==98 ); /* CROSS */
126668       testcase( i==99 ); /* CURRENT_TIMESTAMP */
126669       testcase( i==100 ); /* CURRENT_TIME */
126670       testcase( i==101 ); /* PRIMARY */
126671       testcase( i==102 ); /* DEFERRED */
126672       testcase( i==103 ); /* DISTINCT */
126673       testcase( i==104 ); /* IS */
126674       testcase( i==105 ); /* DROP */
126675       testcase( i==106 ); /* FAIL */
126676       testcase( i==107 ); /* FROM */
126677       testcase( i==108 ); /* FULL */
126678       testcase( i==109 ); /* GLOB */
126679       testcase( i==110 ); /* BY */
126680       testcase( i==111 ); /* IF */
126681       testcase( i==112 ); /* ISNULL */
126682       testcase( i==113 ); /* ORDER */
126683       testcase( i==114 ); /* RESTRICT */
126684       testcase( i==115 ); /* RIGHT */
126685       testcase( i==116 ); /* ROLLBACK */
126686       testcase( i==117 ); /* ROW */
126687       testcase( i==118 ); /* UNION */
126688       testcase( i==119 ); /* USING */
126689       testcase( i==120 ); /* VACUUM */
126690       testcase( i==121 ); /* VIEW */
126691       testcase( i==122 ); /* INITIALLY */
126692       testcase( i==123 ); /* ALL */
126693       return aCode[i];
126694     }
126695   }
126696   return TK_ID;
126697 }
126698 SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
126699   return keywordCode((char*)z, n);
126700 }
126701 #define SQLITE_N_KEYWORD 124
126702
126703 /************** End of keywordhash.h *****************************************/
126704 /************** Continuing where we left off in tokenize.c *******************/
126705
126706
126707 /*
126708 ** If X is a character that can be used in an identifier then
126709 ** IdChar(X) will be true.  Otherwise it is false.
126710 **
126711 ** For ASCII, any character with the high-order bit set is
126712 ** allowed in an identifier.  For 7-bit characters, 
126713 ** sqlite3IsIdChar[X] must be 1.
126714 **
126715 ** For EBCDIC, the rules are more complex but have the same
126716 ** end result.
126717 **
126718 ** Ticket #1066.  the SQL standard does not allow '$' in the
126719 ** middle of identifiers.  But many SQL implementations do. 
126720 ** SQLite will allow '$' in identifiers for compatibility.
126721 ** But the feature is undocumented.
126722 */
126723 #ifdef SQLITE_ASCII
126724 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
126725 #endif
126726 #ifdef SQLITE_EBCDIC
126727 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
126728 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
126729     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 4x */
126730     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0,  /* 5x */
126731     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0,  /* 6x */
126732     0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0,  /* 7x */
126733     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0,  /* 8x */
126734     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0,  /* 9x */
126735     1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0,  /* Ax */
126736     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* Bx */
126737     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Cx */
126738     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Dx */
126739     0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1,  /* Ex */
126740     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0,  /* Fx */
126741 };
126742 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
126743 #endif
126744 SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
126745
126746
126747 /*
126748 ** Return the length of the token that begins at z[0]. 
126749 ** Store the token type in *tokenType before returning.
126750 */
126751 SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
126752   int i, c;
126753   switch( *z ){
126754     case ' ': case '\t': case '\n': case '\f': case '\r': {
126755       testcase( z[0]==' ' );
126756       testcase( z[0]=='\t' );
126757       testcase( z[0]=='\n' );
126758       testcase( z[0]=='\f' );
126759       testcase( z[0]=='\r' );
126760       for(i=1; sqlite3Isspace(z[i]); i++){}
126761       *tokenType = TK_SPACE;
126762       return i;
126763     }
126764     case '-': {
126765       if( z[1]=='-' ){
126766         for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
126767         *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
126768         return i;
126769       }
126770       *tokenType = TK_MINUS;
126771       return 1;
126772     }
126773     case '(': {
126774       *tokenType = TK_LP;
126775       return 1;
126776     }
126777     case ')': {
126778       *tokenType = TK_RP;
126779       return 1;
126780     }
126781     case ';': {
126782       *tokenType = TK_SEMI;
126783       return 1;
126784     }
126785     case '+': {
126786       *tokenType = TK_PLUS;
126787       return 1;
126788     }
126789     case '*': {
126790       *tokenType = TK_STAR;
126791       return 1;
126792     }
126793     case '/': {
126794       if( z[1]!='*' || z[2]==0 ){
126795         *tokenType = TK_SLASH;
126796         return 1;
126797       }
126798       for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
126799       if( c ) i++;
126800       *tokenType = TK_SPACE;   /* IMP: R-22934-25134 */
126801       return i;
126802     }
126803     case '%': {
126804       *tokenType = TK_REM;
126805       return 1;
126806     }
126807     case '=': {
126808       *tokenType = TK_EQ;
126809       return 1 + (z[1]=='=');
126810     }
126811     case '<': {
126812       if( (c=z[1])=='=' ){
126813         *tokenType = TK_LE;
126814         return 2;
126815       }else if( c=='>' ){
126816         *tokenType = TK_NE;
126817         return 2;
126818       }else if( c=='<' ){
126819         *tokenType = TK_LSHIFT;
126820         return 2;
126821       }else{
126822         *tokenType = TK_LT;
126823         return 1;
126824       }
126825     }
126826     case '>': {
126827       if( (c=z[1])=='=' ){
126828         *tokenType = TK_GE;
126829         return 2;
126830       }else if( c=='>' ){
126831         *tokenType = TK_RSHIFT;
126832         return 2;
126833       }else{
126834         *tokenType = TK_GT;
126835         return 1;
126836       }
126837     }
126838     case '!': {
126839       if( z[1]!='=' ){
126840         *tokenType = TK_ILLEGAL;
126841         return 2;
126842       }else{
126843         *tokenType = TK_NE;
126844         return 2;
126845       }
126846     }
126847     case '|': {
126848       if( z[1]!='|' ){
126849         *tokenType = TK_BITOR;
126850         return 1;
126851       }else{
126852         *tokenType = TK_CONCAT;
126853         return 2;
126854       }
126855     }
126856     case ',': {
126857       *tokenType = TK_COMMA;
126858       return 1;
126859     }
126860     case '&': {
126861       *tokenType = TK_BITAND;
126862       return 1;
126863     }
126864     case '~': {
126865       *tokenType = TK_BITNOT;
126866       return 1;
126867     }
126868     case '`':
126869     case '\'':
126870     case '"': {
126871       int delim = z[0];
126872       testcase( delim=='`' );
126873       testcase( delim=='\'' );
126874       testcase( delim=='"' );
126875       for(i=1; (c=z[i])!=0; i++){
126876         if( c==delim ){
126877           if( z[i+1]==delim ){
126878             i++;
126879           }else{
126880             break;
126881           }
126882         }
126883       }
126884       if( c=='\'' ){
126885         *tokenType = TK_STRING;
126886         return i+1;
126887       }else if( c!=0 ){
126888         *tokenType = TK_ID;
126889         return i+1;
126890       }else{
126891         *tokenType = TK_ILLEGAL;
126892         return i;
126893       }
126894     }
126895     case '.': {
126896 #ifndef SQLITE_OMIT_FLOATING_POINT
126897       if( !sqlite3Isdigit(z[1]) )
126898 #endif
126899       {
126900         *tokenType = TK_DOT;
126901         return 1;
126902       }
126903       /* If the next character is a digit, this is a floating point
126904       ** number that begins with ".".  Fall thru into the next case */
126905     }
126906     case '0': case '1': case '2': case '3': case '4':
126907     case '5': case '6': case '7': case '8': case '9': {
126908       testcase( z[0]=='0' );  testcase( z[0]=='1' );  testcase( z[0]=='2' );
126909       testcase( z[0]=='3' );  testcase( z[0]=='4' );  testcase( z[0]=='5' );
126910       testcase( z[0]=='6' );  testcase( z[0]=='7' );  testcase( z[0]=='8' );
126911       testcase( z[0]=='9' );
126912       *tokenType = TK_INTEGER;
126913 #ifndef SQLITE_OMIT_HEX_INTEGER
126914       if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
126915         for(i=3; sqlite3Isxdigit(z[i]); i++){}
126916         return i;
126917       }
126918 #endif
126919       for(i=0; sqlite3Isdigit(z[i]); i++){}
126920 #ifndef SQLITE_OMIT_FLOATING_POINT
126921       if( z[i]=='.' ){
126922         i++;
126923         while( sqlite3Isdigit(z[i]) ){ i++; }
126924         *tokenType = TK_FLOAT;
126925       }
126926       if( (z[i]=='e' || z[i]=='E') &&
126927            ( sqlite3Isdigit(z[i+1]) 
126928             || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
126929            )
126930       ){
126931         i += 2;
126932         while( sqlite3Isdigit(z[i]) ){ i++; }
126933         *tokenType = TK_FLOAT;
126934       }
126935 #endif
126936       while( IdChar(z[i]) ){
126937         *tokenType = TK_ILLEGAL;
126938         i++;
126939       }
126940       return i;
126941     }
126942     case '[': {
126943       for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
126944       *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
126945       return i;
126946     }
126947     case '?': {
126948       *tokenType = TK_VARIABLE;
126949       for(i=1; sqlite3Isdigit(z[i]); i++){}
126950       return i;
126951     }
126952 #ifndef SQLITE_OMIT_TCL_VARIABLE
126953     case '$':
126954 #endif
126955     case '@':  /* For compatibility with MS SQL Server */
126956     case '#':
126957     case ':': {
126958       int n = 0;
126959       testcase( z[0]=='$' );  testcase( z[0]=='@' );
126960       testcase( z[0]==':' );  testcase( z[0]=='#' );
126961       *tokenType = TK_VARIABLE;
126962       for(i=1; (c=z[i])!=0; i++){
126963         if( IdChar(c) ){
126964           n++;
126965 #ifndef SQLITE_OMIT_TCL_VARIABLE
126966         }else if( c=='(' && n>0 ){
126967           do{
126968             i++;
126969           }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
126970           if( c==')' ){
126971             i++;
126972           }else{
126973             *tokenType = TK_ILLEGAL;
126974           }
126975           break;
126976         }else if( c==':' && z[i+1]==':' ){
126977           i++;
126978 #endif
126979         }else{
126980           break;
126981         }
126982       }
126983       if( n==0 ) *tokenType = TK_ILLEGAL;
126984       return i;
126985     }
126986 #ifndef SQLITE_OMIT_BLOB_LITERAL
126987     case 'x': case 'X': {
126988       testcase( z[0]=='x' ); testcase( z[0]=='X' );
126989       if( z[1]=='\'' ){
126990         *tokenType = TK_BLOB;
126991         for(i=2; sqlite3Isxdigit(z[i]); i++){}
126992         if( z[i]!='\'' || i%2 ){
126993           *tokenType = TK_ILLEGAL;
126994           while( z[i] && z[i]!='\'' ){ i++; }
126995         }
126996         if( z[i] ) i++;
126997         return i;
126998       }
126999       /* Otherwise fall through to the next case */
127000     }
127001 #endif
127002     default: {
127003       if( !IdChar(*z) ){
127004         break;
127005       }
127006       for(i=1; IdChar(z[i]); i++){}
127007       *tokenType = keywordCode((char*)z, i);
127008       return i;
127009     }
127010   }
127011   *tokenType = TK_ILLEGAL;
127012   return 1;
127013 }
127014
127015 /*
127016 ** Run the parser on the given SQL string.  The parser structure is
127017 ** passed in.  An SQLITE_ status code is returned.  If an error occurs
127018 ** then an and attempt is made to write an error message into 
127019 ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
127020 ** error message.
127021 */
127022 SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
127023   int nErr = 0;                   /* Number of errors encountered */
127024   int i;                          /* Loop counter */
127025   void *pEngine;                  /* The LEMON-generated LALR(1) parser */
127026   int tokenType;                  /* type of the next token */
127027   int lastTokenParsed = -1;       /* type of the previous token */
127028   u8 enableLookaside;             /* Saved value of db->lookaside.bEnabled */
127029   sqlite3 *db = pParse->db;       /* The database connection */
127030   int mxSqlLen;                   /* Max length of an SQL string */
127031
127032   assert( zSql!=0 );
127033   mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
127034   if( db->nVdbeActive==0 ){
127035     db->u1.isInterrupted = 0;
127036   }
127037   pParse->rc = SQLITE_OK;
127038   pParse->zTail = zSql;
127039   i = 0;
127040   assert( pzErrMsg!=0 );
127041   pEngine = sqlite3ParserAlloc(sqlite3Malloc);
127042   if( pEngine==0 ){
127043     db->mallocFailed = 1;
127044     return SQLITE_NOMEM;
127045   }
127046   assert( pParse->pNewTable==0 );
127047   assert( pParse->pNewTrigger==0 );
127048   assert( pParse->nVar==0 );
127049   assert( pParse->nzVar==0 );
127050   assert( pParse->azVar==0 );
127051   enableLookaside = db->lookaside.bEnabled;
127052   if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
127053   while( !db->mallocFailed && zSql[i]!=0 ){
127054     assert( i>=0 );
127055     pParse->sLastToken.z = &zSql[i];
127056     pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
127057     i += pParse->sLastToken.n;
127058     if( i>mxSqlLen ){
127059       pParse->rc = SQLITE_TOOBIG;
127060       break;
127061     }
127062     switch( tokenType ){
127063       case TK_SPACE: {
127064         if( db->u1.isInterrupted ){
127065           sqlite3ErrorMsg(pParse, "interrupt");
127066           pParse->rc = SQLITE_INTERRUPT;
127067           goto abort_parse;
127068         }
127069         break;
127070       }
127071       case TK_ILLEGAL: {
127072         sqlite3DbFree(db, *pzErrMsg);
127073         *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
127074                         &pParse->sLastToken);
127075         nErr++;
127076         goto abort_parse;
127077       }
127078       case TK_SEMI: {
127079         pParse->zTail = &zSql[i];
127080         /* Fall thru into the default case */
127081       }
127082       default: {
127083         sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
127084         lastTokenParsed = tokenType;
127085         if( pParse->rc!=SQLITE_OK ){
127086           goto abort_parse;
127087         }
127088         break;
127089       }
127090     }
127091   }
127092 abort_parse:
127093   if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
127094     if( lastTokenParsed!=TK_SEMI ){
127095       sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
127096       pParse->zTail = &zSql[i];
127097     }
127098     sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
127099   }
127100 #ifdef YYTRACKMAXSTACKDEPTH
127101   sqlite3_mutex_enter(sqlite3MallocMutex());
127102   sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
127103       sqlite3ParserStackPeak(pEngine)
127104   );
127105   sqlite3_mutex_leave(sqlite3MallocMutex());
127106 #endif /* YYDEBUG */
127107   sqlite3ParserFree(pEngine, sqlite3_free);
127108   db->lookaside.bEnabled = enableLookaside;
127109   if( db->mallocFailed ){
127110     pParse->rc = SQLITE_NOMEM;
127111   }
127112   if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
127113     sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
127114   }
127115   assert( pzErrMsg!=0 );
127116   if( pParse->zErrMsg ){
127117     *pzErrMsg = pParse->zErrMsg;
127118     sqlite3_log(pParse->rc, "%s", *pzErrMsg);
127119     pParse->zErrMsg = 0;
127120     nErr++;
127121   }
127122   if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
127123     sqlite3VdbeDelete(pParse->pVdbe);
127124     pParse->pVdbe = 0;
127125   }
127126 #ifndef SQLITE_OMIT_SHARED_CACHE
127127   if( pParse->nested==0 ){
127128     sqlite3DbFree(db, pParse->aTableLock);
127129     pParse->aTableLock = 0;
127130     pParse->nTableLock = 0;
127131   }
127132 #endif
127133 #ifndef SQLITE_OMIT_VIRTUALTABLE
127134   sqlite3_free(pParse->apVtabLock);
127135 #endif
127136
127137   if( !IN_DECLARE_VTAB ){
127138     /* If the pParse->declareVtab flag is set, do not delete any table 
127139     ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
127140     ** will take responsibility for freeing the Table structure.
127141     */
127142     sqlite3DeleteTable(db, pParse->pNewTable);
127143   }
127144
127145   if( pParse->bFreeWith ) sqlite3WithDelete(db, pParse->pWith);
127146   sqlite3DeleteTrigger(db, pParse->pNewTrigger);
127147   for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
127148   sqlite3DbFree(db, pParse->azVar);
127149   while( pParse->pAinc ){
127150     AutoincInfo *p = pParse->pAinc;
127151     pParse->pAinc = p->pNext;
127152     sqlite3DbFree(db, p);
127153   }
127154   while( pParse->pZombieTab ){
127155     Table *p = pParse->pZombieTab;
127156     pParse->pZombieTab = p->pNextZombie;
127157     sqlite3DeleteTable(db, p);
127158   }
127159   if( nErr>0 && pParse->rc==SQLITE_OK ){
127160     pParse->rc = SQLITE_ERROR;
127161   }
127162   return nErr;
127163 }
127164
127165 /************** End of tokenize.c ********************************************/
127166 /************** Begin file complete.c ****************************************/
127167 /*
127168 ** 2001 September 15
127169 **
127170 ** The author disclaims copyright to this source code.  In place of
127171 ** a legal notice, here is a blessing:
127172 **
127173 **    May you do good and not evil.
127174 **    May you find forgiveness for yourself and forgive others.
127175 **    May you share freely, never taking more than you give.
127176 **
127177 *************************************************************************
127178 ** An tokenizer for SQL
127179 **
127180 ** This file contains C code that implements the sqlite3_complete() API.
127181 ** This code used to be part of the tokenizer.c source file.  But by
127182 ** separating it out, the code will be automatically omitted from
127183 ** static links that do not use it.
127184 */
127185 #ifndef SQLITE_OMIT_COMPLETE
127186
127187 /*
127188 ** This is defined in tokenize.c.  We just have to import the definition.
127189 */
127190 #ifndef SQLITE_AMALGAMATION
127191 #ifdef SQLITE_ASCII
127192 #define IdChar(C)  ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
127193 #endif
127194 #ifdef SQLITE_EBCDIC
127195 SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
127196 #define IdChar(C)  (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
127197 #endif
127198 #endif /* SQLITE_AMALGAMATION */
127199
127200
127201 /*
127202 ** Token types used by the sqlite3_complete() routine.  See the header
127203 ** comments on that procedure for additional information.
127204 */
127205 #define tkSEMI    0
127206 #define tkWS      1
127207 #define tkOTHER   2
127208 #ifndef SQLITE_OMIT_TRIGGER
127209 #define tkEXPLAIN 3
127210 #define tkCREATE  4
127211 #define tkTEMP    5
127212 #define tkTRIGGER 6
127213 #define tkEND     7
127214 #endif
127215
127216 /*
127217 ** Return TRUE if the given SQL string ends in a semicolon.
127218 **
127219 ** Special handling is require for CREATE TRIGGER statements.
127220 ** Whenever the CREATE TRIGGER keywords are seen, the statement
127221 ** must end with ";END;".
127222 **
127223 ** This implementation uses a state machine with 8 states:
127224 **
127225 **   (0) INVALID   We have not yet seen a non-whitespace character.
127226 **
127227 **   (1) START     At the beginning or end of an SQL statement.  This routine
127228 **                 returns 1 if it ends in the START state and 0 if it ends
127229 **                 in any other state.
127230 **
127231 **   (2) NORMAL    We are in the middle of statement which ends with a single
127232 **                 semicolon.
127233 **
127234 **   (3) EXPLAIN   The keyword EXPLAIN has been seen at the beginning of 
127235 **                 a statement.
127236 **
127237 **   (4) CREATE    The keyword CREATE has been seen at the beginning of a
127238 **                 statement, possibly preceded by EXPLAIN and/or followed by
127239 **                 TEMP or TEMPORARY
127240 **
127241 **   (5) TRIGGER   We are in the middle of a trigger definition that must be
127242 **                 ended by a semicolon, the keyword END, and another semicolon.
127243 **
127244 **   (6) SEMI      We've seen the first semicolon in the ";END;" that occurs at
127245 **                 the end of a trigger definition.
127246 **
127247 **   (7) END       We've seen the ";END" of the ";END;" that occurs at the end
127248 **                 of a trigger definition.
127249 **
127250 ** Transitions between states above are determined by tokens extracted
127251 ** from the input.  The following tokens are significant:
127252 **
127253 **   (0) tkSEMI      A semicolon.
127254 **   (1) tkWS        Whitespace.
127255 **   (2) tkOTHER     Any other SQL token.
127256 **   (3) tkEXPLAIN   The "explain" keyword.
127257 **   (4) tkCREATE    The "create" keyword.
127258 **   (5) tkTEMP      The "temp" or "temporary" keyword.
127259 **   (6) tkTRIGGER   The "trigger" keyword.
127260 **   (7) tkEND       The "end" keyword.
127261 **
127262 ** Whitespace never causes a state transition and is always ignored.
127263 ** This means that a SQL string of all whitespace is invalid.
127264 **
127265 ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
127266 ** to recognize the end of a trigger can be omitted.  All we have to do
127267 ** is look for a semicolon that is not part of an string or comment.
127268 */
127269 SQLITE_API int SQLITE_STDCALL sqlite3_complete(const char *zSql){
127270   u8 state = 0;   /* Current state, using numbers defined in header comment */
127271   u8 token;       /* Value of the next token */
127272
127273 #ifndef SQLITE_OMIT_TRIGGER
127274   /* A complex statement machine used to detect the end of a CREATE TRIGGER
127275   ** statement.  This is the normal case.
127276   */
127277   static const u8 trans[8][8] = {
127278                      /* Token:                                                */
127279      /* State:       **  SEMI  WS  OTHER  EXPLAIN  CREATE  TEMP  TRIGGER  END */
127280      /* 0 INVALID: */ {    1,  0,     2,       3,      4,    2,       2,   2, },
127281      /* 1   START: */ {    1,  1,     2,       3,      4,    2,       2,   2, },
127282      /* 2  NORMAL: */ {    1,  2,     2,       2,      2,    2,       2,   2, },
127283      /* 3 EXPLAIN: */ {    1,  3,     3,       2,      4,    2,       2,   2, },
127284      /* 4  CREATE: */ {    1,  4,     2,       2,      2,    4,       5,   2, },
127285      /* 5 TRIGGER: */ {    6,  5,     5,       5,      5,    5,       5,   5, },
127286      /* 6    SEMI: */ {    6,  6,     5,       5,      5,    5,       5,   7, },
127287      /* 7     END: */ {    1,  7,     5,       5,      5,    5,       5,   5, },
127288   };
127289 #else
127290   /* If triggers are not supported by this compile then the statement machine
127291   ** used to detect the end of a statement is much simpler
127292   */
127293   static const u8 trans[3][3] = {
127294                      /* Token:           */
127295      /* State:       **  SEMI  WS  OTHER */
127296      /* 0 INVALID: */ {    1,  0,     2, },
127297      /* 1   START: */ {    1,  1,     2, },
127298      /* 2  NORMAL: */ {    1,  2,     2, },
127299   };
127300 #endif /* SQLITE_OMIT_TRIGGER */
127301
127302 #ifdef SQLITE_ENABLE_API_ARMOR
127303   if( zSql==0 ){
127304     (void)SQLITE_MISUSE_BKPT;
127305     return 0;
127306   }
127307 #endif
127308
127309   while( *zSql ){
127310     switch( *zSql ){
127311       case ';': {  /* A semicolon */
127312         token = tkSEMI;
127313         break;
127314       }
127315       case ' ':
127316       case '\r':
127317       case '\t':
127318       case '\n':
127319       case '\f': {  /* White space is ignored */
127320         token = tkWS;
127321         break;
127322       }
127323       case '/': {   /* C-style comments */
127324         if( zSql[1]!='*' ){
127325           token = tkOTHER;
127326           break;
127327         }
127328         zSql += 2;
127329         while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
127330         if( zSql[0]==0 ) return 0;
127331         zSql++;
127332         token = tkWS;
127333         break;
127334       }
127335       case '-': {   /* SQL-style comments from "--" to end of line */
127336         if( zSql[1]!='-' ){
127337           token = tkOTHER;
127338           break;
127339         }
127340         while( *zSql && *zSql!='\n' ){ zSql++; }
127341         if( *zSql==0 ) return state==1;
127342         token = tkWS;
127343         break;
127344       }
127345       case '[': {   /* Microsoft-style identifiers in [...] */
127346         zSql++;
127347         while( *zSql && *zSql!=']' ){ zSql++; }
127348         if( *zSql==0 ) return 0;
127349         token = tkOTHER;
127350         break;
127351       }
127352       case '`':     /* Grave-accent quoted symbols used by MySQL */
127353       case '"':     /* single- and double-quoted strings */
127354       case '\'': {
127355         int c = *zSql;
127356         zSql++;
127357         while( *zSql && *zSql!=c ){ zSql++; }
127358         if( *zSql==0 ) return 0;
127359         token = tkOTHER;
127360         break;
127361       }
127362       default: {
127363 #ifdef SQLITE_EBCDIC
127364         unsigned char c;
127365 #endif
127366         if( IdChar((u8)*zSql) ){
127367           /* Keywords and unquoted identifiers */
127368           int nId;
127369           for(nId=1; IdChar(zSql[nId]); nId++){}
127370 #ifdef SQLITE_OMIT_TRIGGER
127371           token = tkOTHER;
127372 #else
127373           switch( *zSql ){
127374             case 'c': case 'C': {
127375               if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
127376                 token = tkCREATE;
127377               }else{
127378                 token = tkOTHER;
127379               }
127380               break;
127381             }
127382             case 't': case 'T': {
127383               if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
127384                 token = tkTRIGGER;
127385               }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
127386                 token = tkTEMP;
127387               }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
127388                 token = tkTEMP;
127389               }else{
127390                 token = tkOTHER;
127391               }
127392               break;
127393             }
127394             case 'e':  case 'E': {
127395               if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
127396                 token = tkEND;
127397               }else
127398 #ifndef SQLITE_OMIT_EXPLAIN
127399               if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
127400                 token = tkEXPLAIN;
127401               }else
127402 #endif
127403               {
127404                 token = tkOTHER;
127405               }
127406               break;
127407             }
127408             default: {
127409               token = tkOTHER;
127410               break;
127411             }
127412           }
127413 #endif /* SQLITE_OMIT_TRIGGER */
127414           zSql += nId-1;
127415         }else{
127416           /* Operators and special symbols */
127417           token = tkOTHER;
127418         }
127419         break;
127420       }
127421     }
127422     state = trans[state][token];
127423     zSql++;
127424   }
127425   return state==1;
127426 }
127427
127428 #ifndef SQLITE_OMIT_UTF16
127429 /*
127430 ** This routine is the same as the sqlite3_complete() routine described
127431 ** above, except that the parameter is required to be UTF-16 encoded, not
127432 ** UTF-8.
127433 */
127434 SQLITE_API int SQLITE_STDCALL sqlite3_complete16(const void *zSql){
127435   sqlite3_value *pVal;
127436   char const *zSql8;
127437   int rc = SQLITE_NOMEM;
127438
127439 #ifndef SQLITE_OMIT_AUTOINIT
127440   rc = sqlite3_initialize();
127441   if( rc ) return rc;
127442 #endif
127443   pVal = sqlite3ValueNew(0);
127444   sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
127445   zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
127446   if( zSql8 ){
127447     rc = sqlite3_complete(zSql8);
127448   }else{
127449     rc = SQLITE_NOMEM;
127450   }
127451   sqlite3ValueFree(pVal);
127452   return sqlite3ApiExit(0, rc);
127453 }
127454 #endif /* SQLITE_OMIT_UTF16 */
127455 #endif /* SQLITE_OMIT_COMPLETE */
127456
127457 /************** End of complete.c ********************************************/
127458 /************** Begin file main.c ********************************************/
127459 /*
127460 ** 2001 September 15
127461 **
127462 ** The author disclaims copyright to this source code.  In place of
127463 ** a legal notice, here is a blessing:
127464 **
127465 **    May you do good and not evil.
127466 **    May you find forgiveness for yourself and forgive others.
127467 **    May you share freely, never taking more than you give.
127468 **
127469 *************************************************************************
127470 ** Main file for the SQLite library.  The routines in this file
127471 ** implement the programmer interface to the library.  Routines in
127472 ** other files are for internal use by SQLite and should not be
127473 ** accessed by users of the library.
127474 */
127475
127476 #ifdef SQLITE_ENABLE_FTS3
127477 /************** Include fts3.h in the middle of main.c ***********************/
127478 /************** Begin file fts3.h ********************************************/
127479 /*
127480 ** 2006 Oct 10
127481 **
127482 ** The author disclaims copyright to this source code.  In place of
127483 ** a legal notice, here is a blessing:
127484 **
127485 **    May you do good and not evil.
127486 **    May you find forgiveness for yourself and forgive others.
127487 **    May you share freely, never taking more than you give.
127488 **
127489 ******************************************************************************
127490 **
127491 ** This header file is used by programs that want to link against the
127492 ** FTS3 library.  All it does is declare the sqlite3Fts3Init() interface.
127493 */
127494
127495 #if 0
127496 extern "C" {
127497 #endif  /* __cplusplus */
127498
127499 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
127500
127501 #if 0
127502 }  /* extern "C" */
127503 #endif  /* __cplusplus */
127504
127505 /************** End of fts3.h ************************************************/
127506 /************** Continuing where we left off in main.c ***********************/
127507 #endif
127508 #ifdef SQLITE_ENABLE_RTREE
127509 /************** Include rtree.h in the middle of main.c **********************/
127510 /************** Begin file rtree.h *******************************************/
127511 /*
127512 ** 2008 May 26
127513 **
127514 ** The author disclaims copyright to this source code.  In place of
127515 ** a legal notice, here is a blessing:
127516 **
127517 **    May you do good and not evil.
127518 **    May you find forgiveness for yourself and forgive others.
127519 **    May you share freely, never taking more than you give.
127520 **
127521 ******************************************************************************
127522 **
127523 ** This header file is used by programs that want to link against the
127524 ** RTREE library.  All it does is declare the sqlite3RtreeInit() interface.
127525 */
127526
127527 #if 0
127528 extern "C" {
127529 #endif  /* __cplusplus */
127530
127531 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
127532
127533 #if 0
127534 }  /* extern "C" */
127535 #endif  /* __cplusplus */
127536
127537 /************** End of rtree.h ***********************************************/
127538 /************** Continuing where we left off in main.c ***********************/
127539 #endif
127540 #ifdef SQLITE_ENABLE_ICU
127541 /************** Include sqliteicu.h in the middle of main.c ******************/
127542 /************** Begin file sqliteicu.h ***************************************/
127543 /*
127544 ** 2008 May 26
127545 **
127546 ** The author disclaims copyright to this source code.  In place of
127547 ** a legal notice, here is a blessing:
127548 **
127549 **    May you do good and not evil.
127550 **    May you find forgiveness for yourself and forgive others.
127551 **    May you share freely, never taking more than you give.
127552 **
127553 ******************************************************************************
127554 **
127555 ** This header file is used by programs that want to link against the
127556 ** ICU extension.  All it does is declare the sqlite3IcuInit() interface.
127557 */
127558
127559 #if 0
127560 extern "C" {
127561 #endif  /* __cplusplus */
127562
127563 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
127564
127565 #if 0
127566 }  /* extern "C" */
127567 #endif  /* __cplusplus */
127568
127569
127570 /************** End of sqliteicu.h *******************************************/
127571 /************** Continuing where we left off in main.c ***********************/
127572 #endif
127573
127574 #ifndef SQLITE_AMALGAMATION
127575 /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
127576 ** contains the text of SQLITE_VERSION macro. 
127577 */
127578 SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
127579 #endif
127580
127581 /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
127582 ** a pointer to the to the sqlite3_version[] string constant. 
127583 */
127584 SQLITE_API const char *SQLITE_STDCALL sqlite3_libversion(void){ return sqlite3_version; }
127585
127586 /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
127587 ** pointer to a string constant whose value is the same as the
127588 ** SQLITE_SOURCE_ID C preprocessor macro. 
127589 */
127590 SQLITE_API const char *SQLITE_STDCALL sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
127591
127592 /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
127593 ** returns an integer equal to SQLITE_VERSION_NUMBER.
127594 */
127595 SQLITE_API int SQLITE_STDCALL sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
127596
127597 /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
127598 ** zero if and only if SQLite was compiled with mutexing code omitted due to
127599 ** the SQLITE_THREADSAFE compile-time option being set to 0.
127600 */
127601 SQLITE_API int SQLITE_STDCALL sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
127602
127603 #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
127604 /*
127605 ** If the following function pointer is not NULL and if
127606 ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
127607 ** I/O active are written using this function.  These messages
127608 ** are intended for debugging activity only.
127609 */
127610 SQLITE_API void (SQLITE_CDECL *sqlite3IoTrace)(const char*, ...) = 0;
127611 #endif
127612
127613 /*
127614 ** If the following global variable points to a string which is the
127615 ** name of a directory, then that directory will be used to store
127616 ** temporary files.
127617 **
127618 ** See also the "PRAGMA temp_store_directory" SQL command.
127619 */
127620 SQLITE_API char *sqlite3_temp_directory = 0;
127621
127622 /*
127623 ** If the following global variable points to a string which is the
127624 ** name of a directory, then that directory will be used to store
127625 ** all database files specified with a relative pathname.
127626 **
127627 ** See also the "PRAGMA data_store_directory" SQL command.
127628 */
127629 SQLITE_API char *sqlite3_data_directory = 0;
127630
127631 /*
127632 ** Initialize SQLite.  
127633 **
127634 ** This routine must be called to initialize the memory allocation,
127635 ** VFS, and mutex subsystems prior to doing any serious work with
127636 ** SQLite.  But as long as you do not compile with SQLITE_OMIT_AUTOINIT
127637 ** this routine will be called automatically by key routines such as
127638 ** sqlite3_open().  
127639 **
127640 ** This routine is a no-op except on its very first call for the process,
127641 ** or for the first call after a call to sqlite3_shutdown.
127642 **
127643 ** The first thread to call this routine runs the initialization to
127644 ** completion.  If subsequent threads call this routine before the first
127645 ** thread has finished the initialization process, then the subsequent
127646 ** threads must block until the first thread finishes with the initialization.
127647 **
127648 ** The first thread might call this routine recursively.  Recursive
127649 ** calls to this routine should not block, of course.  Otherwise the
127650 ** initialization process would never complete.
127651 **
127652 ** Let X be the first thread to enter this routine.  Let Y be some other
127653 ** thread.  Then while the initial invocation of this routine by X is
127654 ** incomplete, it is required that:
127655 **
127656 **    *  Calls to this routine from Y must block until the outer-most
127657 **       call by X completes.
127658 **
127659 **    *  Recursive calls to this routine from thread X return immediately
127660 **       without blocking.
127661 */
127662 SQLITE_API int SQLITE_STDCALL sqlite3_initialize(void){
127663   MUTEX_LOGIC( sqlite3_mutex *pMaster; )       /* The main static mutex */
127664   int rc;                                      /* Result code */
127665 #ifdef SQLITE_EXTRA_INIT
127666   int bRunExtraInit = 0;                       /* Extra initialization needed */
127667 #endif
127668
127669 #ifdef SQLITE_OMIT_WSD
127670   rc = sqlite3_wsd_init(4096, 24);
127671   if( rc!=SQLITE_OK ){
127672     return rc;
127673   }
127674 #endif
127675
127676   /* If the following assert() fails on some obscure processor/compiler
127677   ** combination, the work-around is to set the correct pointer
127678   ** size at compile-time using -DSQLITE_PTRSIZE=n compile-time option */
127679   assert( SQLITE_PTRSIZE==sizeof(char*) );
127680
127681   /* If SQLite is already completely initialized, then this call
127682   ** to sqlite3_initialize() should be a no-op.  But the initialization
127683   ** must be complete.  So isInit must not be set until the very end
127684   ** of this routine.
127685   */
127686   if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
127687
127688   /* Make sure the mutex subsystem is initialized.  If unable to 
127689   ** initialize the mutex subsystem, return early with the error.
127690   ** If the system is so sick that we are unable to allocate a mutex,
127691   ** there is not much SQLite is going to be able to do.
127692   **
127693   ** The mutex subsystem must take care of serializing its own
127694   ** initialization.
127695   */
127696   rc = sqlite3MutexInit();
127697   if( rc ) return rc;
127698
127699   /* Initialize the malloc() system and the recursive pInitMutex mutex.
127700   ** This operation is protected by the STATIC_MASTER mutex.  Note that
127701   ** MutexAlloc() is called for a static mutex prior to initializing the
127702   ** malloc subsystem - this implies that the allocation of a static
127703   ** mutex must not require support from the malloc subsystem.
127704   */
127705   MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
127706   sqlite3_mutex_enter(pMaster);
127707   sqlite3GlobalConfig.isMutexInit = 1;
127708   if( !sqlite3GlobalConfig.isMallocInit ){
127709     rc = sqlite3MallocInit();
127710   }
127711   if( rc==SQLITE_OK ){
127712     sqlite3GlobalConfig.isMallocInit = 1;
127713     if( !sqlite3GlobalConfig.pInitMutex ){
127714       sqlite3GlobalConfig.pInitMutex =
127715            sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
127716       if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
127717         rc = SQLITE_NOMEM;
127718       }
127719     }
127720   }
127721   if( rc==SQLITE_OK ){
127722     sqlite3GlobalConfig.nRefInitMutex++;
127723   }
127724   sqlite3_mutex_leave(pMaster);
127725
127726   /* If rc is not SQLITE_OK at this point, then either the malloc
127727   ** subsystem could not be initialized or the system failed to allocate
127728   ** the pInitMutex mutex. Return an error in either case.  */
127729   if( rc!=SQLITE_OK ){
127730     return rc;
127731   }
127732
127733   /* Do the rest of the initialization under the recursive mutex so
127734   ** that we will be able to handle recursive calls into
127735   ** sqlite3_initialize().  The recursive calls normally come through
127736   ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
127737   ** recursive calls might also be possible.
127738   **
127739   ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
127740   ** to the xInit method, so the xInit method need not be threadsafe.
127741   **
127742   ** The following mutex is what serializes access to the appdef pcache xInit
127743   ** methods.  The sqlite3_pcache_methods.xInit() all is embedded in the
127744   ** call to sqlite3PcacheInitialize().
127745   */
127746   sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
127747   if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
127748     FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
127749     sqlite3GlobalConfig.inProgress = 1;
127750     memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
127751     sqlite3RegisterGlobalFunctions();
127752     if( sqlite3GlobalConfig.isPCacheInit==0 ){
127753       rc = sqlite3PcacheInitialize();
127754     }
127755     if( rc==SQLITE_OK ){
127756       sqlite3GlobalConfig.isPCacheInit = 1;
127757       rc = sqlite3OsInit();
127758     }
127759     if( rc==SQLITE_OK ){
127760       sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage, 
127761           sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
127762       sqlite3GlobalConfig.isInit = 1;
127763 #ifdef SQLITE_EXTRA_INIT
127764       bRunExtraInit = 1;
127765 #endif
127766     }
127767     sqlite3GlobalConfig.inProgress = 0;
127768   }
127769   sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
127770
127771   /* Go back under the static mutex and clean up the recursive
127772   ** mutex to prevent a resource leak.
127773   */
127774   sqlite3_mutex_enter(pMaster);
127775   sqlite3GlobalConfig.nRefInitMutex--;
127776   if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
127777     assert( sqlite3GlobalConfig.nRefInitMutex==0 );
127778     sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
127779     sqlite3GlobalConfig.pInitMutex = 0;
127780   }
127781   sqlite3_mutex_leave(pMaster);
127782
127783   /* The following is just a sanity check to make sure SQLite has
127784   ** been compiled correctly.  It is important to run this code, but
127785   ** we don't want to run it too often and soak up CPU cycles for no
127786   ** reason.  So we run it once during initialization.
127787   */
127788 #ifndef NDEBUG
127789 #ifndef SQLITE_OMIT_FLOATING_POINT
127790   /* This section of code's only "output" is via assert() statements. */
127791   if ( rc==SQLITE_OK ){
127792     u64 x = (((u64)1)<<63)-1;
127793     double y;
127794     assert(sizeof(x)==8);
127795     assert(sizeof(x)==sizeof(y));
127796     memcpy(&y, &x, 8);
127797     assert( sqlite3IsNaN(y) );
127798   }
127799 #endif
127800 #endif
127801
127802   /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
127803   ** compile-time option.
127804   */
127805 #ifdef SQLITE_EXTRA_INIT
127806   if( bRunExtraInit ){
127807     int SQLITE_EXTRA_INIT(const char*);
127808     rc = SQLITE_EXTRA_INIT(0);
127809   }
127810 #endif
127811
127812   return rc;
127813 }
127814
127815 /*
127816 ** Undo the effects of sqlite3_initialize().  Must not be called while
127817 ** there are outstanding database connections or memory allocations or
127818 ** while any part of SQLite is otherwise in use in any thread.  This
127819 ** routine is not threadsafe.  But it is safe to invoke this routine
127820 ** on when SQLite is already shut down.  If SQLite is already shut down
127821 ** when this routine is invoked, then this routine is a harmless no-op.
127822 */
127823 SQLITE_API int SQLITE_STDCALL sqlite3_shutdown(void){
127824 #ifdef SQLITE_OMIT_WSD
127825   int rc = sqlite3_wsd_init(4096, 24);
127826   if( rc!=SQLITE_OK ){
127827     return rc;
127828   }
127829 #endif
127830
127831   if( sqlite3GlobalConfig.isInit ){
127832 #ifdef SQLITE_EXTRA_SHUTDOWN
127833     void SQLITE_EXTRA_SHUTDOWN(void);
127834     SQLITE_EXTRA_SHUTDOWN();
127835 #endif
127836     sqlite3_os_end();
127837     sqlite3_reset_auto_extension();
127838     sqlite3GlobalConfig.isInit = 0;
127839   }
127840   if( sqlite3GlobalConfig.isPCacheInit ){
127841     sqlite3PcacheShutdown();
127842     sqlite3GlobalConfig.isPCacheInit = 0;
127843   }
127844   if( sqlite3GlobalConfig.isMallocInit ){
127845     sqlite3MallocEnd();
127846     sqlite3GlobalConfig.isMallocInit = 0;
127847
127848 #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
127849     /* The heap subsystem has now been shutdown and these values are supposed
127850     ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
127851     ** which would rely on that heap subsystem; therefore, make sure these
127852     ** values cannot refer to heap memory that was just invalidated when the
127853     ** heap subsystem was shutdown.  This is only done if the current call to
127854     ** this function resulted in the heap subsystem actually being shutdown.
127855     */
127856     sqlite3_data_directory = 0;
127857     sqlite3_temp_directory = 0;
127858 #endif
127859   }
127860   if( sqlite3GlobalConfig.isMutexInit ){
127861     sqlite3MutexEnd();
127862     sqlite3GlobalConfig.isMutexInit = 0;
127863   }
127864
127865   return SQLITE_OK;
127866 }
127867
127868 /*
127869 ** This API allows applications to modify the global configuration of
127870 ** the SQLite library at run-time.
127871 **
127872 ** This routine should only be called when there are no outstanding
127873 ** database connections or memory allocations.  This routine is not
127874 ** threadsafe.  Failure to heed these warnings can lead to unpredictable
127875 ** behavior.
127876 */
127877 SQLITE_API int SQLITE_CDECL sqlite3_config(int op, ...){
127878   va_list ap;
127879   int rc = SQLITE_OK;
127880
127881   /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
127882   ** the SQLite library is in use. */
127883   if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
127884
127885   va_start(ap, op);
127886   switch( op ){
127887
127888     /* Mutex configuration options are only available in a threadsafe
127889     ** compile.
127890     */
127891 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0  /* IMP: R-54466-46756 */
127892     case SQLITE_CONFIG_SINGLETHREAD: {
127893       /* EVIDENCE-OF: R-02748-19096 This option sets the threading mode to
127894       ** Single-thread. */
127895       sqlite3GlobalConfig.bCoreMutex = 0;  /* Disable mutex on core */
127896       sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
127897       break;
127898     }
127899 #endif
127900 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-20520-54086 */
127901     case SQLITE_CONFIG_MULTITHREAD: {
127902       /* EVIDENCE-OF: R-14374-42468 This option sets the threading mode to
127903       ** Multi-thread. */
127904       sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
127905       sqlite3GlobalConfig.bFullMutex = 0;  /* Disable mutex on connections */
127906       break;
127907     }
127908 #endif
127909 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-59593-21810 */
127910     case SQLITE_CONFIG_SERIALIZED: {
127911       /* EVIDENCE-OF: R-41220-51800 This option sets the threading mode to
127912       ** Serialized. */
127913       sqlite3GlobalConfig.bCoreMutex = 1;  /* Enable mutex on core */
127914       sqlite3GlobalConfig.bFullMutex = 1;  /* Enable mutex on connections */
127915       break;
127916     }
127917 #endif
127918 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-63666-48755 */
127919     case SQLITE_CONFIG_MUTEX: {
127920       /* Specify an alternative mutex implementation */
127921       sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
127922       break;
127923     }
127924 #endif
127925 #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0 /* IMP: R-14450-37597 */
127926     case SQLITE_CONFIG_GETMUTEX: {
127927       /* Retrieve the current mutex implementation */
127928       *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
127929       break;
127930     }
127931 #endif
127932
127933     case SQLITE_CONFIG_MALLOC: {
127934       /* EVIDENCE-OF: R-55594-21030 The SQLITE_CONFIG_MALLOC option takes a
127935       ** single argument which is a pointer to an instance of the
127936       ** sqlite3_mem_methods structure. The argument specifies alternative
127937       ** low-level memory allocation routines to be used in place of the memory
127938       ** allocation routines built into SQLite. */
127939       sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
127940       break;
127941     }
127942     case SQLITE_CONFIG_GETMALLOC: {
127943       /* EVIDENCE-OF: R-51213-46414 The SQLITE_CONFIG_GETMALLOC option takes a
127944       ** single argument which is a pointer to an instance of the
127945       ** sqlite3_mem_methods structure. The sqlite3_mem_methods structure is
127946       ** filled with the currently defined memory allocation routines. */
127947       if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
127948       *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
127949       break;
127950     }
127951     case SQLITE_CONFIG_MEMSTATUS: {
127952       /* EVIDENCE-OF: R-61275-35157 The SQLITE_CONFIG_MEMSTATUS option takes
127953       ** single argument of type int, interpreted as a boolean, which enables
127954       ** or disables the collection of memory allocation statistics. */
127955       sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
127956       break;
127957     }
127958     case SQLITE_CONFIG_SCRATCH: {
127959       /* EVIDENCE-OF: R-08404-60887 There are three arguments to
127960       ** SQLITE_CONFIG_SCRATCH: A pointer an 8-byte aligned memory buffer from
127961       ** which the scratch allocations will be drawn, the size of each scratch
127962       ** allocation (sz), and the maximum number of scratch allocations (N). */
127963       sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
127964       sqlite3GlobalConfig.szScratch = va_arg(ap, int);
127965       sqlite3GlobalConfig.nScratch = va_arg(ap, int);
127966       break;
127967     }
127968     case SQLITE_CONFIG_PAGECACHE: {
127969       /* EVIDENCE-OF: R-31408-40510 There are three arguments to
127970       ** SQLITE_CONFIG_PAGECACHE: A pointer to 8-byte aligned memory, the size
127971       ** of each page buffer (sz), and the number of pages (N). */
127972       sqlite3GlobalConfig.pPage = va_arg(ap, void*);
127973       sqlite3GlobalConfig.szPage = va_arg(ap, int);
127974       sqlite3GlobalConfig.nPage = va_arg(ap, int);
127975       break;
127976     }
127977     case SQLITE_CONFIG_PCACHE_HDRSZ: {
127978       /* EVIDENCE-OF: R-39100-27317 The SQLITE_CONFIG_PCACHE_HDRSZ option takes
127979       ** a single parameter which is a pointer to an integer and writes into
127980       ** that integer the number of extra bytes per page required for each page
127981       ** in SQLITE_CONFIG_PAGECACHE. */
127982       *va_arg(ap, int*) = 
127983           sqlite3HeaderSizeBtree() +
127984           sqlite3HeaderSizePcache() +
127985           sqlite3HeaderSizePcache1();
127986       break;
127987     }
127988
127989     case SQLITE_CONFIG_PCACHE: {
127990       /* no-op */
127991       break;
127992     }
127993     case SQLITE_CONFIG_GETPCACHE: {
127994       /* now an error */
127995       rc = SQLITE_ERROR;
127996       break;
127997     }
127998
127999     case SQLITE_CONFIG_PCACHE2: {
128000       /* EVIDENCE-OF: R-63325-48378 The SQLITE_CONFIG_PCACHE2 option takes a
128001       ** single argument which is a pointer to an sqlite3_pcache_methods2
128002       ** object. This object specifies the interface to a custom page cache
128003       ** implementation. */
128004       sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
128005       break;
128006     }
128007     case SQLITE_CONFIG_GETPCACHE2: {
128008       /* EVIDENCE-OF: R-22035-46182 The SQLITE_CONFIG_GETPCACHE2 option takes a
128009       ** single argument which is a pointer to an sqlite3_pcache_methods2
128010       ** object. SQLite copies of the current page cache implementation into
128011       ** that object. */
128012       if( sqlite3GlobalConfig.pcache2.xInit==0 ){
128013         sqlite3PCacheSetDefault();
128014       }
128015       *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
128016       break;
128017     }
128018
128019 /* EVIDENCE-OF: R-06626-12911 The SQLITE_CONFIG_HEAP option is only
128020 ** available if SQLite is compiled with either SQLITE_ENABLE_MEMSYS3 or
128021 ** SQLITE_ENABLE_MEMSYS5 and returns SQLITE_ERROR if invoked otherwise. */
128022 #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
128023     case SQLITE_CONFIG_HEAP: {
128024       /* EVIDENCE-OF: R-19854-42126 There are three arguments to
128025       ** SQLITE_CONFIG_HEAP: An 8-byte aligned pointer to the memory, the
128026       ** number of bytes in the memory buffer, and the minimum allocation size.
128027       */
128028       sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
128029       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
128030       sqlite3GlobalConfig.mnReq = va_arg(ap, int);
128031
128032       if( sqlite3GlobalConfig.mnReq<1 ){
128033         sqlite3GlobalConfig.mnReq = 1;
128034       }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
128035         /* cap min request size at 2^12 */
128036         sqlite3GlobalConfig.mnReq = (1<<12);
128037       }
128038
128039       if( sqlite3GlobalConfig.pHeap==0 ){
128040         /* EVIDENCE-OF: R-49920-60189 If the first pointer (the memory pointer)
128041         ** is NULL, then SQLite reverts to using its default memory allocator
128042         ** (the system malloc() implementation), undoing any prior invocation of
128043         ** SQLITE_CONFIG_MALLOC.
128044         **
128045         ** Setting sqlite3GlobalConfig.m to all zeros will cause malloc to
128046         ** revert to its default implementation when sqlite3_initialize() is run
128047         */
128048         memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
128049       }else{
128050         /* EVIDENCE-OF: R-61006-08918 If the memory pointer is not NULL then the
128051         ** alternative memory allocator is engaged to handle all of SQLites
128052         ** memory allocation needs. */
128053 #ifdef SQLITE_ENABLE_MEMSYS3
128054         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
128055 #endif
128056 #ifdef SQLITE_ENABLE_MEMSYS5
128057         sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
128058 #endif
128059       }
128060       break;
128061     }
128062 #endif
128063
128064     case SQLITE_CONFIG_LOOKASIDE: {
128065       sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
128066       sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
128067       break;
128068     }
128069     
128070     /* Record a pointer to the logger function and its first argument.
128071     ** The default is NULL.  Logging is disabled if the function pointer is
128072     ** NULL.
128073     */
128074     case SQLITE_CONFIG_LOG: {
128075       /* MSVC is picky about pulling func ptrs from va lists.
128076       ** http://support.microsoft.com/kb/47961
128077       ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
128078       */
128079       typedef void(*LOGFUNC_t)(void*,int,const char*);
128080       sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
128081       sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
128082       break;
128083     }
128084
128085     /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
128086     ** can be changed at start-time using the
128087     ** sqlite3_config(SQLITE_CONFIG_URI,1) or
128088     ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
128089     */
128090     case SQLITE_CONFIG_URI: {
128091       /* EVIDENCE-OF: R-25451-61125 The SQLITE_CONFIG_URI option takes a single
128092       ** argument of type int. If non-zero, then URI handling is globally
128093       ** enabled. If the parameter is zero, then URI handling is globally
128094       ** disabled. */
128095       sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
128096       break;
128097     }
128098
128099     case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
128100       /* EVIDENCE-OF: R-36592-02772 The SQLITE_CONFIG_COVERING_INDEX_SCAN
128101       ** option takes a single integer argument which is interpreted as a
128102       ** boolean in order to enable or disable the use of covering indices for
128103       ** full table scans in the query optimizer. */
128104       sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
128105       break;
128106     }
128107
128108 #ifdef SQLITE_ENABLE_SQLLOG
128109     case SQLITE_CONFIG_SQLLOG: {
128110       typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
128111       sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
128112       sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
128113       break;
128114     }
128115 #endif
128116
128117     case SQLITE_CONFIG_MMAP_SIZE: {
128118       /* EVIDENCE-OF: R-58063-38258 SQLITE_CONFIG_MMAP_SIZE takes two 64-bit
128119       ** integer (sqlite3_int64) values that are the default mmap size limit
128120       ** (the default setting for PRAGMA mmap_size) and the maximum allowed
128121       ** mmap size limit. */
128122       sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
128123       sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
128124       /* EVIDENCE-OF: R-53367-43190 If either argument to this option is
128125       ** negative, then that argument is changed to its compile-time default.
128126       **
128127       ** EVIDENCE-OF: R-34993-45031 The maximum allowed mmap size will be
128128       ** silently truncated if necessary so that it does not exceed the
128129       ** compile-time maximum mmap size set by the SQLITE_MAX_MMAP_SIZE
128130       ** compile-time option.
128131       */
128132       if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
128133         mxMmap = SQLITE_MAX_MMAP_SIZE;
128134       }
128135       if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
128136       if( szMmap>mxMmap) szMmap = mxMmap;
128137       sqlite3GlobalConfig.mxMmap = mxMmap;
128138       sqlite3GlobalConfig.szMmap = szMmap;
128139       break;
128140     }
128141
128142 #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC) /* IMP: R-04780-55815 */
128143     case SQLITE_CONFIG_WIN32_HEAPSIZE: {
128144       /* EVIDENCE-OF: R-34926-03360 SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit
128145       ** unsigned integer value that specifies the maximum size of the created
128146       ** heap. */
128147       sqlite3GlobalConfig.nHeap = va_arg(ap, int);
128148       break;
128149     }
128150 #endif
128151
128152     case SQLITE_CONFIG_PMASZ: {
128153       sqlite3GlobalConfig.szPma = va_arg(ap, unsigned int);
128154       break;
128155     }
128156
128157     default: {
128158       rc = SQLITE_ERROR;
128159       break;
128160     }
128161   }
128162   va_end(ap);
128163   return rc;
128164 }
128165
128166 /*
128167 ** Set up the lookaside buffers for a database connection.
128168 ** Return SQLITE_OK on success.  
128169 ** If lookaside is already active, return SQLITE_BUSY.
128170 **
128171 ** The sz parameter is the number of bytes in each lookaside slot.
128172 ** The cnt parameter is the number of slots.  If pStart is NULL the
128173 ** space for the lookaside memory is obtained from sqlite3_malloc().
128174 ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
128175 ** the lookaside memory.
128176 */
128177 static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
128178   void *pStart;
128179   if( db->lookaside.nOut ){
128180     return SQLITE_BUSY;
128181   }
128182   /* Free any existing lookaside buffer for this handle before
128183   ** allocating a new one so we don't have to have space for 
128184   ** both at the same time.
128185   */
128186   if( db->lookaside.bMalloced ){
128187     sqlite3_free(db->lookaside.pStart);
128188   }
128189   /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
128190   ** than a pointer to be useful.
128191   */
128192   sz = ROUNDDOWN8(sz);  /* IMP: R-33038-09382 */
128193   if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
128194   if( cnt<0 ) cnt = 0;
128195   if( sz==0 || cnt==0 ){
128196     sz = 0;
128197     pStart = 0;
128198   }else if( pBuf==0 ){
128199     sqlite3BeginBenignMalloc();
128200     pStart = sqlite3Malloc( sz*cnt );  /* IMP: R-61949-35727 */
128201     sqlite3EndBenignMalloc();
128202     if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
128203   }else{
128204     pStart = pBuf;
128205   }
128206   db->lookaside.pStart = pStart;
128207   db->lookaside.pFree = 0;
128208   db->lookaside.sz = (u16)sz;
128209   if( pStart ){
128210     int i;
128211     LookasideSlot *p;
128212     assert( sz > (int)sizeof(LookasideSlot*) );
128213     p = (LookasideSlot*)pStart;
128214     for(i=cnt-1; i>=0; i--){
128215       p->pNext = db->lookaside.pFree;
128216       db->lookaside.pFree = p;
128217       p = (LookasideSlot*)&((u8*)p)[sz];
128218     }
128219     db->lookaside.pEnd = p;
128220     db->lookaside.bEnabled = 1;
128221     db->lookaside.bMalloced = pBuf==0 ?1:0;
128222   }else{
128223     db->lookaside.pStart = db;
128224     db->lookaside.pEnd = db;
128225     db->lookaside.bEnabled = 0;
128226     db->lookaside.bMalloced = 0;
128227   }
128228   return SQLITE_OK;
128229 }
128230
128231 /*
128232 ** Return the mutex associated with a database connection.
128233 */
128234 SQLITE_API sqlite3_mutex *SQLITE_STDCALL sqlite3_db_mutex(sqlite3 *db){
128235 #ifdef SQLITE_ENABLE_API_ARMOR
128236   if( !sqlite3SafetyCheckOk(db) ){
128237     (void)SQLITE_MISUSE_BKPT;
128238     return 0;
128239   }
128240 #endif
128241   return db->mutex;
128242 }
128243
128244 /*
128245 ** Free up as much memory as we can from the given database
128246 ** connection.
128247 */
128248 SQLITE_API int SQLITE_STDCALL sqlite3_db_release_memory(sqlite3 *db){
128249   int i;
128250
128251 #ifdef SQLITE_ENABLE_API_ARMOR
128252   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
128253 #endif
128254   sqlite3_mutex_enter(db->mutex);
128255   sqlite3BtreeEnterAll(db);
128256   for(i=0; i<db->nDb; i++){
128257     Btree *pBt = db->aDb[i].pBt;
128258     if( pBt ){
128259       Pager *pPager = sqlite3BtreePager(pBt);
128260       sqlite3PagerShrink(pPager);
128261     }
128262   }
128263   sqlite3BtreeLeaveAll(db);
128264   sqlite3_mutex_leave(db->mutex);
128265   return SQLITE_OK;
128266 }
128267
128268 /*
128269 ** Configuration settings for an individual database connection
128270 */
128271 SQLITE_API int SQLITE_CDECL sqlite3_db_config(sqlite3 *db, int op, ...){
128272   va_list ap;
128273   int rc;
128274   va_start(ap, op);
128275   switch( op ){
128276     case SQLITE_DBCONFIG_LOOKASIDE: {
128277       void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
128278       int sz = va_arg(ap, int);       /* IMP: R-47871-25994 */
128279       int cnt = va_arg(ap, int);      /* IMP: R-04460-53386 */
128280       rc = setupLookaside(db, pBuf, sz, cnt);
128281       break;
128282     }
128283     default: {
128284       static const struct {
128285         int op;      /* The opcode */
128286         u32 mask;    /* Mask of the bit in sqlite3.flags to set/clear */
128287       } aFlagOp[] = {
128288         { SQLITE_DBCONFIG_ENABLE_FKEY,    SQLITE_ForeignKeys    },
128289         { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger  },
128290       };
128291       unsigned int i;
128292       rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
128293       for(i=0; i<ArraySize(aFlagOp); i++){
128294         if( aFlagOp[i].op==op ){
128295           int onoff = va_arg(ap, int);
128296           int *pRes = va_arg(ap, int*);
128297           int oldFlags = db->flags;
128298           if( onoff>0 ){
128299             db->flags |= aFlagOp[i].mask;
128300           }else if( onoff==0 ){
128301             db->flags &= ~aFlagOp[i].mask;
128302           }
128303           if( oldFlags!=db->flags ){
128304             sqlite3ExpirePreparedStatements(db);
128305           }
128306           if( pRes ){
128307             *pRes = (db->flags & aFlagOp[i].mask)!=0;
128308           }
128309           rc = SQLITE_OK;
128310           break;
128311         }
128312       }
128313       break;
128314     }
128315   }
128316   va_end(ap);
128317   return rc;
128318 }
128319
128320
128321 /*
128322 ** Return true if the buffer z[0..n-1] contains all spaces.
128323 */
128324 static int allSpaces(const char *z, int n){
128325   while( n>0 && z[n-1]==' ' ){ n--; }
128326   return n==0;
128327 }
128328
128329 /*
128330 ** This is the default collating function named "BINARY" which is always
128331 ** available.
128332 **
128333 ** If the padFlag argument is not NULL then space padding at the end
128334 ** of strings is ignored.  This implements the RTRIM collation.
128335 */
128336 static int binCollFunc(
128337   void *padFlag,
128338   int nKey1, const void *pKey1,
128339   int nKey2, const void *pKey2
128340 ){
128341   int rc, n;
128342   n = nKey1<nKey2 ? nKey1 : nKey2;
128343   /* EVIDENCE-OF: R-65033-28449 The built-in BINARY collation compares
128344   ** strings byte by byte using the memcmp() function from the standard C
128345   ** library. */
128346   rc = memcmp(pKey1, pKey2, n);
128347   if( rc==0 ){
128348     if( padFlag
128349      && allSpaces(((char*)pKey1)+n, nKey1-n)
128350      && allSpaces(((char*)pKey2)+n, nKey2-n)
128351     ){
128352       /* EVIDENCE-OF: R-31624-24737 RTRIM is like BINARY except that extra
128353       ** spaces at the end of either string do not change the result. In other
128354       ** words, strings will compare equal to one another as long as they
128355       ** differ only in the number of spaces at the end.
128356       */
128357     }else{
128358       rc = nKey1 - nKey2;
128359     }
128360   }
128361   return rc;
128362 }
128363
128364 /*
128365 ** Another built-in collating sequence: NOCASE. 
128366 **
128367 ** This collating sequence is intended to be used for "case independent
128368 ** comparison". SQLite's knowledge of upper and lower case equivalents
128369 ** extends only to the 26 characters used in the English language.
128370 **
128371 ** At the moment there is only a UTF-8 implementation.
128372 */
128373 static int nocaseCollatingFunc(
128374   void *NotUsed,
128375   int nKey1, const void *pKey1,
128376   int nKey2, const void *pKey2
128377 ){
128378   int r = sqlite3StrNICmp(
128379       (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
128380   UNUSED_PARAMETER(NotUsed);
128381   if( 0==r ){
128382     r = nKey1-nKey2;
128383   }
128384   return r;
128385 }
128386
128387 /*
128388 ** Return the ROWID of the most recent insert
128389 */
128390 SQLITE_API sqlite_int64 SQLITE_STDCALL sqlite3_last_insert_rowid(sqlite3 *db){
128391 #ifdef SQLITE_ENABLE_API_ARMOR
128392   if( !sqlite3SafetyCheckOk(db) ){
128393     (void)SQLITE_MISUSE_BKPT;
128394     return 0;
128395   }
128396 #endif
128397   return db->lastRowid;
128398 }
128399
128400 /*
128401 ** Return the number of changes in the most recent call to sqlite3_exec().
128402 */
128403 SQLITE_API int SQLITE_STDCALL sqlite3_changes(sqlite3 *db){
128404 #ifdef SQLITE_ENABLE_API_ARMOR
128405   if( !sqlite3SafetyCheckOk(db) ){
128406     (void)SQLITE_MISUSE_BKPT;
128407     return 0;
128408   }
128409 #endif
128410   return db->nChange;
128411 }
128412
128413 /*
128414 ** Return the number of changes since the database handle was opened.
128415 */
128416 SQLITE_API int SQLITE_STDCALL sqlite3_total_changes(sqlite3 *db){
128417 #ifdef SQLITE_ENABLE_API_ARMOR
128418   if( !sqlite3SafetyCheckOk(db) ){
128419     (void)SQLITE_MISUSE_BKPT;
128420     return 0;
128421   }
128422 #endif
128423   return db->nTotalChange;
128424 }
128425
128426 /*
128427 ** Close all open savepoints. This function only manipulates fields of the
128428 ** database handle object, it does not close any savepoints that may be open
128429 ** at the b-tree/pager level.
128430 */
128431 SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
128432   while( db->pSavepoint ){
128433     Savepoint *pTmp = db->pSavepoint;
128434     db->pSavepoint = pTmp->pNext;
128435     sqlite3DbFree(db, pTmp);
128436   }
128437   db->nSavepoint = 0;
128438   db->nStatement = 0;
128439   db->isTransactionSavepoint = 0;
128440 }
128441
128442 /*
128443 ** Invoke the destructor function associated with FuncDef p, if any. Except,
128444 ** if this is not the last copy of the function, do not invoke it. Multiple
128445 ** copies of a single function are created when create_function() is called
128446 ** with SQLITE_ANY as the encoding.
128447 */
128448 static void functionDestroy(sqlite3 *db, FuncDef *p){
128449   FuncDestructor *pDestructor = p->pDestructor;
128450   if( pDestructor ){
128451     pDestructor->nRef--;
128452     if( pDestructor->nRef==0 ){
128453       pDestructor->xDestroy(pDestructor->pUserData);
128454       sqlite3DbFree(db, pDestructor);
128455     }
128456   }
128457 }
128458
128459 /*
128460 ** Disconnect all sqlite3_vtab objects that belong to database connection
128461 ** db. This is called when db is being closed.
128462 */
128463 static void disconnectAllVtab(sqlite3 *db){
128464 #ifndef SQLITE_OMIT_VIRTUALTABLE
128465   int i;
128466   sqlite3BtreeEnterAll(db);
128467   for(i=0; i<db->nDb; i++){
128468     Schema *pSchema = db->aDb[i].pSchema;
128469     if( db->aDb[i].pSchema ){
128470       HashElem *p;
128471       for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
128472         Table *pTab = (Table *)sqliteHashData(p);
128473         if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
128474       }
128475     }
128476   }
128477   sqlite3VtabUnlockList(db);
128478   sqlite3BtreeLeaveAll(db);
128479 #else
128480   UNUSED_PARAMETER(db);
128481 #endif
128482 }
128483
128484 /*
128485 ** Return TRUE if database connection db has unfinalized prepared
128486 ** statements or unfinished sqlite3_backup objects.  
128487 */
128488 static int connectionIsBusy(sqlite3 *db){
128489   int j;
128490   assert( sqlite3_mutex_held(db->mutex) );
128491   if( db->pVdbe ) return 1;
128492   for(j=0; j<db->nDb; j++){
128493     Btree *pBt = db->aDb[j].pBt;
128494     if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
128495   }
128496   return 0;
128497 }
128498
128499 /*
128500 ** Close an existing SQLite database
128501 */
128502 static int sqlite3Close(sqlite3 *db, int forceZombie){
128503   if( !db ){
128504     /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
128505     ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
128506     return SQLITE_OK;
128507   }
128508   if( !sqlite3SafetyCheckSickOrOk(db) ){
128509     return SQLITE_MISUSE_BKPT;
128510   }
128511   sqlite3_mutex_enter(db->mutex);
128512
128513   /* Force xDisconnect calls on all virtual tables */
128514   disconnectAllVtab(db);
128515
128516   /* If a transaction is open, the disconnectAllVtab() call above
128517   ** will not have called the xDisconnect() method on any virtual
128518   ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
128519   ** call will do so. We need to do this before the check for active
128520   ** SQL statements below, as the v-table implementation may be storing
128521   ** some prepared statements internally.
128522   */
128523   sqlite3VtabRollback(db);
128524
128525   /* Legacy behavior (sqlite3_close() behavior) is to return
128526   ** SQLITE_BUSY if the connection can not be closed immediately.
128527   */
128528   if( !forceZombie && connectionIsBusy(db) ){
128529     sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
128530        "statements or unfinished backups");
128531     sqlite3_mutex_leave(db->mutex);
128532     return SQLITE_BUSY;
128533   }
128534
128535 #ifdef SQLITE_ENABLE_SQLLOG
128536   if( sqlite3GlobalConfig.xSqllog ){
128537     /* Closing the handle. Fourth parameter is passed the value 2. */
128538     sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
128539   }
128540 #endif
128541
128542   /* Convert the connection into a zombie and then close it.
128543   */
128544   db->magic = SQLITE_MAGIC_ZOMBIE;
128545   sqlite3LeaveMutexAndCloseZombie(db);
128546   return SQLITE_OK;
128547 }
128548
128549 /*
128550 ** Two variations on the public interface for closing a database
128551 ** connection. The sqlite3_close() version returns SQLITE_BUSY and
128552 ** leaves the connection option if there are unfinalized prepared
128553 ** statements or unfinished sqlite3_backups.  The sqlite3_close_v2()
128554 ** version forces the connection to become a zombie if there are
128555 ** unclosed resources, and arranges for deallocation when the last
128556 ** prepare statement or sqlite3_backup closes.
128557 */
128558 SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
128559 SQLITE_API int SQLITE_STDCALL sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
128560
128561
128562 /*
128563 ** Close the mutex on database connection db.
128564 **
128565 ** Furthermore, if database connection db is a zombie (meaning that there
128566 ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
128567 ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
128568 ** finished, then free all resources.
128569 */
128570 SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
128571   HashElem *i;                    /* Hash table iterator */
128572   int j;
128573
128574   /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
128575   ** or if the connection has not yet been closed by sqlite3_close_v2(),
128576   ** then just leave the mutex and return.
128577   */
128578   if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
128579     sqlite3_mutex_leave(db->mutex);
128580     return;
128581   }
128582
128583   /* If we reach this point, it means that the database connection has
128584   ** closed all sqlite3_stmt and sqlite3_backup objects and has been
128585   ** passed to sqlite3_close (meaning that it is a zombie).  Therefore,
128586   ** go ahead and free all resources.
128587   */
128588
128589   /* If a transaction is open, roll it back. This also ensures that if
128590   ** any database schemas have been modified by an uncommitted transaction
128591   ** they are reset. And that the required b-tree mutex is held to make
128592   ** the pager rollback and schema reset an atomic operation. */
128593   sqlite3RollbackAll(db, SQLITE_OK);
128594
128595   /* Free any outstanding Savepoint structures. */
128596   sqlite3CloseSavepoints(db);
128597
128598   /* Close all database connections */
128599   for(j=0; j<db->nDb; j++){
128600     struct Db *pDb = &db->aDb[j];
128601     if( pDb->pBt ){
128602       sqlite3BtreeClose(pDb->pBt);
128603       pDb->pBt = 0;
128604       if( j!=1 ){
128605         pDb->pSchema = 0;
128606       }
128607     }
128608   }
128609   /* Clear the TEMP schema separately and last */
128610   if( db->aDb[1].pSchema ){
128611     sqlite3SchemaClear(db->aDb[1].pSchema);
128612   }
128613   sqlite3VtabUnlockList(db);
128614
128615   /* Free up the array of auxiliary databases */
128616   sqlite3CollapseDatabaseArray(db);
128617   assert( db->nDb<=2 );
128618   assert( db->aDb==db->aDbStatic );
128619
128620   /* Tell the code in notify.c that the connection no longer holds any
128621   ** locks and does not require any further unlock-notify callbacks.
128622   */
128623   sqlite3ConnectionClosed(db);
128624
128625   for(j=0; j<ArraySize(db->aFunc.a); j++){
128626     FuncDef *pNext, *pHash, *p;
128627     for(p=db->aFunc.a[j]; p; p=pHash){
128628       pHash = p->pHash;
128629       while( p ){
128630         functionDestroy(db, p);
128631         pNext = p->pNext;
128632         sqlite3DbFree(db, p);
128633         p = pNext;
128634       }
128635     }
128636   }
128637   for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
128638     CollSeq *pColl = (CollSeq *)sqliteHashData(i);
128639     /* Invoke any destructors registered for collation sequence user data. */
128640     for(j=0; j<3; j++){
128641       if( pColl[j].xDel ){
128642         pColl[j].xDel(pColl[j].pUser);
128643       }
128644     }
128645     sqlite3DbFree(db, pColl);
128646   }
128647   sqlite3HashClear(&db->aCollSeq);
128648 #ifndef SQLITE_OMIT_VIRTUALTABLE
128649   for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
128650     Module *pMod = (Module *)sqliteHashData(i);
128651     if( pMod->xDestroy ){
128652       pMod->xDestroy(pMod->pAux);
128653     }
128654     sqlite3DbFree(db, pMod);
128655   }
128656   sqlite3HashClear(&db->aModule);
128657 #endif
128658
128659   sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
128660   sqlite3ValueFree(db->pErr);
128661   sqlite3CloseExtensions(db);
128662 #if SQLITE_USER_AUTHENTICATION
128663   sqlite3_free(db->auth.zAuthUser);
128664   sqlite3_free(db->auth.zAuthPW);
128665 #endif
128666
128667   db->magic = SQLITE_MAGIC_ERROR;
128668
128669   /* The temp-database schema is allocated differently from the other schema
128670   ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
128671   ** So it needs to be freed here. Todo: Why not roll the temp schema into
128672   ** the same sqliteMalloc() as the one that allocates the database 
128673   ** structure?
128674   */
128675   sqlite3DbFree(db, db->aDb[1].pSchema);
128676   sqlite3_mutex_leave(db->mutex);
128677   db->magic = SQLITE_MAGIC_CLOSED;
128678   sqlite3_mutex_free(db->mutex);
128679   assert( db->lookaside.nOut==0 );  /* Fails on a lookaside memory leak */
128680   if( db->lookaside.bMalloced ){
128681     sqlite3_free(db->lookaside.pStart);
128682   }
128683   sqlite3_free(db);
128684 }
128685
128686 /*
128687 ** Rollback all database files.  If tripCode is not SQLITE_OK, then
128688 ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
128689 ** breaker") and made to return tripCode if there are any further
128690 ** attempts to use that cursor.  Read cursors remain open and valid
128691 ** but are "saved" in case the table pages are moved around.
128692 */
128693 SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
128694   int i;
128695   int inTrans = 0;
128696   int schemaChange;
128697   assert( sqlite3_mutex_held(db->mutex) );
128698   sqlite3BeginBenignMalloc();
128699
128700   /* Obtain all b-tree mutexes before making any calls to BtreeRollback(). 
128701   ** This is important in case the transaction being rolled back has
128702   ** modified the database schema. If the b-tree mutexes are not taken
128703   ** here, then another shared-cache connection might sneak in between
128704   ** the database rollback and schema reset, which can cause false
128705   ** corruption reports in some cases.  */
128706   sqlite3BtreeEnterAll(db);
128707   schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
128708
128709   for(i=0; i<db->nDb; i++){
128710     Btree *p = db->aDb[i].pBt;
128711     if( p ){
128712       if( sqlite3BtreeIsInTrans(p) ){
128713         inTrans = 1;
128714       }
128715       sqlite3BtreeRollback(p, tripCode, !schemaChange);
128716     }
128717   }
128718   sqlite3VtabRollback(db);
128719   sqlite3EndBenignMalloc();
128720
128721   if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
128722     sqlite3ExpirePreparedStatements(db);
128723     sqlite3ResetAllSchemasOfConnection(db);
128724   }
128725   sqlite3BtreeLeaveAll(db);
128726
128727   /* Any deferred constraint violations have now been resolved. */
128728   db->nDeferredCons = 0;
128729   db->nDeferredImmCons = 0;
128730   db->flags &= ~SQLITE_DeferFKs;
128731
128732   /* If one has been configured, invoke the rollback-hook callback */
128733   if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
128734     db->xRollbackCallback(db->pRollbackArg);
128735   }
128736 }
128737
128738 /*
128739 ** Return a static string containing the name corresponding to the error code
128740 ** specified in the argument.
128741 */
128742 #if (defined(SQLITE_DEBUG) && SQLITE_OS_WIN) || defined(SQLITE_TEST)
128743 SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
128744   const char *zName = 0;
128745   int i, origRc = rc;
128746   for(i=0; i<2 && zName==0; i++, rc &= 0xff){
128747     switch( rc ){
128748       case SQLITE_OK:                 zName = "SQLITE_OK";                break;
128749       case SQLITE_ERROR:              zName = "SQLITE_ERROR";             break;
128750       case SQLITE_INTERNAL:           zName = "SQLITE_INTERNAL";          break;
128751       case SQLITE_PERM:               zName = "SQLITE_PERM";              break;
128752       case SQLITE_ABORT:              zName = "SQLITE_ABORT";             break;
128753       case SQLITE_ABORT_ROLLBACK:     zName = "SQLITE_ABORT_ROLLBACK";    break;
128754       case SQLITE_BUSY:               zName = "SQLITE_BUSY";              break;
128755       case SQLITE_BUSY_RECOVERY:      zName = "SQLITE_BUSY_RECOVERY";     break;
128756       case SQLITE_BUSY_SNAPSHOT:      zName = "SQLITE_BUSY_SNAPSHOT";     break;
128757       case SQLITE_LOCKED:             zName = "SQLITE_LOCKED";            break;
128758       case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
128759       case SQLITE_NOMEM:              zName = "SQLITE_NOMEM";             break;
128760       case SQLITE_READONLY:           zName = "SQLITE_READONLY";          break;
128761       case SQLITE_READONLY_RECOVERY:  zName = "SQLITE_READONLY_RECOVERY"; break;
128762       case SQLITE_READONLY_CANTLOCK:  zName = "SQLITE_READONLY_CANTLOCK"; break;
128763       case SQLITE_READONLY_ROLLBACK:  zName = "SQLITE_READONLY_ROLLBACK"; break;
128764       case SQLITE_READONLY_DBMOVED:   zName = "SQLITE_READONLY_DBMOVED";  break;
128765       case SQLITE_INTERRUPT:          zName = "SQLITE_INTERRUPT";         break;
128766       case SQLITE_IOERR:              zName = "SQLITE_IOERR";             break;
128767       case SQLITE_IOERR_READ:         zName = "SQLITE_IOERR_READ";        break;
128768       case SQLITE_IOERR_SHORT_READ:   zName = "SQLITE_IOERR_SHORT_READ";  break;
128769       case SQLITE_IOERR_WRITE:        zName = "SQLITE_IOERR_WRITE";       break;
128770       case SQLITE_IOERR_FSYNC:        zName = "SQLITE_IOERR_FSYNC";       break;
128771       case SQLITE_IOERR_DIR_FSYNC:    zName = "SQLITE_IOERR_DIR_FSYNC";   break;
128772       case SQLITE_IOERR_TRUNCATE:     zName = "SQLITE_IOERR_TRUNCATE";    break;
128773       case SQLITE_IOERR_FSTAT:        zName = "SQLITE_IOERR_FSTAT";       break;
128774       case SQLITE_IOERR_UNLOCK:       zName = "SQLITE_IOERR_UNLOCK";      break;
128775       case SQLITE_IOERR_RDLOCK:       zName = "SQLITE_IOERR_RDLOCK";      break;
128776       case SQLITE_IOERR_DELETE:       zName = "SQLITE_IOERR_DELETE";      break;
128777       case SQLITE_IOERR_NOMEM:        zName = "SQLITE_IOERR_NOMEM";       break;
128778       case SQLITE_IOERR_ACCESS:       zName = "SQLITE_IOERR_ACCESS";      break;
128779       case SQLITE_IOERR_CHECKRESERVEDLOCK:
128780                                 zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
128781       case SQLITE_IOERR_LOCK:         zName = "SQLITE_IOERR_LOCK";        break;
128782       case SQLITE_IOERR_CLOSE:        zName = "SQLITE_IOERR_CLOSE";       break;
128783       case SQLITE_IOERR_DIR_CLOSE:    zName = "SQLITE_IOERR_DIR_CLOSE";   break;
128784       case SQLITE_IOERR_SHMOPEN:      zName = "SQLITE_IOERR_SHMOPEN";     break;
128785       case SQLITE_IOERR_SHMSIZE:      zName = "SQLITE_IOERR_SHMSIZE";     break;
128786       case SQLITE_IOERR_SHMLOCK:      zName = "SQLITE_IOERR_SHMLOCK";     break;
128787       case SQLITE_IOERR_SHMMAP:       zName = "SQLITE_IOERR_SHMMAP";      break;
128788       case SQLITE_IOERR_SEEK:         zName = "SQLITE_IOERR_SEEK";        break;
128789       case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
128790       case SQLITE_IOERR_MMAP:         zName = "SQLITE_IOERR_MMAP";        break;
128791       case SQLITE_IOERR_GETTEMPPATH:  zName = "SQLITE_IOERR_GETTEMPPATH"; break;
128792       case SQLITE_IOERR_CONVPATH:     zName = "SQLITE_IOERR_CONVPATH";    break;
128793       case SQLITE_CORRUPT:            zName = "SQLITE_CORRUPT";           break;
128794       case SQLITE_CORRUPT_VTAB:       zName = "SQLITE_CORRUPT_VTAB";      break;
128795       case SQLITE_NOTFOUND:           zName = "SQLITE_NOTFOUND";          break;
128796       case SQLITE_FULL:               zName = "SQLITE_FULL";              break;
128797       case SQLITE_CANTOPEN:           zName = "SQLITE_CANTOPEN";          break;
128798       case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
128799       case SQLITE_CANTOPEN_ISDIR:     zName = "SQLITE_CANTOPEN_ISDIR";    break;
128800       case SQLITE_CANTOPEN_FULLPATH:  zName = "SQLITE_CANTOPEN_FULLPATH"; break;
128801       case SQLITE_CANTOPEN_CONVPATH:  zName = "SQLITE_CANTOPEN_CONVPATH"; break;
128802       case SQLITE_PROTOCOL:           zName = "SQLITE_PROTOCOL";          break;
128803       case SQLITE_EMPTY:              zName = "SQLITE_EMPTY";             break;
128804       case SQLITE_SCHEMA:             zName = "SQLITE_SCHEMA";            break;
128805       case SQLITE_TOOBIG:             zName = "SQLITE_TOOBIG";            break;
128806       case SQLITE_CONSTRAINT:         zName = "SQLITE_CONSTRAINT";        break;
128807       case SQLITE_CONSTRAINT_UNIQUE:  zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
128808       case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
128809       case SQLITE_CONSTRAINT_FOREIGNKEY:
128810                                 zName = "SQLITE_CONSTRAINT_FOREIGNKEY";   break;
128811       case SQLITE_CONSTRAINT_CHECK:   zName = "SQLITE_CONSTRAINT_CHECK";  break;
128812       case SQLITE_CONSTRAINT_PRIMARYKEY:
128813                                 zName = "SQLITE_CONSTRAINT_PRIMARYKEY";   break;
128814       case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
128815       case SQLITE_CONSTRAINT_COMMITHOOK:
128816                                 zName = "SQLITE_CONSTRAINT_COMMITHOOK";   break;
128817       case SQLITE_CONSTRAINT_VTAB:    zName = "SQLITE_CONSTRAINT_VTAB";   break;
128818       case SQLITE_CONSTRAINT_FUNCTION:
128819                                 zName = "SQLITE_CONSTRAINT_FUNCTION";     break;
128820       case SQLITE_CONSTRAINT_ROWID:   zName = "SQLITE_CONSTRAINT_ROWID";  break;
128821       case SQLITE_MISMATCH:           zName = "SQLITE_MISMATCH";          break;
128822       case SQLITE_MISUSE:             zName = "SQLITE_MISUSE";            break;
128823       case SQLITE_NOLFS:              zName = "SQLITE_NOLFS";             break;
128824       case SQLITE_AUTH:               zName = "SQLITE_AUTH";              break;
128825       case SQLITE_FORMAT:             zName = "SQLITE_FORMAT";            break;
128826       case SQLITE_RANGE:              zName = "SQLITE_RANGE";             break;
128827       case SQLITE_NOTADB:             zName = "SQLITE_NOTADB";            break;
128828       case SQLITE_ROW:                zName = "SQLITE_ROW";               break;
128829       case SQLITE_NOTICE:             zName = "SQLITE_NOTICE";            break;
128830       case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
128831       case SQLITE_NOTICE_RECOVER_ROLLBACK:
128832                                 zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
128833       case SQLITE_WARNING:            zName = "SQLITE_WARNING";           break;
128834       case SQLITE_WARNING_AUTOINDEX:  zName = "SQLITE_WARNING_AUTOINDEX"; break;
128835       case SQLITE_DONE:               zName = "SQLITE_DONE";              break;
128836     }
128837   }
128838   if( zName==0 ){
128839     static char zBuf[50];
128840     sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
128841     zName = zBuf;
128842   }
128843   return zName;
128844 }
128845 #endif
128846
128847 /*
128848 ** Return a static string that describes the kind of error specified in the
128849 ** argument.
128850 */
128851 SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
128852   static const char* const aMsg[] = {
128853     /* SQLITE_OK          */ "not an error",
128854     /* SQLITE_ERROR       */ "SQL logic error or missing database",
128855     /* SQLITE_INTERNAL    */ 0,
128856     /* SQLITE_PERM        */ "access permission denied",
128857     /* SQLITE_ABORT       */ "callback requested query abort",
128858     /* SQLITE_BUSY        */ "database is locked",
128859     /* SQLITE_LOCKED      */ "database table is locked",
128860     /* SQLITE_NOMEM       */ "out of memory",
128861     /* SQLITE_READONLY    */ "attempt to write a readonly database",
128862     /* SQLITE_INTERRUPT   */ "interrupted",
128863     /* SQLITE_IOERR       */ "disk I/O error",
128864     /* SQLITE_CORRUPT     */ "database disk image is malformed",
128865     /* SQLITE_NOTFOUND    */ "unknown operation",
128866     /* SQLITE_FULL        */ "database or disk is full",
128867     /* SQLITE_CANTOPEN    */ "unable to open database file",
128868     /* SQLITE_PROTOCOL    */ "locking protocol",
128869     /* SQLITE_EMPTY       */ "table contains no data",
128870     /* SQLITE_SCHEMA      */ "database schema has changed",
128871     /* SQLITE_TOOBIG      */ "string or blob too big",
128872     /* SQLITE_CONSTRAINT  */ "constraint failed",
128873     /* SQLITE_MISMATCH    */ "datatype mismatch",
128874     /* SQLITE_MISUSE      */ "library routine called out of sequence",
128875     /* SQLITE_NOLFS       */ "large file support is disabled",
128876     /* SQLITE_AUTH        */ "authorization denied",
128877     /* SQLITE_FORMAT      */ "auxiliary database format error",
128878     /* SQLITE_RANGE       */ "bind or column index out of range",
128879     /* SQLITE_NOTADB      */ "file is encrypted or is not a database",
128880   };
128881   const char *zErr = "unknown error";
128882   switch( rc ){
128883     case SQLITE_ABORT_ROLLBACK: {
128884       zErr = "abort due to ROLLBACK";
128885       break;
128886     }
128887     default: {
128888       rc &= 0xff;
128889       if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
128890         zErr = aMsg[rc];
128891       }
128892       break;
128893     }
128894   }
128895   return zErr;
128896 }
128897
128898 /*
128899 ** This routine implements a busy callback that sleeps and tries
128900 ** again until a timeout value is reached.  The timeout value is
128901 ** an integer number of milliseconds passed in as the first
128902 ** argument.
128903 */
128904 static int sqliteDefaultBusyCallback(
128905  void *ptr,               /* Database connection */
128906  int count                /* Number of times table has been busy */
128907 ){
128908 #if SQLITE_OS_WIN || HAVE_USLEEP
128909   static const u8 delays[] =
128910      { 1, 2, 5, 10, 15, 20, 25, 25,  25,  50,  50, 100 };
128911   static const u8 totals[] =
128912      { 0, 1, 3,  8, 18, 33, 53, 78, 103, 128, 178, 228 };
128913 # define NDELAY ArraySize(delays)
128914   sqlite3 *db = (sqlite3 *)ptr;
128915   int timeout = db->busyTimeout;
128916   int delay, prior;
128917
128918   assert( count>=0 );
128919   if( count < NDELAY ){
128920     delay = delays[count];
128921     prior = totals[count];
128922   }else{
128923     delay = delays[NDELAY-1];
128924     prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
128925   }
128926   if( prior + delay > timeout ){
128927     delay = timeout - prior;
128928     if( delay<=0 ) return 0;
128929   }
128930   sqlite3OsSleep(db->pVfs, delay*1000);
128931   return 1;
128932 #else
128933   sqlite3 *db = (sqlite3 *)ptr;
128934   int timeout = ((sqlite3 *)ptr)->busyTimeout;
128935   if( (count+1)*1000 > timeout ){
128936     return 0;
128937   }
128938   sqlite3OsSleep(db->pVfs, 1000000);
128939   return 1;
128940 #endif
128941 }
128942
128943 /*
128944 ** Invoke the given busy handler.
128945 **
128946 ** This routine is called when an operation failed with a lock.
128947 ** If this routine returns non-zero, the lock is retried.  If it
128948 ** returns 0, the operation aborts with an SQLITE_BUSY error.
128949 */
128950 SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
128951   int rc;
128952   if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
128953   rc = p->xFunc(p->pArg, p->nBusy);
128954   if( rc==0 ){
128955     p->nBusy = -1;
128956   }else{
128957     p->nBusy++;
128958   }
128959   return rc; 
128960 }
128961
128962 /*
128963 ** This routine sets the busy callback for an Sqlite database to the
128964 ** given callback function with the given argument.
128965 */
128966 SQLITE_API int SQLITE_STDCALL sqlite3_busy_handler(
128967   sqlite3 *db,
128968   int (*xBusy)(void*,int),
128969   void *pArg
128970 ){
128971 #ifdef SQLITE_ENABLE_API_ARMOR
128972   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
128973 #endif
128974   sqlite3_mutex_enter(db->mutex);
128975   db->busyHandler.xFunc = xBusy;
128976   db->busyHandler.pArg = pArg;
128977   db->busyHandler.nBusy = 0;
128978   db->busyTimeout = 0;
128979   sqlite3_mutex_leave(db->mutex);
128980   return SQLITE_OK;
128981 }
128982
128983 #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
128984 /*
128985 ** This routine sets the progress callback for an Sqlite database to the
128986 ** given callback function with the given argument. The progress callback will
128987 ** be invoked every nOps opcodes.
128988 */
128989 SQLITE_API void SQLITE_STDCALL sqlite3_progress_handler(
128990   sqlite3 *db, 
128991   int nOps,
128992   int (*xProgress)(void*), 
128993   void *pArg
128994 ){
128995 #ifdef SQLITE_ENABLE_API_ARMOR
128996   if( !sqlite3SafetyCheckOk(db) ){
128997     (void)SQLITE_MISUSE_BKPT;
128998     return;
128999   }
129000 #endif
129001   sqlite3_mutex_enter(db->mutex);
129002   if( nOps>0 ){
129003     db->xProgress = xProgress;
129004     db->nProgressOps = (unsigned)nOps;
129005     db->pProgressArg = pArg;
129006   }else{
129007     db->xProgress = 0;
129008     db->nProgressOps = 0;
129009     db->pProgressArg = 0;
129010   }
129011   sqlite3_mutex_leave(db->mutex);
129012 }
129013 #endif
129014
129015
129016 /*
129017 ** This routine installs a default busy handler that waits for the
129018 ** specified number of milliseconds before returning 0.
129019 */
129020 SQLITE_API int SQLITE_STDCALL sqlite3_busy_timeout(sqlite3 *db, int ms){
129021 #ifdef SQLITE_ENABLE_API_ARMOR
129022   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
129023 #endif
129024   if( ms>0 ){
129025     sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
129026     db->busyTimeout = ms;
129027   }else{
129028     sqlite3_busy_handler(db, 0, 0);
129029   }
129030   return SQLITE_OK;
129031 }
129032
129033 /*
129034 ** Cause any pending operation to stop at its earliest opportunity.
129035 */
129036 SQLITE_API void SQLITE_STDCALL sqlite3_interrupt(sqlite3 *db){
129037 #ifdef SQLITE_ENABLE_API_ARMOR
129038   if( !sqlite3SafetyCheckOk(db) ){
129039     (void)SQLITE_MISUSE_BKPT;
129040     return;
129041   }
129042 #endif
129043   db->u1.isInterrupted = 1;
129044 }
129045
129046
129047 /*
129048 ** This function is exactly the same as sqlite3_create_function(), except
129049 ** that it is designed to be called by internal code. The difference is
129050 ** that if a malloc() fails in sqlite3_create_function(), an error code
129051 ** is returned and the mallocFailed flag cleared. 
129052 */
129053 SQLITE_PRIVATE int sqlite3CreateFunc(
129054   sqlite3 *db,
129055   const char *zFunctionName,
129056   int nArg,
129057   int enc,
129058   void *pUserData,
129059   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
129060   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
129061   void (*xFinal)(sqlite3_context*),
129062   FuncDestructor *pDestructor
129063 ){
129064   FuncDef *p;
129065   int nName;
129066   int extraFlags;
129067
129068   assert( sqlite3_mutex_held(db->mutex) );
129069   if( zFunctionName==0 ||
129070       (xFunc && (xFinal || xStep)) || 
129071       (!xFunc && (xFinal && !xStep)) ||
129072       (!xFunc && (!xFinal && xStep)) ||
129073       (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
129074       (255<(nName = sqlite3Strlen30( zFunctionName))) ){
129075     return SQLITE_MISUSE_BKPT;
129076   }
129077
129078   assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
129079   extraFlags = enc &  SQLITE_DETERMINISTIC;
129080   enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
129081   
129082 #ifndef SQLITE_OMIT_UTF16
129083   /* If SQLITE_UTF16 is specified as the encoding type, transform this
129084   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
129085   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
129086   **
129087   ** If SQLITE_ANY is specified, add three versions of the function
129088   ** to the hash table.
129089   */
129090   if( enc==SQLITE_UTF16 ){
129091     enc = SQLITE_UTF16NATIVE;
129092   }else if( enc==SQLITE_ANY ){
129093     int rc;
129094     rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
129095          pUserData, xFunc, xStep, xFinal, pDestructor);
129096     if( rc==SQLITE_OK ){
129097       rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
129098           pUserData, xFunc, xStep, xFinal, pDestructor);
129099     }
129100     if( rc!=SQLITE_OK ){
129101       return rc;
129102     }
129103     enc = SQLITE_UTF16BE;
129104   }
129105 #else
129106   enc = SQLITE_UTF8;
129107 #endif
129108   
129109   /* Check if an existing function is being overridden or deleted. If so,
129110   ** and there are active VMs, then return SQLITE_BUSY. If a function
129111   ** is being overridden/deleted but there are no active VMs, allow the
129112   ** operation to continue but invalidate all precompiled statements.
129113   */
129114   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
129115   if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
129116     if( db->nVdbeActive ){
129117       sqlite3ErrorWithMsg(db, SQLITE_BUSY, 
129118         "unable to delete/modify user-function due to active statements");
129119       assert( !db->mallocFailed );
129120       return SQLITE_BUSY;
129121     }else{
129122       sqlite3ExpirePreparedStatements(db);
129123     }
129124   }
129125
129126   p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
129127   assert(p || db->mallocFailed);
129128   if( !p ){
129129     return SQLITE_NOMEM;
129130   }
129131
129132   /* If an older version of the function with a configured destructor is
129133   ** being replaced invoke the destructor function here. */
129134   functionDestroy(db, p);
129135
129136   if( pDestructor ){
129137     pDestructor->nRef++;
129138   }
129139   p->pDestructor = pDestructor;
129140   p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
129141   testcase( p->funcFlags & SQLITE_DETERMINISTIC );
129142   p->xFunc = xFunc;
129143   p->xStep = xStep;
129144   p->xFinalize = xFinal;
129145   p->pUserData = pUserData;
129146   p->nArg = (u16)nArg;
129147   return SQLITE_OK;
129148 }
129149
129150 /*
129151 ** Create new user functions.
129152 */
129153 SQLITE_API int SQLITE_STDCALL sqlite3_create_function(
129154   sqlite3 *db,
129155   const char *zFunc,
129156   int nArg,
129157   int enc,
129158   void *p,
129159   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
129160   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
129161   void (*xFinal)(sqlite3_context*)
129162 ){
129163   return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
129164                                     xFinal, 0);
129165 }
129166
129167 SQLITE_API int SQLITE_STDCALL sqlite3_create_function_v2(
129168   sqlite3 *db,
129169   const char *zFunc,
129170   int nArg,
129171   int enc,
129172   void *p,
129173   void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
129174   void (*xStep)(sqlite3_context*,int,sqlite3_value **),
129175   void (*xFinal)(sqlite3_context*),
129176   void (*xDestroy)(void *)
129177 ){
129178   int rc = SQLITE_ERROR;
129179   FuncDestructor *pArg = 0;
129180
129181 #ifdef SQLITE_ENABLE_API_ARMOR
129182   if( !sqlite3SafetyCheckOk(db) ){
129183     return SQLITE_MISUSE_BKPT;
129184   }
129185 #endif
129186   sqlite3_mutex_enter(db->mutex);
129187   if( xDestroy ){
129188     pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
129189     if( !pArg ){
129190       xDestroy(p);
129191       goto out;
129192     }
129193     pArg->xDestroy = xDestroy;
129194     pArg->pUserData = p;
129195   }
129196   rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
129197   if( pArg && pArg->nRef==0 ){
129198     assert( rc!=SQLITE_OK );
129199     xDestroy(p);
129200     sqlite3DbFree(db, pArg);
129201   }
129202
129203  out:
129204   rc = sqlite3ApiExit(db, rc);
129205   sqlite3_mutex_leave(db->mutex);
129206   return rc;
129207 }
129208
129209 #ifndef SQLITE_OMIT_UTF16
129210 SQLITE_API int SQLITE_STDCALL sqlite3_create_function16(
129211   sqlite3 *db,
129212   const void *zFunctionName,
129213   int nArg,
129214   int eTextRep,
129215   void *p,
129216   void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
129217   void (*xStep)(sqlite3_context*,int,sqlite3_value**),
129218   void (*xFinal)(sqlite3_context*)
129219 ){
129220   int rc;
129221   char *zFunc8;
129222
129223 #ifdef SQLITE_ENABLE_API_ARMOR
129224   if( !sqlite3SafetyCheckOk(db) || zFunctionName==0 ) return SQLITE_MISUSE_BKPT;
129225 #endif
129226   sqlite3_mutex_enter(db->mutex);
129227   assert( !db->mallocFailed );
129228   zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
129229   rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
129230   sqlite3DbFree(db, zFunc8);
129231   rc = sqlite3ApiExit(db, rc);
129232   sqlite3_mutex_leave(db->mutex);
129233   return rc;
129234 }
129235 #endif
129236
129237
129238 /*
129239 ** Declare that a function has been overloaded by a virtual table.
129240 **
129241 ** If the function already exists as a regular global function, then
129242 ** this routine is a no-op.  If the function does not exist, then create
129243 ** a new one that always throws a run-time error.  
129244 **
129245 ** When virtual tables intend to provide an overloaded function, they
129246 ** should call this routine to make sure the global function exists.
129247 ** A global function must exist in order for name resolution to work
129248 ** properly.
129249 */
129250 SQLITE_API int SQLITE_STDCALL sqlite3_overload_function(
129251   sqlite3 *db,
129252   const char *zName,
129253   int nArg
129254 ){
129255   int nName = sqlite3Strlen30(zName);
129256   int rc = SQLITE_OK;
129257
129258 #ifdef SQLITE_ENABLE_API_ARMOR
129259   if( !sqlite3SafetyCheckOk(db) || zName==0 || nArg<-2 ){
129260     return SQLITE_MISUSE_BKPT;
129261   }
129262 #endif
129263   sqlite3_mutex_enter(db->mutex);
129264   if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
129265     rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
129266                            0, sqlite3InvalidFunction, 0, 0, 0);
129267   }
129268   rc = sqlite3ApiExit(db, rc);
129269   sqlite3_mutex_leave(db->mutex);
129270   return rc;
129271 }
129272
129273 #ifndef SQLITE_OMIT_TRACE
129274 /*
129275 ** Register a trace function.  The pArg from the previously registered trace
129276 ** is returned.  
129277 **
129278 ** A NULL trace function means that no tracing is executes.  A non-NULL
129279 ** trace is a pointer to a function that is invoked at the start of each
129280 ** SQL statement.
129281 */
129282 SQLITE_API void *SQLITE_STDCALL sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
129283   void *pOld;
129284
129285 #ifdef SQLITE_ENABLE_API_ARMOR
129286   if( !sqlite3SafetyCheckOk(db) ){
129287     (void)SQLITE_MISUSE_BKPT;
129288     return 0;
129289   }
129290 #endif
129291   sqlite3_mutex_enter(db->mutex);
129292   pOld = db->pTraceArg;
129293   db->xTrace = xTrace;
129294   db->pTraceArg = pArg;
129295   sqlite3_mutex_leave(db->mutex);
129296   return pOld;
129297 }
129298 /*
129299 ** Register a profile function.  The pArg from the previously registered 
129300 ** profile function is returned.  
129301 **
129302 ** A NULL profile function means that no profiling is executes.  A non-NULL
129303 ** profile is a pointer to a function that is invoked at the conclusion of
129304 ** each SQL statement that is run.
129305 */
129306 SQLITE_API void *SQLITE_STDCALL sqlite3_profile(
129307   sqlite3 *db,
129308   void (*xProfile)(void*,const char*,sqlite_uint64),
129309   void *pArg
129310 ){
129311   void *pOld;
129312
129313 #ifdef SQLITE_ENABLE_API_ARMOR
129314   if( !sqlite3SafetyCheckOk(db) ){
129315     (void)SQLITE_MISUSE_BKPT;
129316     return 0;
129317   }
129318 #endif
129319   sqlite3_mutex_enter(db->mutex);
129320   pOld = db->pProfileArg;
129321   db->xProfile = xProfile;
129322   db->pProfileArg = pArg;
129323   sqlite3_mutex_leave(db->mutex);
129324   return pOld;
129325 }
129326 #endif /* SQLITE_OMIT_TRACE */
129327
129328 /*
129329 ** Register a function to be invoked when a transaction commits.
129330 ** If the invoked function returns non-zero, then the commit becomes a
129331 ** rollback.
129332 */
129333 SQLITE_API void *SQLITE_STDCALL sqlite3_commit_hook(
129334   sqlite3 *db,              /* Attach the hook to this database */
129335   int (*xCallback)(void*),  /* Function to invoke on each commit */
129336   void *pArg                /* Argument to the function */
129337 ){
129338   void *pOld;
129339
129340 #ifdef SQLITE_ENABLE_API_ARMOR
129341   if( !sqlite3SafetyCheckOk(db) ){
129342     (void)SQLITE_MISUSE_BKPT;
129343     return 0;
129344   }
129345 #endif
129346   sqlite3_mutex_enter(db->mutex);
129347   pOld = db->pCommitArg;
129348   db->xCommitCallback = xCallback;
129349   db->pCommitArg = pArg;
129350   sqlite3_mutex_leave(db->mutex);
129351   return pOld;
129352 }
129353
129354 /*
129355 ** Register a callback to be invoked each time a row is updated,
129356 ** inserted or deleted using this database connection.
129357 */
129358 SQLITE_API void *SQLITE_STDCALL sqlite3_update_hook(
129359   sqlite3 *db,              /* Attach the hook to this database */
129360   void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
129361   void *pArg                /* Argument to the function */
129362 ){
129363   void *pRet;
129364
129365 #ifdef SQLITE_ENABLE_API_ARMOR
129366   if( !sqlite3SafetyCheckOk(db) ){
129367     (void)SQLITE_MISUSE_BKPT;
129368     return 0;
129369   }
129370 #endif
129371   sqlite3_mutex_enter(db->mutex);
129372   pRet = db->pUpdateArg;
129373   db->xUpdateCallback = xCallback;
129374   db->pUpdateArg = pArg;
129375   sqlite3_mutex_leave(db->mutex);
129376   return pRet;
129377 }
129378
129379 /*
129380 ** Register a callback to be invoked each time a transaction is rolled
129381 ** back by this database connection.
129382 */
129383 SQLITE_API void *SQLITE_STDCALL sqlite3_rollback_hook(
129384   sqlite3 *db,              /* Attach the hook to this database */
129385   void (*xCallback)(void*), /* Callback function */
129386   void *pArg                /* Argument to the function */
129387 ){
129388   void *pRet;
129389
129390 #ifdef SQLITE_ENABLE_API_ARMOR
129391   if( !sqlite3SafetyCheckOk(db) ){
129392     (void)SQLITE_MISUSE_BKPT;
129393     return 0;
129394   }
129395 #endif
129396   sqlite3_mutex_enter(db->mutex);
129397   pRet = db->pRollbackArg;
129398   db->xRollbackCallback = xCallback;
129399   db->pRollbackArg = pArg;
129400   sqlite3_mutex_leave(db->mutex);
129401   return pRet;
129402 }
129403
129404 #ifndef SQLITE_OMIT_WAL
129405 /*
129406 ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
129407 ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
129408 ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
129409 ** wal_autocheckpoint()).
129410 */ 
129411 SQLITE_PRIVATE int sqlite3WalDefaultHook(
129412   void *pClientData,     /* Argument */
129413   sqlite3 *db,           /* Connection */
129414   const char *zDb,       /* Database */
129415   int nFrame             /* Size of WAL */
129416 ){
129417   if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
129418     sqlite3BeginBenignMalloc();
129419     sqlite3_wal_checkpoint(db, zDb);
129420     sqlite3EndBenignMalloc();
129421   }
129422   return SQLITE_OK;
129423 }
129424 #endif /* SQLITE_OMIT_WAL */
129425
129426 /*
129427 ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
129428 ** a database after committing a transaction if there are nFrame or
129429 ** more frames in the log file. Passing zero or a negative value as the
129430 ** nFrame parameter disables automatic checkpoints entirely.
129431 **
129432 ** The callback registered by this function replaces any existing callback
129433 ** registered using sqlite3_wal_hook(). Likewise, registering a callback
129434 ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
129435 ** configured by this function.
129436 */
129437 SQLITE_API int SQLITE_STDCALL sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
129438 #ifdef SQLITE_OMIT_WAL
129439   UNUSED_PARAMETER(db);
129440   UNUSED_PARAMETER(nFrame);
129441 #else
129442 #ifdef SQLITE_ENABLE_API_ARMOR
129443   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
129444 #endif
129445   if( nFrame>0 ){
129446     sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
129447   }else{
129448     sqlite3_wal_hook(db, 0, 0);
129449   }
129450 #endif
129451   return SQLITE_OK;
129452 }
129453
129454 /*
129455 ** Register a callback to be invoked each time a transaction is written
129456 ** into the write-ahead-log by this database connection.
129457 */
129458 SQLITE_API void *SQLITE_STDCALL sqlite3_wal_hook(
129459   sqlite3 *db,                    /* Attach the hook to this db handle */
129460   int(*xCallback)(void *, sqlite3*, const char*, int),
129461   void *pArg                      /* First argument passed to xCallback() */
129462 ){
129463 #ifndef SQLITE_OMIT_WAL
129464   void *pRet;
129465 #ifdef SQLITE_ENABLE_API_ARMOR
129466   if( !sqlite3SafetyCheckOk(db) ){
129467     (void)SQLITE_MISUSE_BKPT;
129468     return 0;
129469   }
129470 #endif
129471   sqlite3_mutex_enter(db->mutex);
129472   pRet = db->pWalArg;
129473   db->xWalCallback = xCallback;
129474   db->pWalArg = pArg;
129475   sqlite3_mutex_leave(db->mutex);
129476   return pRet;
129477 #else
129478   return 0;
129479 #endif
129480 }
129481
129482 /*
129483 ** Checkpoint database zDb.
129484 */
129485 SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint_v2(
129486   sqlite3 *db,                    /* Database handle */
129487   const char *zDb,                /* Name of attached database (or NULL) */
129488   int eMode,                      /* SQLITE_CHECKPOINT_* value */
129489   int *pnLog,                     /* OUT: Size of WAL log in frames */
129490   int *pnCkpt                     /* OUT: Total number of frames checkpointed */
129491 ){
129492 #ifdef SQLITE_OMIT_WAL
129493   return SQLITE_OK;
129494 #else
129495   int rc;                         /* Return code */
129496   int iDb = SQLITE_MAX_ATTACHED;  /* sqlite3.aDb[] index of db to checkpoint */
129497
129498 #ifdef SQLITE_ENABLE_API_ARMOR
129499   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
129500 #endif
129501
129502   /* Initialize the output variables to -1 in case an error occurs. */
129503   if( pnLog ) *pnLog = -1;
129504   if( pnCkpt ) *pnCkpt = -1;
129505
129506   assert( SQLITE_CHECKPOINT_PASSIVE==0 );
129507   assert( SQLITE_CHECKPOINT_FULL==1 );
129508   assert( SQLITE_CHECKPOINT_RESTART==2 );
129509   assert( SQLITE_CHECKPOINT_TRUNCATE==3 );
129510   if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_TRUNCATE ){
129511     /* EVIDENCE-OF: R-03996-12088 The M parameter must be a valid checkpoint
129512     ** mode: */
129513     return SQLITE_MISUSE;
129514   }
129515
129516   sqlite3_mutex_enter(db->mutex);
129517   if( zDb && zDb[0] ){
129518     iDb = sqlite3FindDbName(db, zDb);
129519   }
129520   if( iDb<0 ){
129521     rc = SQLITE_ERROR;
129522     sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
129523   }else{
129524     db->busyHandler.nBusy = 0;
129525     rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
129526     sqlite3Error(db, rc);
129527   }
129528   rc = sqlite3ApiExit(db, rc);
129529   sqlite3_mutex_leave(db->mutex);
129530   return rc;
129531 #endif
129532 }
129533
129534
129535 /*
129536 ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
129537 ** to contains a zero-length string, all attached databases are 
129538 ** checkpointed.
129539 */
129540 SQLITE_API int SQLITE_STDCALL sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
129541   /* EVIDENCE-OF: R-41613-20553 The sqlite3_wal_checkpoint(D,X) is equivalent to
129542   ** sqlite3_wal_checkpoint_v2(D,X,SQLITE_CHECKPOINT_PASSIVE,0,0). */
129543   return sqlite3_wal_checkpoint_v2(db,zDb,SQLITE_CHECKPOINT_PASSIVE,0,0);
129544 }
129545
129546 #ifndef SQLITE_OMIT_WAL
129547 /*
129548 ** Run a checkpoint on database iDb. This is a no-op if database iDb is
129549 ** not currently open in WAL mode.
129550 **
129551 ** If a transaction is open on the database being checkpointed, this 
129552 ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If 
129553 ** an error occurs while running the checkpoint, an SQLite error code is 
129554 ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
129555 **
129556 ** The mutex on database handle db should be held by the caller. The mutex
129557 ** associated with the specific b-tree being checkpointed is taken by
129558 ** this function while the checkpoint is running.
129559 **
129560 ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
129561 ** checkpointed. If an error is encountered it is returned immediately -
129562 ** no attempt is made to checkpoint any remaining databases.
129563 **
129564 ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
129565 */
129566 SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
129567   int rc = SQLITE_OK;             /* Return code */
129568   int i;                          /* Used to iterate through attached dbs */
129569   int bBusy = 0;                  /* True if SQLITE_BUSY has been encountered */
129570
129571   assert( sqlite3_mutex_held(db->mutex) );
129572   assert( !pnLog || *pnLog==-1 );
129573   assert( !pnCkpt || *pnCkpt==-1 );
129574
129575   for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
129576     if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
129577       rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
129578       pnLog = 0;
129579       pnCkpt = 0;
129580       if( rc==SQLITE_BUSY ){
129581         bBusy = 1;
129582         rc = SQLITE_OK;
129583       }
129584     }
129585   }
129586
129587   return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
129588 }
129589 #endif /* SQLITE_OMIT_WAL */
129590
129591 /*
129592 ** This function returns true if main-memory should be used instead of
129593 ** a temporary file for transient pager files and statement journals.
129594 ** The value returned depends on the value of db->temp_store (runtime
129595 ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
129596 ** following table describes the relationship between these two values
129597 ** and this functions return value.
129598 **
129599 **   SQLITE_TEMP_STORE     db->temp_store     Location of temporary database
129600 **   -----------------     --------------     ------------------------------
129601 **   0                     any                file      (return 0)
129602 **   1                     1                  file      (return 0)
129603 **   1                     2                  memory    (return 1)
129604 **   1                     0                  file      (return 0)
129605 **   2                     1                  file      (return 0)
129606 **   2                     2                  memory    (return 1)
129607 **   2                     0                  memory    (return 1)
129608 **   3                     any                memory    (return 1)
129609 */
129610 SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
129611 #if SQLITE_TEMP_STORE==1
129612   return ( db->temp_store==2 );
129613 #endif
129614 #if SQLITE_TEMP_STORE==2
129615   return ( db->temp_store!=1 );
129616 #endif
129617 #if SQLITE_TEMP_STORE==3
129618   return 1;
129619 #endif
129620 #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
129621   return 0;
129622 #endif
129623 }
129624
129625 /*
129626 ** Return UTF-8 encoded English language explanation of the most recent
129627 ** error.
129628 */
129629 SQLITE_API const char *SQLITE_STDCALL sqlite3_errmsg(sqlite3 *db){
129630   const char *z;
129631   if( !db ){
129632     return sqlite3ErrStr(SQLITE_NOMEM);
129633   }
129634   if( !sqlite3SafetyCheckSickOrOk(db) ){
129635     return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
129636   }
129637   sqlite3_mutex_enter(db->mutex);
129638   if( db->mallocFailed ){
129639     z = sqlite3ErrStr(SQLITE_NOMEM);
129640   }else{
129641     testcase( db->pErr==0 );
129642     z = (char*)sqlite3_value_text(db->pErr);
129643     assert( !db->mallocFailed );
129644     if( z==0 ){
129645       z = sqlite3ErrStr(db->errCode);
129646     }
129647   }
129648   sqlite3_mutex_leave(db->mutex);
129649   return z;
129650 }
129651
129652 #ifndef SQLITE_OMIT_UTF16
129653 /*
129654 ** Return UTF-16 encoded English language explanation of the most recent
129655 ** error.
129656 */
129657 SQLITE_API const void *SQLITE_STDCALL sqlite3_errmsg16(sqlite3 *db){
129658   static const u16 outOfMem[] = {
129659     'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
129660   };
129661   static const u16 misuse[] = {
129662     'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ', 
129663     'r', 'o', 'u', 't', 'i', 'n', 'e', ' ', 
129664     'c', 'a', 'l', 'l', 'e', 'd', ' ', 
129665     'o', 'u', 't', ' ', 
129666     'o', 'f', ' ', 
129667     's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
129668   };
129669
129670   const void *z;
129671   if( !db ){
129672     return (void *)outOfMem;
129673   }
129674   if( !sqlite3SafetyCheckSickOrOk(db) ){
129675     return (void *)misuse;
129676   }
129677   sqlite3_mutex_enter(db->mutex);
129678   if( db->mallocFailed ){
129679     z = (void *)outOfMem;
129680   }else{
129681     z = sqlite3_value_text16(db->pErr);
129682     if( z==0 ){
129683       sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
129684       z = sqlite3_value_text16(db->pErr);
129685     }
129686     /* A malloc() may have failed within the call to sqlite3_value_text16()
129687     ** above. If this is the case, then the db->mallocFailed flag needs to
129688     ** be cleared before returning. Do this directly, instead of via
129689     ** sqlite3ApiExit(), to avoid setting the database handle error message.
129690     */
129691     db->mallocFailed = 0;
129692   }
129693   sqlite3_mutex_leave(db->mutex);
129694   return z;
129695 }
129696 #endif /* SQLITE_OMIT_UTF16 */
129697
129698 /*
129699 ** Return the most recent error code generated by an SQLite routine. If NULL is
129700 ** passed to this function, we assume a malloc() failed during sqlite3_open().
129701 */
129702 SQLITE_API int SQLITE_STDCALL sqlite3_errcode(sqlite3 *db){
129703   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
129704     return SQLITE_MISUSE_BKPT;
129705   }
129706   if( !db || db->mallocFailed ){
129707     return SQLITE_NOMEM;
129708   }
129709   return db->errCode & db->errMask;
129710 }
129711 SQLITE_API int SQLITE_STDCALL sqlite3_extended_errcode(sqlite3 *db){
129712   if( db && !sqlite3SafetyCheckSickOrOk(db) ){
129713     return SQLITE_MISUSE_BKPT;
129714   }
129715   if( !db || db->mallocFailed ){
129716     return SQLITE_NOMEM;
129717   }
129718   return db->errCode;
129719 }
129720
129721 /*
129722 ** Return a string that describes the kind of error specified in the
129723 ** argument.  For now, this simply calls the internal sqlite3ErrStr()
129724 ** function.
129725 */
129726 SQLITE_API const char *SQLITE_STDCALL sqlite3_errstr(int rc){
129727   return sqlite3ErrStr(rc);
129728 }
129729
129730 /*
129731 ** Create a new collating function for database "db".  The name is zName
129732 ** and the encoding is enc.
129733 */
129734 static int createCollation(
129735   sqlite3* db,
129736   const char *zName, 
129737   u8 enc,
129738   void* pCtx,
129739   int(*xCompare)(void*,int,const void*,int,const void*),
129740   void(*xDel)(void*)
129741 ){
129742   CollSeq *pColl;
129743   int enc2;
129744   
129745   assert( sqlite3_mutex_held(db->mutex) );
129746
129747   /* If SQLITE_UTF16 is specified as the encoding type, transform this
129748   ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
129749   ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
129750   */
129751   enc2 = enc;
129752   testcase( enc2==SQLITE_UTF16 );
129753   testcase( enc2==SQLITE_UTF16_ALIGNED );
129754   if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
129755     enc2 = SQLITE_UTF16NATIVE;
129756   }
129757   if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
129758     return SQLITE_MISUSE_BKPT;
129759   }
129760
129761   /* Check if this call is removing or replacing an existing collation 
129762   ** sequence. If so, and there are active VMs, return busy. If there
129763   ** are no active VMs, invalidate any pre-compiled statements.
129764   */
129765   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
129766   if( pColl && pColl->xCmp ){
129767     if( db->nVdbeActive ){
129768       sqlite3ErrorWithMsg(db, SQLITE_BUSY, 
129769         "unable to delete/modify collation sequence due to active statements");
129770       return SQLITE_BUSY;
129771     }
129772     sqlite3ExpirePreparedStatements(db);
129773
129774     /* If collation sequence pColl was created directly by a call to
129775     ** sqlite3_create_collation, and not generated by synthCollSeq(),
129776     ** then any copies made by synthCollSeq() need to be invalidated.
129777     ** Also, collation destructor - CollSeq.xDel() - function may need
129778     ** to be called.
129779     */ 
129780     if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
129781       CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
129782       int j;
129783       for(j=0; j<3; j++){
129784         CollSeq *p = &aColl[j];
129785         if( p->enc==pColl->enc ){
129786           if( p->xDel ){
129787             p->xDel(p->pUser);
129788           }
129789           p->xCmp = 0;
129790         }
129791       }
129792     }
129793   }
129794
129795   pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
129796   if( pColl==0 ) return SQLITE_NOMEM;
129797   pColl->xCmp = xCompare;
129798   pColl->pUser = pCtx;
129799   pColl->xDel = xDel;
129800   pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
129801   sqlite3Error(db, SQLITE_OK);
129802   return SQLITE_OK;
129803 }
129804
129805
129806 /*
129807 ** This array defines hard upper bounds on limit values.  The
129808 ** initializer must be kept in sync with the SQLITE_LIMIT_*
129809 ** #defines in sqlite3.h.
129810 */
129811 static const int aHardLimit[] = {
129812   SQLITE_MAX_LENGTH,
129813   SQLITE_MAX_SQL_LENGTH,
129814   SQLITE_MAX_COLUMN,
129815   SQLITE_MAX_EXPR_DEPTH,
129816   SQLITE_MAX_COMPOUND_SELECT,
129817   SQLITE_MAX_VDBE_OP,
129818   SQLITE_MAX_FUNCTION_ARG,
129819   SQLITE_MAX_ATTACHED,
129820   SQLITE_MAX_LIKE_PATTERN_LENGTH,
129821   SQLITE_MAX_VARIABLE_NUMBER,      /* IMP: R-38091-32352 */
129822   SQLITE_MAX_TRIGGER_DEPTH,
129823   SQLITE_MAX_WORKER_THREADS,
129824 };
129825
129826 /*
129827 ** Make sure the hard limits are set to reasonable values
129828 */
129829 #if SQLITE_MAX_LENGTH<100
129830 # error SQLITE_MAX_LENGTH must be at least 100
129831 #endif
129832 #if SQLITE_MAX_SQL_LENGTH<100
129833 # error SQLITE_MAX_SQL_LENGTH must be at least 100
129834 #endif
129835 #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
129836 # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
129837 #endif
129838 #if SQLITE_MAX_COMPOUND_SELECT<2
129839 # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
129840 #endif
129841 #if SQLITE_MAX_VDBE_OP<40
129842 # error SQLITE_MAX_VDBE_OP must be at least 40
129843 #endif
129844 #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
129845 # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
129846 #endif
129847 #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
129848 # error SQLITE_MAX_ATTACHED must be between 0 and 125
129849 #endif
129850 #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
129851 # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
129852 #endif
129853 #if SQLITE_MAX_COLUMN>32767
129854 # error SQLITE_MAX_COLUMN must not exceed 32767
129855 #endif
129856 #if SQLITE_MAX_TRIGGER_DEPTH<1
129857 # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
129858 #endif
129859 #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
129860 # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
129861 #endif
129862
129863
129864 /*
129865 ** Change the value of a limit.  Report the old value.
129866 ** If an invalid limit index is supplied, report -1.
129867 ** Make no changes but still report the old value if the
129868 ** new limit is negative.
129869 **
129870 ** A new lower limit does not shrink existing constructs.
129871 ** It merely prevents new constructs that exceed the limit
129872 ** from forming.
129873 */
129874 SQLITE_API int SQLITE_STDCALL sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
129875   int oldLimit;
129876
129877 #ifdef SQLITE_ENABLE_API_ARMOR
129878   if( !sqlite3SafetyCheckOk(db) ){
129879     (void)SQLITE_MISUSE_BKPT;
129880     return -1;
129881   }
129882 #endif
129883
129884   /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
129885   ** there is a hard upper bound set at compile-time by a C preprocessor
129886   ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
129887   ** "_MAX_".)
129888   */
129889   assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
129890   assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
129891   assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
129892   assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
129893   assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
129894   assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
129895   assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
129896   assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
129897   assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
129898                                                SQLITE_MAX_LIKE_PATTERN_LENGTH );
129899   assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
129900   assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
129901   assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
129902   assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
129903
129904
129905   if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
129906     return -1;
129907   }
129908   oldLimit = db->aLimit[limitId];
129909   if( newLimit>=0 ){                   /* IMP: R-52476-28732 */
129910     if( newLimit>aHardLimit[limitId] ){
129911       newLimit = aHardLimit[limitId];  /* IMP: R-51463-25634 */
129912     }
129913     db->aLimit[limitId] = newLimit;
129914   }
129915   return oldLimit;                     /* IMP: R-53341-35419 */
129916 }
129917
129918 /*
129919 ** This function is used to parse both URIs and non-URI filenames passed by the
129920 ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
129921 ** URIs specified as part of ATTACH statements.
129922 **
129923 ** The first argument to this function is the name of the VFS to use (or
129924 ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
129925 ** query parameter. The second argument contains the URI (or non-URI filename)
129926 ** itself. When this function is called the *pFlags variable should contain
129927 ** the default flags to open the database handle with. The value stored in
129928 ** *pFlags may be updated before returning if the URI filename contains 
129929 ** "cache=xxx" or "mode=xxx" query parameters.
129930 **
129931 ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
129932 ** the VFS that should be used to open the database file. *pzFile is set to
129933 ** point to a buffer containing the name of the file to open. It is the 
129934 ** responsibility of the caller to eventually call sqlite3_free() to release
129935 ** this buffer.
129936 **
129937 ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
129938 ** may be set to point to a buffer containing an English language error 
129939 ** message. It is the responsibility of the caller to eventually release
129940 ** this buffer by calling sqlite3_free().
129941 */
129942 SQLITE_PRIVATE int sqlite3ParseUri(
129943   const char *zDefaultVfs,        /* VFS to use if no "vfs=xxx" query option */
129944   const char *zUri,               /* Nul-terminated URI to parse */
129945   unsigned int *pFlags,           /* IN/OUT: SQLITE_OPEN_XXX flags */
129946   sqlite3_vfs **ppVfs,            /* OUT: VFS to use */ 
129947   char **pzFile,                  /* OUT: Filename component of URI */
129948   char **pzErrMsg                 /* OUT: Error message (if rc!=SQLITE_OK) */
129949 ){
129950   int rc = SQLITE_OK;
129951   unsigned int flags = *pFlags;
129952   const char *zVfs = zDefaultVfs;
129953   char *zFile;
129954   char c;
129955   int nUri = sqlite3Strlen30(zUri);
129956
129957   assert( *pzErrMsg==0 );
129958
129959   if( ((flags & SQLITE_OPEN_URI)             /* IMP: R-48725-32206 */
129960             || sqlite3GlobalConfig.bOpenUri) /* IMP: R-51689-46548 */
129961    && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
129962   ){
129963     char *zOpt;
129964     int eState;                   /* Parser state when parsing URI */
129965     int iIn;                      /* Input character index */
129966     int iOut = 0;                 /* Output character index */
129967     int nByte = nUri+2;           /* Bytes of space to allocate */
129968
129969     /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen 
129970     ** method that there may be extra parameters following the file-name.  */
129971     flags |= SQLITE_OPEN_URI;
129972
129973     for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
129974     zFile = sqlite3_malloc(nByte);
129975     if( !zFile ) return SQLITE_NOMEM;
129976
129977     iIn = 5;
129978 #ifdef SQLITE_ALLOW_URI_AUTHORITY
129979     if( strncmp(zUri+5, "///", 3)==0 ){
129980       iIn = 7;
129981       /* The following condition causes URIs with five leading / characters
129982       ** like file://///host/path to be converted into UNCs like //host/path.
129983       ** The correct URI for that UNC has only two or four leading / characters
129984       ** file://host/path or file:////host/path.  But 5 leading slashes is a 
129985       ** common error, we are told, so we handle it as a special case. */
129986       if( strncmp(zUri+7, "///", 3)==0 ){ iIn++; }
129987     }else if( strncmp(zUri+5, "//localhost/", 12)==0 ){
129988       iIn = 16;
129989     }
129990 #else
129991     /* Discard the scheme and authority segments of the URI. */
129992     if( zUri[5]=='/' && zUri[6]=='/' ){
129993       iIn = 7;
129994       while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
129995       if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
129996         *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s", 
129997             iIn-7, &zUri[7]);
129998         rc = SQLITE_ERROR;
129999         goto parse_uri_out;
130000       }
130001     }
130002 #endif
130003
130004     /* Copy the filename and any query parameters into the zFile buffer. 
130005     ** Decode %HH escape codes along the way. 
130006     **
130007     ** Within this loop, variable eState may be set to 0, 1 or 2, depending
130008     ** on the parsing context. As follows:
130009     **
130010     **   0: Parsing file-name.
130011     **   1: Parsing name section of a name=value query parameter.
130012     **   2: Parsing value section of a name=value query parameter.
130013     */
130014     eState = 0;
130015     while( (c = zUri[iIn])!=0 && c!='#' ){
130016       iIn++;
130017       if( c=='%' 
130018        && sqlite3Isxdigit(zUri[iIn]) 
130019        && sqlite3Isxdigit(zUri[iIn+1]) 
130020       ){
130021         int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
130022         octet += sqlite3HexToInt(zUri[iIn++]);
130023
130024         assert( octet>=0 && octet<256 );
130025         if( octet==0 ){
130026           /* This branch is taken when "%00" appears within the URI. In this
130027           ** case we ignore all text in the remainder of the path, name or
130028           ** value currently being parsed. So ignore the current character
130029           ** and skip to the next "?", "=" or "&", as appropriate. */
130030           while( (c = zUri[iIn])!=0 && c!='#' 
130031               && (eState!=0 || c!='?')
130032               && (eState!=1 || (c!='=' && c!='&'))
130033               && (eState!=2 || c!='&')
130034           ){
130035             iIn++;
130036           }
130037           continue;
130038         }
130039         c = octet;
130040       }else if( eState==1 && (c=='&' || c=='=') ){
130041         if( zFile[iOut-1]==0 ){
130042           /* An empty option name. Ignore this option altogether. */
130043           while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
130044           continue;
130045         }
130046         if( c=='&' ){
130047           zFile[iOut++] = '\0';
130048         }else{
130049           eState = 2;
130050         }
130051         c = 0;
130052       }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
130053         c = 0;
130054         eState = 1;
130055       }
130056       zFile[iOut++] = c;
130057     }
130058     if( eState==1 ) zFile[iOut++] = '\0';
130059     zFile[iOut++] = '\0';
130060     zFile[iOut++] = '\0';
130061
130062     /* Check if there were any options specified that should be interpreted 
130063     ** here. Options that are interpreted here include "vfs" and those that
130064     ** correspond to flags that may be passed to the sqlite3_open_v2()
130065     ** method. */
130066     zOpt = &zFile[sqlite3Strlen30(zFile)+1];
130067     while( zOpt[0] ){
130068       int nOpt = sqlite3Strlen30(zOpt);
130069       char *zVal = &zOpt[nOpt+1];
130070       int nVal = sqlite3Strlen30(zVal);
130071
130072       if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
130073         zVfs = zVal;
130074       }else{
130075         struct OpenMode {
130076           const char *z;
130077           int mode;
130078         } *aMode = 0;
130079         char *zModeType = 0;
130080         int mask = 0;
130081         int limit = 0;
130082
130083         if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
130084           static struct OpenMode aCacheMode[] = {
130085             { "shared",  SQLITE_OPEN_SHAREDCACHE },
130086             { "private", SQLITE_OPEN_PRIVATECACHE },
130087             { 0, 0 }
130088           };
130089
130090           mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
130091           aMode = aCacheMode;
130092           limit = mask;
130093           zModeType = "cache";
130094         }
130095         if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
130096           static struct OpenMode aOpenMode[] = {
130097             { "ro",  SQLITE_OPEN_READONLY },
130098             { "rw",  SQLITE_OPEN_READWRITE }, 
130099             { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
130100             { "memory", SQLITE_OPEN_MEMORY },
130101             { 0, 0 }
130102           };
130103
130104           mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
130105                    | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
130106           aMode = aOpenMode;
130107           limit = mask & flags;
130108           zModeType = "access";
130109         }
130110
130111         if( aMode ){
130112           int i;
130113           int mode = 0;
130114           for(i=0; aMode[i].z; i++){
130115             const char *z = aMode[i].z;
130116             if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
130117               mode = aMode[i].mode;
130118               break;
130119             }
130120           }
130121           if( mode==0 ){
130122             *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
130123             rc = SQLITE_ERROR;
130124             goto parse_uri_out;
130125           }
130126           if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
130127             *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
130128                                         zModeType, zVal);
130129             rc = SQLITE_PERM;
130130             goto parse_uri_out;
130131           }
130132           flags = (flags & ~mask) | mode;
130133         }
130134       }
130135
130136       zOpt = &zVal[nVal+1];
130137     }
130138
130139   }else{
130140     zFile = sqlite3_malloc(nUri+2);
130141     if( !zFile ) return SQLITE_NOMEM;
130142     memcpy(zFile, zUri, nUri);
130143     zFile[nUri] = '\0';
130144     zFile[nUri+1] = '\0';
130145     flags &= ~SQLITE_OPEN_URI;
130146   }
130147
130148   *ppVfs = sqlite3_vfs_find(zVfs);
130149   if( *ppVfs==0 ){
130150     *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
130151     rc = SQLITE_ERROR;
130152   }
130153  parse_uri_out:
130154   if( rc!=SQLITE_OK ){
130155     sqlite3_free(zFile);
130156     zFile = 0;
130157   }
130158   *pFlags = flags;
130159   *pzFile = zFile;
130160   return rc;
130161 }
130162
130163
130164 /*
130165 ** This routine does the work of opening a database on behalf of
130166 ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"  
130167 ** is UTF-8 encoded.
130168 */
130169 static int openDatabase(
130170   const char *zFilename, /* Database filename UTF-8 encoded */
130171   sqlite3 **ppDb,        /* OUT: Returned database handle */
130172   unsigned int flags,    /* Operational flags */
130173   const char *zVfs       /* Name of the VFS to use */
130174 ){
130175   sqlite3 *db;                    /* Store allocated handle here */
130176   int rc;                         /* Return code */
130177   int isThreadsafe;               /* True for threadsafe connections */
130178   char *zOpen = 0;                /* Filename argument to pass to BtreeOpen() */
130179   char *zErrMsg = 0;              /* Error message from sqlite3ParseUri() */
130180
130181 #ifdef SQLITE_ENABLE_API_ARMOR
130182   if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
130183 #endif
130184   *ppDb = 0;
130185 #ifndef SQLITE_OMIT_AUTOINIT
130186   rc = sqlite3_initialize();
130187   if( rc ) return rc;
130188 #endif
130189
130190   /* Only allow sensible combinations of bits in the flags argument.  
130191   ** Throw an error if any non-sense combination is used.  If we
130192   ** do not block illegal combinations here, it could trigger
130193   ** assert() statements in deeper layers.  Sensible combinations
130194   ** are:
130195   **
130196   **  1:  SQLITE_OPEN_READONLY
130197   **  2:  SQLITE_OPEN_READWRITE
130198   **  6:  SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
130199   */
130200   assert( SQLITE_OPEN_READONLY  == 0x01 );
130201   assert( SQLITE_OPEN_READWRITE == 0x02 );
130202   assert( SQLITE_OPEN_CREATE    == 0x04 );
130203   testcase( (1<<(flags&7))==0x02 ); /* READONLY */
130204   testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
130205   testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
130206   if( ((1<<(flags&7)) & 0x46)==0 ){
130207     return SQLITE_MISUSE_BKPT;  /* IMP: R-65497-44594 */
130208   }
130209
130210   if( sqlite3GlobalConfig.bCoreMutex==0 ){
130211     isThreadsafe = 0;
130212   }else if( flags & SQLITE_OPEN_NOMUTEX ){
130213     isThreadsafe = 0;
130214   }else if( flags & SQLITE_OPEN_FULLMUTEX ){
130215     isThreadsafe = 1;
130216   }else{
130217     isThreadsafe = sqlite3GlobalConfig.bFullMutex;
130218   }
130219   if( flags & SQLITE_OPEN_PRIVATECACHE ){
130220     flags &= ~SQLITE_OPEN_SHAREDCACHE;
130221   }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
130222     flags |= SQLITE_OPEN_SHAREDCACHE;
130223   }
130224
130225   /* Remove harmful bits from the flags parameter
130226   **
130227   ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
130228   ** dealt with in the previous code block.  Besides these, the only
130229   ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
130230   ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
130231   ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits.  Silently mask
130232   ** off all other flags.
130233   */
130234   flags &=  ~( SQLITE_OPEN_DELETEONCLOSE |
130235                SQLITE_OPEN_EXCLUSIVE |
130236                SQLITE_OPEN_MAIN_DB |
130237                SQLITE_OPEN_TEMP_DB | 
130238                SQLITE_OPEN_TRANSIENT_DB | 
130239                SQLITE_OPEN_MAIN_JOURNAL | 
130240                SQLITE_OPEN_TEMP_JOURNAL | 
130241                SQLITE_OPEN_SUBJOURNAL | 
130242                SQLITE_OPEN_MASTER_JOURNAL |
130243                SQLITE_OPEN_NOMUTEX |
130244                SQLITE_OPEN_FULLMUTEX |
130245                SQLITE_OPEN_WAL
130246              );
130247
130248   /* Allocate the sqlite data structure */
130249   db = sqlite3MallocZero( sizeof(sqlite3) );
130250   if( db==0 ) goto opendb_out;
130251   if( isThreadsafe ){
130252     db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
130253     if( db->mutex==0 ){
130254       sqlite3_free(db);
130255       db = 0;
130256       goto opendb_out;
130257     }
130258   }
130259   sqlite3_mutex_enter(db->mutex);
130260   db->errMask = 0xff;
130261   db->nDb = 2;
130262   db->magic = SQLITE_MAGIC_BUSY;
130263   db->aDb = db->aDbStatic;
130264
130265   assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
130266   memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
130267   db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
130268   db->autoCommit = 1;
130269   db->nextAutovac = -1;
130270   db->szMmap = sqlite3GlobalConfig.szMmap;
130271   db->nextPagesize = 0;
130272   db->nMaxSorterMmap = 0x7FFFFFFF;
130273   db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
130274 #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
130275                  | SQLITE_AutoIndex
130276 #endif
130277 #if SQLITE_DEFAULT_CKPTFULLFSYNC
130278                  | SQLITE_CkptFullFSync
130279 #endif
130280 #if SQLITE_DEFAULT_FILE_FORMAT<4
130281                  | SQLITE_LegacyFileFmt
130282 #endif
130283 #ifdef SQLITE_ENABLE_LOAD_EXTENSION
130284                  | SQLITE_LoadExtension
130285 #endif
130286 #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
130287                  | SQLITE_RecTriggers
130288 #endif
130289 #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
130290                  | SQLITE_ForeignKeys
130291 #endif
130292 #if defined(SQLITE_REVERSE_UNORDERED_SELECTS)
130293                  | SQLITE_ReverseOrder
130294 #endif
130295       ;
130296   sqlite3HashInit(&db->aCollSeq);
130297 #ifndef SQLITE_OMIT_VIRTUALTABLE
130298   sqlite3HashInit(&db->aModule);
130299 #endif
130300
130301   /* Add the default collation sequence BINARY. BINARY works for both UTF-8
130302   ** and UTF-16, so add a version for each to avoid any unnecessary
130303   ** conversions. The only error that can occur here is a malloc() failure.
130304   **
130305   ** EVIDENCE-OF: R-52786-44878 SQLite defines three built-in collating
130306   ** functions:
130307   */
130308   createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
130309   createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
130310   createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
130311   createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
130312   createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
130313   if( db->mallocFailed ){
130314     goto opendb_out;
130315   }
130316   /* EVIDENCE-OF: R-08308-17224 The default collating function for all
130317   ** strings is BINARY. 
130318   */
130319   db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
130320   assert( db->pDfltColl!=0 );
130321
130322   /* Parse the filename/URI argument. */
130323   db->openFlags = flags;
130324   rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
130325   if( rc!=SQLITE_OK ){
130326     if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
130327     sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
130328     sqlite3_free(zErrMsg);
130329     goto opendb_out;
130330   }
130331
130332   /* Open the backend database driver */
130333   rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
130334                         flags | SQLITE_OPEN_MAIN_DB);
130335   if( rc!=SQLITE_OK ){
130336     if( rc==SQLITE_IOERR_NOMEM ){
130337       rc = SQLITE_NOMEM;
130338     }
130339     sqlite3Error(db, rc);
130340     goto opendb_out;
130341   }
130342   sqlite3BtreeEnter(db->aDb[0].pBt);
130343   db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
130344   if( !db->mallocFailed ) ENC(db) = SCHEMA_ENC(db);
130345   sqlite3BtreeLeave(db->aDb[0].pBt);
130346   db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
130347
130348   /* The default safety_level for the main database is 'full'; for the temp
130349   ** database it is 'NONE'. This matches the pager layer defaults.  
130350   */
130351   db->aDb[0].zName = "main";
130352   db->aDb[0].safety_level = 3;
130353   db->aDb[1].zName = "temp";
130354   db->aDb[1].safety_level = 1;
130355
130356   db->magic = SQLITE_MAGIC_OPEN;
130357   if( db->mallocFailed ){
130358     goto opendb_out;
130359   }
130360
130361   /* Register all built-in functions, but do not attempt to read the
130362   ** database schema yet. This is delayed until the first time the database
130363   ** is accessed.
130364   */
130365   sqlite3Error(db, SQLITE_OK);
130366   sqlite3RegisterBuiltinFunctions(db);
130367
130368   /* Load automatic extensions - extensions that have been registered
130369   ** using the sqlite3_automatic_extension() API.
130370   */
130371   rc = sqlite3_errcode(db);
130372   if( rc==SQLITE_OK ){
130373     sqlite3AutoLoadExtensions(db);
130374     rc = sqlite3_errcode(db);
130375     if( rc!=SQLITE_OK ){
130376       goto opendb_out;
130377     }
130378   }
130379
130380 #ifdef SQLITE_ENABLE_FTS1
130381   if( !db->mallocFailed ){
130382     extern int sqlite3Fts1Init(sqlite3*);
130383     rc = sqlite3Fts1Init(db);
130384   }
130385 #endif
130386
130387 #ifdef SQLITE_ENABLE_FTS2
130388   if( !db->mallocFailed && rc==SQLITE_OK ){
130389     extern int sqlite3Fts2Init(sqlite3*);
130390     rc = sqlite3Fts2Init(db);
130391   }
130392 #endif
130393
130394 #ifdef SQLITE_ENABLE_FTS3
130395   if( !db->mallocFailed && rc==SQLITE_OK ){
130396     rc = sqlite3Fts3Init(db);
130397   }
130398 #endif
130399
130400 #ifdef SQLITE_ENABLE_ICU
130401   if( !db->mallocFailed && rc==SQLITE_OK ){
130402     rc = sqlite3IcuInit(db);
130403   }
130404 #endif
130405
130406 #ifdef SQLITE_ENABLE_RTREE
130407   if( !db->mallocFailed && rc==SQLITE_OK){
130408     rc = sqlite3RtreeInit(db);
130409   }
130410 #endif
130411
130412   /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
130413   ** mode.  -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
130414   ** mode.  Doing nothing at all also makes NORMAL the default.
130415   */
130416 #ifdef SQLITE_DEFAULT_LOCKING_MODE
130417   db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
130418   sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
130419                           SQLITE_DEFAULT_LOCKING_MODE);
130420 #endif
130421
130422   if( rc ) sqlite3Error(db, rc);
130423
130424   /* Enable the lookaside-malloc subsystem */
130425   setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
130426                         sqlite3GlobalConfig.nLookaside);
130427
130428   sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
130429
130430 opendb_out:
130431   sqlite3_free(zOpen);
130432   if( db ){
130433     assert( db->mutex!=0 || isThreadsafe==0
130434            || sqlite3GlobalConfig.bFullMutex==0 );
130435     sqlite3_mutex_leave(db->mutex);
130436   }
130437   rc = sqlite3_errcode(db);
130438   assert( db!=0 || rc==SQLITE_NOMEM );
130439   if( rc==SQLITE_NOMEM ){
130440     sqlite3_close(db);
130441     db = 0;
130442   }else if( rc!=SQLITE_OK ){
130443     db->magic = SQLITE_MAGIC_SICK;
130444   }
130445   *ppDb = db;
130446 #ifdef SQLITE_ENABLE_SQLLOG
130447   if( sqlite3GlobalConfig.xSqllog ){
130448     /* Opening a db handle. Fourth parameter is passed 0. */
130449     void *pArg = sqlite3GlobalConfig.pSqllogArg;
130450     sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
130451   }
130452 #endif
130453   return sqlite3ApiExit(0, rc);
130454 }
130455
130456 /*
130457 ** Open a new database handle.
130458 */
130459 SQLITE_API int SQLITE_STDCALL sqlite3_open(
130460   const char *zFilename, 
130461   sqlite3 **ppDb 
130462 ){
130463   return openDatabase(zFilename, ppDb,
130464                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
130465 }
130466 SQLITE_API int SQLITE_STDCALL sqlite3_open_v2(
130467   const char *filename,   /* Database filename (UTF-8) */
130468   sqlite3 **ppDb,         /* OUT: SQLite db handle */
130469   int flags,              /* Flags */
130470   const char *zVfs        /* Name of VFS module to use */
130471 ){
130472   return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
130473 }
130474
130475 #ifndef SQLITE_OMIT_UTF16
130476 /*
130477 ** Open a new database handle.
130478 */
130479 SQLITE_API int SQLITE_STDCALL sqlite3_open16(
130480   const void *zFilename, 
130481   sqlite3 **ppDb
130482 ){
130483   char const *zFilename8;   /* zFilename encoded in UTF-8 instead of UTF-16 */
130484   sqlite3_value *pVal;
130485   int rc;
130486
130487 #ifdef SQLITE_ENABLE_API_ARMOR
130488   if( ppDb==0 ) return SQLITE_MISUSE_BKPT;
130489 #endif
130490   *ppDb = 0;
130491 #ifndef SQLITE_OMIT_AUTOINIT
130492   rc = sqlite3_initialize();
130493   if( rc ) return rc;
130494 #endif
130495   if( zFilename==0 ) zFilename = "\000\000";
130496   pVal = sqlite3ValueNew(0);
130497   sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
130498   zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
130499   if( zFilename8 ){
130500     rc = openDatabase(zFilename8, ppDb,
130501                       SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
130502     assert( *ppDb || rc==SQLITE_NOMEM );
130503     if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
130504       SCHEMA_ENC(*ppDb) = ENC(*ppDb) = SQLITE_UTF16NATIVE;
130505     }
130506   }else{
130507     rc = SQLITE_NOMEM;
130508   }
130509   sqlite3ValueFree(pVal);
130510
130511   return sqlite3ApiExit(0, rc);
130512 }
130513 #endif /* SQLITE_OMIT_UTF16 */
130514
130515 /*
130516 ** Register a new collation sequence with the database handle db.
130517 */
130518 SQLITE_API int SQLITE_STDCALL sqlite3_create_collation(
130519   sqlite3* db, 
130520   const char *zName, 
130521   int enc, 
130522   void* pCtx,
130523   int(*xCompare)(void*,int,const void*,int,const void*)
130524 ){
130525   return sqlite3_create_collation_v2(db, zName, enc, pCtx, xCompare, 0);
130526 }
130527
130528 /*
130529 ** Register a new collation sequence with the database handle db.
130530 */
130531 SQLITE_API int SQLITE_STDCALL sqlite3_create_collation_v2(
130532   sqlite3* db, 
130533   const char *zName, 
130534   int enc, 
130535   void* pCtx,
130536   int(*xCompare)(void*,int,const void*,int,const void*),
130537   void(*xDel)(void*)
130538 ){
130539   int rc;
130540
130541 #ifdef SQLITE_ENABLE_API_ARMOR
130542   if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
130543 #endif
130544   sqlite3_mutex_enter(db->mutex);
130545   assert( !db->mallocFailed );
130546   rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
130547   rc = sqlite3ApiExit(db, rc);
130548   sqlite3_mutex_leave(db->mutex);
130549   return rc;
130550 }
130551
130552 #ifndef SQLITE_OMIT_UTF16
130553 /*
130554 ** Register a new collation sequence with the database handle db.
130555 */
130556 SQLITE_API int SQLITE_STDCALL sqlite3_create_collation16(
130557   sqlite3* db, 
130558   const void *zName,
130559   int enc, 
130560   void* pCtx,
130561   int(*xCompare)(void*,int,const void*,int,const void*)
130562 ){
130563   int rc = SQLITE_OK;
130564   char *zName8;
130565
130566 #ifdef SQLITE_ENABLE_API_ARMOR
130567   if( !sqlite3SafetyCheckOk(db) || zName==0 ) return SQLITE_MISUSE_BKPT;
130568 #endif
130569   sqlite3_mutex_enter(db->mutex);
130570   assert( !db->mallocFailed );
130571   zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
130572   if( zName8 ){
130573     rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
130574     sqlite3DbFree(db, zName8);
130575   }
130576   rc = sqlite3ApiExit(db, rc);
130577   sqlite3_mutex_leave(db->mutex);
130578   return rc;
130579 }
130580 #endif /* SQLITE_OMIT_UTF16 */
130581
130582 /*
130583 ** Register a collation sequence factory callback with the database handle
130584 ** db. Replace any previously installed collation sequence factory.
130585 */
130586 SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed(
130587   sqlite3 *db, 
130588   void *pCollNeededArg, 
130589   void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
130590 ){
130591 #ifdef SQLITE_ENABLE_API_ARMOR
130592   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
130593 #endif
130594   sqlite3_mutex_enter(db->mutex);
130595   db->xCollNeeded = xCollNeeded;
130596   db->xCollNeeded16 = 0;
130597   db->pCollNeededArg = pCollNeededArg;
130598   sqlite3_mutex_leave(db->mutex);
130599   return SQLITE_OK;
130600 }
130601
130602 #ifndef SQLITE_OMIT_UTF16
130603 /*
130604 ** Register a collation sequence factory callback with the database handle
130605 ** db. Replace any previously installed collation sequence factory.
130606 */
130607 SQLITE_API int SQLITE_STDCALL sqlite3_collation_needed16(
130608   sqlite3 *db, 
130609   void *pCollNeededArg, 
130610   void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
130611 ){
130612 #ifdef SQLITE_ENABLE_API_ARMOR
130613   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
130614 #endif
130615   sqlite3_mutex_enter(db->mutex);
130616   db->xCollNeeded = 0;
130617   db->xCollNeeded16 = xCollNeeded16;
130618   db->pCollNeededArg = pCollNeededArg;
130619   sqlite3_mutex_leave(db->mutex);
130620   return SQLITE_OK;
130621 }
130622 #endif /* SQLITE_OMIT_UTF16 */
130623
130624 #ifndef SQLITE_OMIT_DEPRECATED
130625 /*
130626 ** This function is now an anachronism. It used to be used to recover from a
130627 ** malloc() failure, but SQLite now does this automatically.
130628 */
130629 SQLITE_API int SQLITE_STDCALL sqlite3_global_recover(void){
130630   return SQLITE_OK;
130631 }
130632 #endif
130633
130634 /*
130635 ** Test to see whether or not the database connection is in autocommit
130636 ** mode.  Return TRUE if it is and FALSE if not.  Autocommit mode is on
130637 ** by default.  Autocommit is disabled by a BEGIN statement and reenabled
130638 ** by the next COMMIT or ROLLBACK.
130639 */
130640 SQLITE_API int SQLITE_STDCALL sqlite3_get_autocommit(sqlite3 *db){
130641 #ifdef SQLITE_ENABLE_API_ARMOR
130642   if( !sqlite3SafetyCheckOk(db) ){
130643     (void)SQLITE_MISUSE_BKPT;
130644     return 0;
130645   }
130646 #endif
130647   return db->autoCommit;
130648 }
130649
130650 /*
130651 ** The following routines are substitutes for constants SQLITE_CORRUPT,
130652 ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
130653 ** constants.  They serve two purposes:
130654 **
130655 **   1.  Serve as a convenient place to set a breakpoint in a debugger
130656 **       to detect when version error conditions occurs.
130657 **
130658 **   2.  Invoke sqlite3_log() to provide the source code location where
130659 **       a low-level error is first detected.
130660 */
130661 SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
130662   testcase( sqlite3GlobalConfig.xLog!=0 );
130663   sqlite3_log(SQLITE_CORRUPT,
130664               "database corruption at line %d of [%.10s]",
130665               lineno, 20+sqlite3_sourceid());
130666   return SQLITE_CORRUPT;
130667 }
130668 SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
130669   testcase( sqlite3GlobalConfig.xLog!=0 );
130670   sqlite3_log(SQLITE_MISUSE, 
130671               "misuse at line %d of [%.10s]",
130672               lineno, 20+sqlite3_sourceid());
130673   return SQLITE_MISUSE;
130674 }
130675 SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
130676   testcase( sqlite3GlobalConfig.xLog!=0 );
130677   sqlite3_log(SQLITE_CANTOPEN, 
130678               "cannot open file at line %d of [%.10s]",
130679               lineno, 20+sqlite3_sourceid());
130680   return SQLITE_CANTOPEN;
130681 }
130682
130683
130684 #ifndef SQLITE_OMIT_DEPRECATED
130685 /*
130686 ** This is a convenience routine that makes sure that all thread-specific
130687 ** data for this thread has been deallocated.
130688 **
130689 ** SQLite no longer uses thread-specific data so this routine is now a
130690 ** no-op.  It is retained for historical compatibility.
130691 */
130692 SQLITE_API void SQLITE_STDCALL sqlite3_thread_cleanup(void){
130693 }
130694 #endif
130695
130696 /*
130697 ** Return meta information about a specific column of a database table.
130698 ** See comment in sqlite3.h (sqlite.h.in) for details.
130699 */
130700 SQLITE_API int SQLITE_STDCALL sqlite3_table_column_metadata(
130701   sqlite3 *db,                /* Connection handle */
130702   const char *zDbName,        /* Database name or NULL */
130703   const char *zTableName,     /* Table name */
130704   const char *zColumnName,    /* Column name */
130705   char const **pzDataType,    /* OUTPUT: Declared data type */
130706   char const **pzCollSeq,     /* OUTPUT: Collation sequence name */
130707   int *pNotNull,              /* OUTPUT: True if NOT NULL constraint exists */
130708   int *pPrimaryKey,           /* OUTPUT: True if column part of PK */
130709   int *pAutoinc               /* OUTPUT: True if column is auto-increment */
130710 ){
130711   int rc;
130712   char *zErrMsg = 0;
130713   Table *pTab = 0;
130714   Column *pCol = 0;
130715   int iCol = 0;
130716   char const *zDataType = 0;
130717   char const *zCollSeq = 0;
130718   int notnull = 0;
130719   int primarykey = 0;
130720   int autoinc = 0;
130721
130722
130723 #ifdef SQLITE_ENABLE_API_ARMOR
130724   if( !sqlite3SafetyCheckOk(db) || zTableName==0 ){
130725     return SQLITE_MISUSE_BKPT;
130726   }
130727 #endif
130728
130729   /* Ensure the database schema has been loaded */
130730   sqlite3_mutex_enter(db->mutex);
130731   sqlite3BtreeEnterAll(db);
130732   rc = sqlite3Init(db, &zErrMsg);
130733   if( SQLITE_OK!=rc ){
130734     goto error_out;
130735   }
130736
130737   /* Locate the table in question */
130738   pTab = sqlite3FindTable(db, zTableName, zDbName);
130739   if( !pTab || pTab->pSelect ){
130740     pTab = 0;
130741     goto error_out;
130742   }
130743
130744   /* Find the column for which info is requested */
130745   if( zColumnName==0 ){
130746     /* Query for existance of table only */
130747   }else{
130748     for(iCol=0; iCol<pTab->nCol; iCol++){
130749       pCol = &pTab->aCol[iCol];
130750       if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
130751         break;
130752       }
130753     }
130754     if( iCol==pTab->nCol ){
130755       if( HasRowid(pTab) && sqlite3IsRowid(zColumnName) ){
130756         iCol = pTab->iPKey;
130757         pCol = iCol>=0 ? &pTab->aCol[iCol] : 0;
130758       }else{
130759         pTab = 0;
130760         goto error_out;
130761       }
130762     }
130763   }
130764
130765   /* The following block stores the meta information that will be returned
130766   ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
130767   ** and autoinc. At this point there are two possibilities:
130768   ** 
130769   **     1. The specified column name was rowid", "oid" or "_rowid_" 
130770   **        and there is no explicitly declared IPK column. 
130771   **
130772   **     2. The table is not a view and the column name identified an 
130773   **        explicitly declared column. Copy meta information from *pCol.
130774   */ 
130775   if( pCol ){
130776     zDataType = pCol->zType;
130777     zCollSeq = pCol->zColl;
130778     notnull = pCol->notNull!=0;
130779     primarykey  = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
130780     autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
130781   }else{
130782     zDataType = "INTEGER";
130783     primarykey = 1;
130784   }
130785   if( !zCollSeq ){
130786     zCollSeq = "BINARY";
130787   }
130788
130789 error_out:
130790   sqlite3BtreeLeaveAll(db);
130791
130792   /* Whether the function call succeeded or failed, set the output parameters
130793   ** to whatever their local counterparts contain. If an error did occur,
130794   ** this has the effect of zeroing all output parameters.
130795   */
130796   if( pzDataType ) *pzDataType = zDataType;
130797   if( pzCollSeq ) *pzCollSeq = zCollSeq;
130798   if( pNotNull ) *pNotNull = notnull;
130799   if( pPrimaryKey ) *pPrimaryKey = primarykey;
130800   if( pAutoinc ) *pAutoinc = autoinc;
130801
130802   if( SQLITE_OK==rc && !pTab ){
130803     sqlite3DbFree(db, zErrMsg);
130804     zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
130805         zColumnName);
130806     rc = SQLITE_ERROR;
130807   }
130808   sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
130809   sqlite3DbFree(db, zErrMsg);
130810   rc = sqlite3ApiExit(db, rc);
130811   sqlite3_mutex_leave(db->mutex);
130812   return rc;
130813 }
130814
130815 /*
130816 ** Sleep for a little while.  Return the amount of time slept.
130817 */
130818 SQLITE_API int SQLITE_STDCALL sqlite3_sleep(int ms){
130819   sqlite3_vfs *pVfs;
130820   int rc;
130821   pVfs = sqlite3_vfs_find(0);
130822   if( pVfs==0 ) return 0;
130823
130824   /* This function works in milliseconds, but the underlying OsSleep() 
130825   ** API uses microseconds. Hence the 1000's.
130826   */
130827   rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
130828   return rc;
130829 }
130830
130831 /*
130832 ** Enable or disable the extended result codes.
130833 */
130834 SQLITE_API int SQLITE_STDCALL sqlite3_extended_result_codes(sqlite3 *db, int onoff){
130835 #ifdef SQLITE_ENABLE_API_ARMOR
130836   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
130837 #endif
130838   sqlite3_mutex_enter(db->mutex);
130839   db->errMask = onoff ? 0xffffffff : 0xff;
130840   sqlite3_mutex_leave(db->mutex);
130841   return SQLITE_OK;
130842 }
130843
130844 /*
130845 ** Invoke the xFileControl method on a particular database.
130846 */
130847 SQLITE_API int SQLITE_STDCALL sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
130848   int rc = SQLITE_ERROR;
130849   Btree *pBtree;
130850
130851 #ifdef SQLITE_ENABLE_API_ARMOR
130852   if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
130853 #endif
130854   sqlite3_mutex_enter(db->mutex);
130855   pBtree = sqlite3DbNameToBtree(db, zDbName);
130856   if( pBtree ){
130857     Pager *pPager;
130858     sqlite3_file *fd;
130859     sqlite3BtreeEnter(pBtree);
130860     pPager = sqlite3BtreePager(pBtree);
130861     assert( pPager!=0 );
130862     fd = sqlite3PagerFile(pPager);
130863     assert( fd!=0 );
130864     if( op==SQLITE_FCNTL_FILE_POINTER ){
130865       *(sqlite3_file**)pArg = fd;
130866       rc = SQLITE_OK;
130867     }else if( fd->pMethods ){
130868       rc = sqlite3OsFileControl(fd, op, pArg);
130869     }else{
130870       rc = SQLITE_NOTFOUND;
130871     }
130872     sqlite3BtreeLeave(pBtree);
130873   }
130874   sqlite3_mutex_leave(db->mutex);
130875   return rc;
130876 }
130877
130878 /*
130879 ** Interface to the testing logic.
130880 */
130881 SQLITE_API int SQLITE_CDECL sqlite3_test_control(int op, ...){
130882   int rc = 0;
130883 #ifndef SQLITE_OMIT_BUILTIN_TEST
130884   va_list ap;
130885   va_start(ap, op);
130886   switch( op ){
130887
130888     /*
130889     ** Save the current state of the PRNG.
130890     */
130891     case SQLITE_TESTCTRL_PRNG_SAVE: {
130892       sqlite3PrngSaveState();
130893       break;
130894     }
130895
130896     /*
130897     ** Restore the state of the PRNG to the last state saved using
130898     ** PRNG_SAVE.  If PRNG_SAVE has never before been called, then
130899     ** this verb acts like PRNG_RESET.
130900     */
130901     case SQLITE_TESTCTRL_PRNG_RESTORE: {
130902       sqlite3PrngRestoreState();
130903       break;
130904     }
130905
130906     /*
130907     ** Reset the PRNG back to its uninitialized state.  The next call
130908     ** to sqlite3_randomness() will reseed the PRNG using a single call
130909     ** to the xRandomness method of the default VFS.
130910     */
130911     case SQLITE_TESTCTRL_PRNG_RESET: {
130912       sqlite3_randomness(0,0);
130913       break;
130914     }
130915
130916     /*
130917     **  sqlite3_test_control(BITVEC_TEST, size, program)
130918     **
130919     ** Run a test against a Bitvec object of size.  The program argument
130920     ** is an array of integers that defines the test.  Return -1 on a
130921     ** memory allocation error, 0 on success, or non-zero for an error.
130922     ** See the sqlite3BitvecBuiltinTest() for additional information.
130923     */
130924     case SQLITE_TESTCTRL_BITVEC_TEST: {
130925       int sz = va_arg(ap, int);
130926       int *aProg = va_arg(ap, int*);
130927       rc = sqlite3BitvecBuiltinTest(sz, aProg);
130928       break;
130929     }
130930
130931     /*
130932     **  sqlite3_test_control(FAULT_INSTALL, xCallback)
130933     **
130934     ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
130935     ** if xCallback is not NULL.
130936     **
130937     ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
130938     ** is called immediately after installing the new callback and the return
130939     ** value from sqlite3FaultSim(0) becomes the return from
130940     ** sqlite3_test_control().
130941     */
130942     case SQLITE_TESTCTRL_FAULT_INSTALL: {
130943       /* MSVC is picky about pulling func ptrs from va lists.
130944       ** http://support.microsoft.com/kb/47961
130945       ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
130946       */
130947       typedef int(*TESTCALLBACKFUNC_t)(int);
130948       sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
130949       rc = sqlite3FaultSim(0);
130950       break;
130951     }
130952
130953     /*
130954     **  sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
130955     **
130956     ** Register hooks to call to indicate which malloc() failures 
130957     ** are benign.
130958     */
130959     case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
130960       typedef void (*void_function)(void);
130961       void_function xBenignBegin;
130962       void_function xBenignEnd;
130963       xBenignBegin = va_arg(ap, void_function);
130964       xBenignEnd = va_arg(ap, void_function);
130965       sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
130966       break;
130967     }
130968
130969     /*
130970     **  sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
130971     **
130972     ** Set the PENDING byte to the value in the argument, if X>0.
130973     ** Make no changes if X==0.  Return the value of the pending byte
130974     ** as it existing before this routine was called.
130975     **
130976     ** IMPORTANT:  Changing the PENDING byte from 0x40000000 results in
130977     ** an incompatible database file format.  Changing the PENDING byte
130978     ** while any database connection is open results in undefined and
130979     ** deleterious behavior.
130980     */
130981     case SQLITE_TESTCTRL_PENDING_BYTE: {
130982       rc = PENDING_BYTE;
130983 #ifndef SQLITE_OMIT_WSD
130984       {
130985         unsigned int newVal = va_arg(ap, unsigned int);
130986         if( newVal ) sqlite3PendingByte = newVal;
130987       }
130988 #endif
130989       break;
130990     }
130991
130992     /*
130993     **  sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
130994     **
130995     ** This action provides a run-time test to see whether or not
130996     ** assert() was enabled at compile-time.  If X is true and assert()
130997     ** is enabled, then the return value is true.  If X is true and
130998     ** assert() is disabled, then the return value is zero.  If X is
130999     ** false and assert() is enabled, then the assertion fires and the
131000     ** process aborts.  If X is false and assert() is disabled, then the
131001     ** return value is zero.
131002     */
131003     case SQLITE_TESTCTRL_ASSERT: {
131004       volatile int x = 0;
131005       assert( (x = va_arg(ap,int))!=0 );
131006       rc = x;
131007       break;
131008     }
131009
131010
131011     /*
131012     **  sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
131013     **
131014     ** This action provides a run-time test to see how the ALWAYS and
131015     ** NEVER macros were defined at compile-time.
131016     **
131017     ** The return value is ALWAYS(X).  
131018     **
131019     ** The recommended test is X==2.  If the return value is 2, that means
131020     ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
131021     ** default setting.  If the return value is 1, then ALWAYS() is either
131022     ** hard-coded to true or else it asserts if its argument is false.
131023     ** The first behavior (hard-coded to true) is the case if
131024     ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
131025     ** behavior (assert if the argument to ALWAYS() is false) is the case if
131026     ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
131027     **
131028     ** The run-time test procedure might look something like this:
131029     **
131030     **    if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
131031     **      // ALWAYS() and NEVER() are no-op pass-through macros
131032     **    }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
131033     **      // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
131034     **    }else{
131035     **      // ALWAYS(x) is a constant 1.  NEVER(x) is a constant 0.
131036     **    }
131037     */
131038     case SQLITE_TESTCTRL_ALWAYS: {
131039       int x = va_arg(ap,int);
131040       rc = ALWAYS(x);
131041       break;
131042     }
131043
131044     /*
131045     **   sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
131046     **
131047     ** The integer returned reveals the byte-order of the computer on which
131048     ** SQLite is running:
131049     **
131050     **       1     big-endian,    determined at run-time
131051     **      10     little-endian, determined at run-time
131052     **  432101     big-endian,    determined at compile-time
131053     **  123410     little-endian, determined at compile-time
131054     */ 
131055     case SQLITE_TESTCTRL_BYTEORDER: {
131056       rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
131057       break;
131058     }
131059
131060     /*   sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
131061     **
131062     ** Set the nReserve size to N for the main database on the database
131063     ** connection db.
131064     */
131065     case SQLITE_TESTCTRL_RESERVE: {
131066       sqlite3 *db = va_arg(ap, sqlite3*);
131067       int x = va_arg(ap,int);
131068       sqlite3_mutex_enter(db->mutex);
131069       sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
131070       sqlite3_mutex_leave(db->mutex);
131071       break;
131072     }
131073
131074     /*  sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
131075     **
131076     ** Enable or disable various optimizations for testing purposes.  The 
131077     ** argument N is a bitmask of optimizations to be disabled.  For normal
131078     ** operation N should be 0.  The idea is that a test program (like the
131079     ** SQL Logic Test or SLT test module) can run the same SQL multiple times
131080     ** with various optimizations disabled to verify that the same answer
131081     ** is obtained in every case.
131082     */
131083     case SQLITE_TESTCTRL_OPTIMIZATIONS: {
131084       sqlite3 *db = va_arg(ap, sqlite3*);
131085       db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
131086       break;
131087     }
131088
131089 #ifdef SQLITE_N_KEYWORD
131090     /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
131091     **
131092     ** If zWord is a keyword recognized by the parser, then return the
131093     ** number of keywords.  Or if zWord is not a keyword, return 0.
131094     ** 
131095     ** This test feature is only available in the amalgamation since
131096     ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
131097     ** is built using separate source files.
131098     */
131099     case SQLITE_TESTCTRL_ISKEYWORD: {
131100       const char *zWord = va_arg(ap, const char*);
131101       int n = sqlite3Strlen30(zWord);
131102       rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
131103       break;
131104     }
131105 #endif 
131106
131107     /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
131108     **
131109     ** Pass pFree into sqlite3ScratchFree(). 
131110     ** If sz>0 then allocate a scratch buffer into pNew.  
131111     */
131112     case SQLITE_TESTCTRL_SCRATCHMALLOC: {
131113       void *pFree, **ppNew;
131114       int sz;
131115       sz = va_arg(ap, int);
131116       ppNew = va_arg(ap, void**);
131117       pFree = va_arg(ap, void*);
131118       if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
131119       sqlite3ScratchFree(pFree);
131120       break;
131121     }
131122
131123     /*   sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
131124     **
131125     ** If parameter onoff is non-zero, configure the wrappers so that all
131126     ** subsequent calls to localtime() and variants fail. If onoff is zero,
131127     ** undo this setting.
131128     */
131129     case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
131130       sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
131131       break;
131132     }
131133
131134     /*   sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
131135     **
131136     ** Set or clear a flag that indicates that the database file is always well-
131137     ** formed and never corrupt.  This flag is clear by default, indicating that
131138     ** database files might have arbitrary corruption.  Setting the flag during
131139     ** testing causes certain assert() statements in the code to be activated
131140     ** that demonstrat invariants on well-formed database files.
131141     */
131142     case SQLITE_TESTCTRL_NEVER_CORRUPT: {
131143       sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
131144       break;
131145     }
131146
131147
131148     /*   sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
131149     **
131150     ** Set the VDBE coverage callback function to xCallback with context 
131151     ** pointer ptr.
131152     */
131153     case SQLITE_TESTCTRL_VDBE_COVERAGE: {
131154 #ifdef SQLITE_VDBE_COVERAGE
131155       typedef void (*branch_callback)(void*,int,u8,u8);
131156       sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
131157       sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
131158 #endif
131159       break;
131160     }
131161
131162     /*   sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
131163     case SQLITE_TESTCTRL_SORTER_MMAP: {
131164       sqlite3 *db = va_arg(ap, sqlite3*);
131165       db->nMaxSorterMmap = va_arg(ap, int);
131166       break;
131167     }
131168
131169     /*   sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
131170     **
131171     ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
131172     ** not.
131173     */
131174     case SQLITE_TESTCTRL_ISINIT: {
131175       if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
131176       break;
131177     }
131178
131179     /*  sqlite3_test_control(SQLITE_TESTCTRL_IMPOSTER, db, dbName, onOff, tnum);
131180     **
131181     ** This test control is used to create imposter tables.  "db" is a pointer
131182     ** to the database connection.  dbName is the database name (ex: "main" or
131183     ** "temp") which will receive the imposter.  "onOff" turns imposter mode on
131184     ** or off.  "tnum" is the root page of the b-tree to which the imposter
131185     ** table should connect.
131186     **
131187     ** Enable imposter mode only when the schema has already been parsed.  Then
131188     ** run a single CREATE TABLE statement to construct the imposter table in
131189     ** the parsed schema.  Then turn imposter mode back off again.
131190     **
131191     ** If onOff==0 and tnum>0 then reset the schema for all databases, causing
131192     ** the schema to be reparsed the next time it is needed.  This has the
131193     ** effect of erasing all imposter tables.
131194     */
131195     case SQLITE_TESTCTRL_IMPOSTER: {
131196       sqlite3 *db = va_arg(ap, sqlite3*);
131197       sqlite3_mutex_enter(db->mutex);
131198       db->init.iDb = sqlite3FindDbName(db, va_arg(ap,const char*));
131199       db->init.busy = db->init.imposterTable = va_arg(ap,int);
131200       db->init.newTnum = va_arg(ap,int);
131201       if( db->init.busy==0 && db->init.newTnum>0 ){
131202         sqlite3ResetAllSchemasOfConnection(db);
131203       }
131204       sqlite3_mutex_leave(db->mutex);
131205       break;
131206     }
131207   }
131208   va_end(ap);
131209 #endif /* SQLITE_OMIT_BUILTIN_TEST */
131210   return rc;
131211 }
131212
131213 /*
131214 ** This is a utility routine, useful to VFS implementations, that checks
131215 ** to see if a database file was a URI that contained a specific query 
131216 ** parameter, and if so obtains the value of the query parameter.
131217 **
131218 ** The zFilename argument is the filename pointer passed into the xOpen()
131219 ** method of a VFS implementation.  The zParam argument is the name of the
131220 ** query parameter we seek.  This routine returns the value of the zParam
131221 ** parameter if it exists.  If the parameter does not exist, this routine
131222 ** returns a NULL pointer.
131223 */
131224 SQLITE_API const char *SQLITE_STDCALL sqlite3_uri_parameter(const char *zFilename, const char *zParam){
131225   if( zFilename==0 || zParam==0 ) return 0;
131226   zFilename += sqlite3Strlen30(zFilename) + 1;
131227   while( zFilename[0] ){
131228     int x = strcmp(zFilename, zParam);
131229     zFilename += sqlite3Strlen30(zFilename) + 1;
131230     if( x==0 ) return zFilename;
131231     zFilename += sqlite3Strlen30(zFilename) + 1;
131232   }
131233   return 0;
131234 }
131235
131236 /*
131237 ** Return a boolean value for a query parameter.
131238 */
131239 SQLITE_API int SQLITE_STDCALL sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
131240   const char *z = sqlite3_uri_parameter(zFilename, zParam);
131241   bDflt = bDflt!=0;
131242   return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
131243 }
131244
131245 /*
131246 ** Return a 64-bit integer value for a query parameter.
131247 */
131248 SQLITE_API sqlite3_int64 SQLITE_STDCALL sqlite3_uri_int64(
131249   const char *zFilename,    /* Filename as passed to xOpen */
131250   const char *zParam,       /* URI parameter sought */
131251   sqlite3_int64 bDflt       /* return if parameter is missing */
131252 ){
131253   const char *z = sqlite3_uri_parameter(zFilename, zParam);
131254   sqlite3_int64 v;
131255   if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
131256     bDflt = v;
131257   }
131258   return bDflt;
131259 }
131260
131261 /*
131262 ** Return the Btree pointer identified by zDbName.  Return NULL if not found.
131263 */
131264 SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
131265   int i;
131266   for(i=0; i<db->nDb; i++){
131267     if( db->aDb[i].pBt
131268      && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
131269     ){
131270       return db->aDb[i].pBt;
131271     }
131272   }
131273   return 0;
131274 }
131275
131276 /*
131277 ** Return the filename of the database associated with a database
131278 ** connection.
131279 */
131280 SQLITE_API const char *SQLITE_STDCALL sqlite3_db_filename(sqlite3 *db, const char *zDbName){
131281   Btree *pBt;
131282 #ifdef SQLITE_ENABLE_API_ARMOR
131283   if( !sqlite3SafetyCheckOk(db) ){
131284     (void)SQLITE_MISUSE_BKPT;
131285     return 0;
131286   }
131287 #endif
131288   pBt = sqlite3DbNameToBtree(db, zDbName);
131289   return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
131290 }
131291
131292 /*
131293 ** Return 1 if database is read-only or 0 if read/write.  Return -1 if
131294 ** no such database exists.
131295 */
131296 SQLITE_API int SQLITE_STDCALL sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
131297   Btree *pBt;
131298 #ifdef SQLITE_ENABLE_API_ARMOR
131299   if( !sqlite3SafetyCheckOk(db) ){
131300     (void)SQLITE_MISUSE_BKPT;
131301     return -1;
131302   }
131303 #endif
131304   pBt = sqlite3DbNameToBtree(db, zDbName);
131305   return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
131306 }
131307
131308 /************** End of main.c ************************************************/
131309 /************** Begin file notify.c ******************************************/
131310 /*
131311 ** 2009 March 3
131312 **
131313 ** The author disclaims copyright to this source code.  In place of
131314 ** a legal notice, here is a blessing:
131315 **
131316 **    May you do good and not evil.
131317 **    May you find forgiveness for yourself and forgive others.
131318 **    May you share freely, never taking more than you give.
131319 **
131320 *************************************************************************
131321 **
131322 ** This file contains the implementation of the sqlite3_unlock_notify()
131323 ** API method and its associated functionality.
131324 */
131325
131326 /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
131327 #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
131328
131329 /*
131330 ** Public interfaces:
131331 **
131332 **   sqlite3ConnectionBlocked()
131333 **   sqlite3ConnectionUnlocked()
131334 **   sqlite3ConnectionClosed()
131335 **   sqlite3_unlock_notify()
131336 */
131337
131338 #define assertMutexHeld() \
131339   assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
131340
131341 /*
131342 ** Head of a linked list of all sqlite3 objects created by this process
131343 ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
131344 ** is not NULL. This variable may only accessed while the STATIC_MASTER
131345 ** mutex is held.
131346 */
131347 static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
131348
131349 #ifndef NDEBUG
131350 /*
131351 ** This function is a complex assert() that verifies the following 
131352 ** properties of the blocked connections list:
131353 **
131354 **   1) Each entry in the list has a non-NULL value for either 
131355 **      pUnlockConnection or pBlockingConnection, or both.
131356 **
131357 **   2) All entries in the list that share a common value for 
131358 **      xUnlockNotify are grouped together.
131359 **
131360 **   3) If the argument db is not NULL, then none of the entries in the
131361 **      blocked connections list have pUnlockConnection or pBlockingConnection
131362 **      set to db. This is used when closing connection db.
131363 */
131364 static void checkListProperties(sqlite3 *db){
131365   sqlite3 *p;
131366   for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
131367     int seen = 0;
131368     sqlite3 *p2;
131369
131370     /* Verify property (1) */
131371     assert( p->pUnlockConnection || p->pBlockingConnection );
131372
131373     /* Verify property (2) */
131374     for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
131375       if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
131376       assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
131377       assert( db==0 || p->pUnlockConnection!=db );
131378       assert( db==0 || p->pBlockingConnection!=db );
131379     }
131380   }
131381 }
131382 #else
131383 # define checkListProperties(x)
131384 #endif
131385
131386 /*
131387 ** Remove connection db from the blocked connections list. If connection
131388 ** db is not currently a part of the list, this function is a no-op.
131389 */
131390 static void removeFromBlockedList(sqlite3 *db){
131391   sqlite3 **pp;
131392   assertMutexHeld();
131393   for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
131394     if( *pp==db ){
131395       *pp = (*pp)->pNextBlocked;
131396       break;
131397     }
131398   }
131399 }
131400
131401 /*
131402 ** Add connection db to the blocked connections list. It is assumed
131403 ** that it is not already a part of the list.
131404 */
131405 static void addToBlockedList(sqlite3 *db){
131406   sqlite3 **pp;
131407   assertMutexHeld();
131408   for(
131409     pp=&sqlite3BlockedList; 
131410     *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify; 
131411     pp=&(*pp)->pNextBlocked
131412   );
131413   db->pNextBlocked = *pp;
131414   *pp = db;
131415 }
131416
131417 /*
131418 ** Obtain the STATIC_MASTER mutex.
131419 */
131420 static void enterMutex(void){
131421   sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
131422   checkListProperties(0);
131423 }
131424
131425 /*
131426 ** Release the STATIC_MASTER mutex.
131427 */
131428 static void leaveMutex(void){
131429   assertMutexHeld();
131430   checkListProperties(0);
131431   sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
131432 }
131433
131434 /*
131435 ** Register an unlock-notify callback.
131436 **
131437 ** This is called after connection "db" has attempted some operation
131438 ** but has received an SQLITE_LOCKED error because another connection
131439 ** (call it pOther) in the same process was busy using the same shared
131440 ** cache.  pOther is found by looking at db->pBlockingConnection.
131441 **
131442 ** If there is no blocking connection, the callback is invoked immediately,
131443 ** before this routine returns.
131444 **
131445 ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
131446 ** a deadlock.
131447 **
131448 ** Otherwise, make arrangements to invoke xNotify when pOther drops
131449 ** its locks.
131450 **
131451 ** Each call to this routine overrides any prior callbacks registered
131452 ** on the same "db".  If xNotify==0 then any prior callbacks are immediately
131453 ** cancelled.
131454 */
131455 SQLITE_API int SQLITE_STDCALL sqlite3_unlock_notify(
131456   sqlite3 *db,
131457   void (*xNotify)(void **, int),
131458   void *pArg
131459 ){
131460   int rc = SQLITE_OK;
131461
131462   sqlite3_mutex_enter(db->mutex);
131463   enterMutex();
131464
131465   if( xNotify==0 ){
131466     removeFromBlockedList(db);
131467     db->pBlockingConnection = 0;
131468     db->pUnlockConnection = 0;
131469     db->xUnlockNotify = 0;
131470     db->pUnlockArg = 0;
131471   }else if( 0==db->pBlockingConnection ){
131472     /* The blocking transaction has been concluded. Or there never was a 
131473     ** blocking transaction. In either case, invoke the notify callback
131474     ** immediately. 
131475     */
131476     xNotify(&pArg, 1);
131477   }else{
131478     sqlite3 *p;
131479
131480     for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
131481     if( p ){
131482       rc = SQLITE_LOCKED;              /* Deadlock detected. */
131483     }else{
131484       db->pUnlockConnection = db->pBlockingConnection;
131485       db->xUnlockNotify = xNotify;
131486       db->pUnlockArg = pArg;
131487       removeFromBlockedList(db);
131488       addToBlockedList(db);
131489     }
131490   }
131491
131492   leaveMutex();
131493   assert( !db->mallocFailed );
131494   sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
131495   sqlite3_mutex_leave(db->mutex);
131496   return rc;
131497 }
131498
131499 /*
131500 ** This function is called while stepping or preparing a statement 
131501 ** associated with connection db. The operation will return SQLITE_LOCKED
131502 ** to the user because it requires a lock that will not be available
131503 ** until connection pBlocker concludes its current transaction.
131504 */
131505 SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
131506   enterMutex();
131507   if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
131508     addToBlockedList(db);
131509   }
131510   db->pBlockingConnection = pBlocker;
131511   leaveMutex();
131512 }
131513
131514 /*
131515 ** This function is called when
131516 ** the transaction opened by database db has just finished. Locks held 
131517 ** by database connection db have been released.
131518 **
131519 ** This function loops through each entry in the blocked connections
131520 ** list and does the following:
131521 **
131522 **   1) If the sqlite3.pBlockingConnection member of a list entry is
131523 **      set to db, then set pBlockingConnection=0.
131524 **
131525 **   2) If the sqlite3.pUnlockConnection member of a list entry is
131526 **      set to db, then invoke the configured unlock-notify callback and
131527 **      set pUnlockConnection=0.
131528 **
131529 **   3) If the two steps above mean that pBlockingConnection==0 and
131530 **      pUnlockConnection==0, remove the entry from the blocked connections
131531 **      list.
131532 */
131533 SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
131534   void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
131535   int nArg = 0;                            /* Number of entries in aArg[] */
131536   sqlite3 **pp;                            /* Iterator variable */
131537   void **aArg;               /* Arguments to the unlock callback */
131538   void **aDyn = 0;           /* Dynamically allocated space for aArg[] */
131539   void *aStatic[16];         /* Starter space for aArg[].  No malloc required */
131540
131541   aArg = aStatic;
131542   enterMutex();         /* Enter STATIC_MASTER mutex */
131543
131544   /* This loop runs once for each entry in the blocked-connections list. */
131545   for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
131546     sqlite3 *p = *pp;
131547
131548     /* Step 1. */
131549     if( p->pBlockingConnection==db ){
131550       p->pBlockingConnection = 0;
131551     }
131552
131553     /* Step 2. */
131554     if( p->pUnlockConnection==db ){
131555       assert( p->xUnlockNotify );
131556       if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
131557         xUnlockNotify(aArg, nArg);
131558         nArg = 0;
131559       }
131560
131561       sqlite3BeginBenignMalloc();
131562       assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
131563       assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
131564       if( (!aDyn && nArg==(int)ArraySize(aStatic))
131565        || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
131566       ){
131567         /* The aArg[] array needs to grow. */
131568         void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
131569         if( pNew ){
131570           memcpy(pNew, aArg, nArg*sizeof(void *));
131571           sqlite3_free(aDyn);
131572           aDyn = aArg = pNew;
131573         }else{
131574           /* This occurs when the array of context pointers that need to
131575           ** be passed to the unlock-notify callback is larger than the
131576           ** aStatic[] array allocated on the stack and the attempt to 
131577           ** allocate a larger array from the heap has failed.
131578           **
131579           ** This is a difficult situation to handle. Returning an error
131580           ** code to the caller is insufficient, as even if an error code
131581           ** is returned the transaction on connection db will still be
131582           ** closed and the unlock-notify callbacks on blocked connections
131583           ** will go unissued. This might cause the application to wait
131584           ** indefinitely for an unlock-notify callback that will never 
131585           ** arrive.
131586           **
131587           ** Instead, invoke the unlock-notify callback with the context
131588           ** array already accumulated. We can then clear the array and
131589           ** begin accumulating any further context pointers without 
131590           ** requiring any dynamic allocation. This is sub-optimal because
131591           ** it means that instead of one callback with a large array of
131592           ** context pointers the application will receive two or more
131593           ** callbacks with smaller arrays of context pointers, which will
131594           ** reduce the applications ability to prioritize multiple 
131595           ** connections. But it is the best that can be done under the
131596           ** circumstances.
131597           */
131598           xUnlockNotify(aArg, nArg);
131599           nArg = 0;
131600         }
131601       }
131602       sqlite3EndBenignMalloc();
131603
131604       aArg[nArg++] = p->pUnlockArg;
131605       xUnlockNotify = p->xUnlockNotify;
131606       p->pUnlockConnection = 0;
131607       p->xUnlockNotify = 0;
131608       p->pUnlockArg = 0;
131609     }
131610
131611     /* Step 3. */
131612     if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
131613       /* Remove connection p from the blocked connections list. */
131614       *pp = p->pNextBlocked;
131615       p->pNextBlocked = 0;
131616     }else{
131617       pp = &p->pNextBlocked;
131618     }
131619   }
131620
131621   if( nArg!=0 ){
131622     xUnlockNotify(aArg, nArg);
131623   }
131624   sqlite3_free(aDyn);
131625   leaveMutex();         /* Leave STATIC_MASTER mutex */
131626 }
131627
131628 /*
131629 ** This is called when the database connection passed as an argument is 
131630 ** being closed. The connection is removed from the blocked list.
131631 */
131632 SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
131633   sqlite3ConnectionUnlocked(db);
131634   enterMutex();
131635   removeFromBlockedList(db);
131636   checkListProperties(db);
131637   leaveMutex();
131638 }
131639 #endif
131640
131641 /************** End of notify.c **********************************************/
131642 /************** Begin file fts3.c ********************************************/
131643 /*
131644 ** 2006 Oct 10
131645 **
131646 ** The author disclaims copyright to this source code.  In place of
131647 ** a legal notice, here is a blessing:
131648 **
131649 **    May you do good and not evil.
131650 **    May you find forgiveness for yourself and forgive others.
131651 **    May you share freely, never taking more than you give.
131652 **
131653 ******************************************************************************
131654 **
131655 ** This is an SQLite module implementing full-text search.
131656 */
131657
131658 /*
131659 ** The code in this file is only compiled if:
131660 **
131661 **     * The FTS3 module is being built as an extension
131662 **       (in which case SQLITE_CORE is not defined), or
131663 **
131664 **     * The FTS3 module is being built into the core of
131665 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
131666 */
131667
131668 /* The full-text index is stored in a series of b+tree (-like)
131669 ** structures called segments which map terms to doclists.  The
131670 ** structures are like b+trees in layout, but are constructed from the
131671 ** bottom up in optimal fashion and are not updatable.  Since trees
131672 ** are built from the bottom up, things will be described from the
131673 ** bottom up.
131674 **
131675 **
131676 **** Varints ****
131677 ** The basic unit of encoding is a variable-length integer called a
131678 ** varint.  We encode variable-length integers in little-endian order
131679 ** using seven bits * per byte as follows:
131680 **
131681 ** KEY:
131682 **         A = 0xxxxxxx    7 bits of data and one flag bit
131683 **         B = 1xxxxxxx    7 bits of data and one flag bit
131684 **
131685 **  7 bits - A
131686 ** 14 bits - BA
131687 ** 21 bits - BBA
131688 ** and so on.
131689 **
131690 ** This is similar in concept to how sqlite encodes "varints" but
131691 ** the encoding is not the same.  SQLite varints are big-endian
131692 ** are are limited to 9 bytes in length whereas FTS3 varints are
131693 ** little-endian and can be up to 10 bytes in length (in theory).
131694 **
131695 ** Example encodings:
131696 **
131697 **     1:    0x01
131698 **   127:    0x7f
131699 **   128:    0x81 0x00
131700 **
131701 **
131702 **** Document lists ****
131703 ** A doclist (document list) holds a docid-sorted list of hits for a
131704 ** given term.  Doclists hold docids and associated token positions.
131705 ** A docid is the unique integer identifier for a single document.
131706 ** A position is the index of a word within the document.  The first 
131707 ** word of the document has a position of 0.
131708 **
131709 ** FTS3 used to optionally store character offsets using a compile-time
131710 ** option.  But that functionality is no longer supported.
131711 **
131712 ** A doclist is stored like this:
131713 **
131714 ** array {
131715 **   varint docid;          (delta from previous doclist)
131716 **   array {                (position list for column 0)
131717 **     varint position;     (2 more than the delta from previous position)
131718 **   }
131719 **   array {
131720 **     varint POS_COLUMN;   (marks start of position list for new column)
131721 **     varint column;       (index of new column)
131722 **     array {
131723 **       varint position;   (2 more than the delta from previous position)
131724 **     }
131725 **   }
131726 **   varint POS_END;        (marks end of positions for this document.
131727 ** }
131728 **
131729 ** Here, array { X } means zero or more occurrences of X, adjacent in
131730 ** memory.  A "position" is an index of a token in the token stream
131731 ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur 
131732 ** in the same logical place as the position element, and act as sentinals
131733 ** ending a position list array.  POS_END is 0.  POS_COLUMN is 1.
131734 ** The positions numbers are not stored literally but rather as two more
131735 ** than the difference from the prior position, or the just the position plus
131736 ** 2 for the first position.  Example:
131737 **
131738 **   label:       A B C D E  F  G H   I  J K
131739 **   value:     123 5 9 1 1 14 35 0 234 72 0
131740 **
131741 ** The 123 value is the first docid.  For column zero in this document
131742 ** there are two matches at positions 3 and 10 (5-2 and 9-2+3).  The 1
131743 ** at D signals the start of a new column; the 1 at E indicates that the
131744 ** new column is column number 1.  There are two positions at 12 and 45
131745 ** (14-2 and 35-2+12).  The 0 at H indicate the end-of-document.  The
131746 ** 234 at I is the delta to next docid (357).  It has one position 70
131747 ** (72-2) and then terminates with the 0 at K.
131748 **
131749 ** A "position-list" is the list of positions for multiple columns for
131750 ** a single docid.  A "column-list" is the set of positions for a single
131751 ** column.  Hence, a position-list consists of one or more column-lists,
131752 ** a document record consists of a docid followed by a position-list and
131753 ** a doclist consists of one or more document records.
131754 **
131755 ** A bare doclist omits the position information, becoming an 
131756 ** array of varint-encoded docids.
131757 **
131758 **** Segment leaf nodes ****
131759 ** Segment leaf nodes store terms and doclists, ordered by term.  Leaf
131760 ** nodes are written using LeafWriter, and read using LeafReader (to
131761 ** iterate through a single leaf node's data) and LeavesReader (to
131762 ** iterate through a segment's entire leaf layer).  Leaf nodes have
131763 ** the format:
131764 **
131765 ** varint iHeight;             (height from leaf level, always 0)
131766 ** varint nTerm;               (length of first term)
131767 ** char pTerm[nTerm];          (content of first term)
131768 ** varint nDoclist;            (length of term's associated doclist)
131769 ** char pDoclist[nDoclist];    (content of doclist)
131770 ** array {
131771 **                             (further terms are delta-encoded)
131772 **   varint nPrefix;           (length of prefix shared with previous term)
131773 **   varint nSuffix;           (length of unshared suffix)
131774 **   char pTermSuffix[nSuffix];(unshared suffix of next term)
131775 **   varint nDoclist;          (length of term's associated doclist)
131776 **   char pDoclist[nDoclist];  (content of doclist)
131777 ** }
131778 **
131779 ** Here, array { X } means zero or more occurrences of X, adjacent in
131780 ** memory.
131781 **
131782 ** Leaf nodes are broken into blocks which are stored contiguously in
131783 ** the %_segments table in sorted order.  This means that when the end
131784 ** of a node is reached, the next term is in the node with the next
131785 ** greater node id.
131786 **
131787 ** New data is spilled to a new leaf node when the current node
131788 ** exceeds LEAF_MAX bytes (default 2048).  New data which itself is
131789 ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
131790 ** node (a leaf node with a single term and doclist).  The goal of
131791 ** these settings is to pack together groups of small doclists while
131792 ** making it efficient to directly access large doclists.  The
131793 ** assumption is that large doclists represent terms which are more
131794 ** likely to be query targets.
131795 **
131796 ** TODO(shess) It may be useful for blocking decisions to be more
131797 ** dynamic.  For instance, it may make more sense to have a 2.5k leaf
131798 ** node rather than splitting into 2k and .5k nodes.  My intuition is
131799 ** that this might extend through 2x or 4x the pagesize.
131800 **
131801 **
131802 **** Segment interior nodes ****
131803 ** Segment interior nodes store blockids for subtree nodes and terms
131804 ** to describe what data is stored by the each subtree.  Interior
131805 ** nodes are written using InteriorWriter, and read using
131806 ** InteriorReader.  InteriorWriters are created as needed when
131807 ** SegmentWriter creates new leaf nodes, or when an interior node
131808 ** itself grows too big and must be split.  The format of interior
131809 ** nodes:
131810 **
131811 ** varint iHeight;           (height from leaf level, always >0)
131812 ** varint iBlockid;          (block id of node's leftmost subtree)
131813 ** optional {
131814 **   varint nTerm;           (length of first term)
131815 **   char pTerm[nTerm];      (content of first term)
131816 **   array {
131817 **                                (further terms are delta-encoded)
131818 **     varint nPrefix;            (length of shared prefix with previous term)
131819 **     varint nSuffix;            (length of unshared suffix)
131820 **     char pTermSuffix[nSuffix]; (unshared suffix of next term)
131821 **   }
131822 ** }
131823 **
131824 ** Here, optional { X } means an optional element, while array { X }
131825 ** means zero or more occurrences of X, adjacent in memory.
131826 **
131827 ** An interior node encodes n terms separating n+1 subtrees.  The
131828 ** subtree blocks are contiguous, so only the first subtree's blockid
131829 ** is encoded.  The subtree at iBlockid will contain all terms less
131830 ** than the first term encoded (or all terms if no term is encoded).
131831 ** Otherwise, for terms greater than or equal to pTerm[i] but less
131832 ** than pTerm[i+1], the subtree for that term will be rooted at
131833 ** iBlockid+i.  Interior nodes only store enough term data to
131834 ** distinguish adjacent children (if the rightmost term of the left
131835 ** child is "something", and the leftmost term of the right child is
131836 ** "wicked", only "w" is stored).
131837 **
131838 ** New data is spilled to a new interior node at the same height when
131839 ** the current node exceeds INTERIOR_MAX bytes (default 2048).
131840 ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
131841 ** interior nodes and making the tree too skinny.  The interior nodes
131842 ** at a given height are naturally tracked by interior nodes at
131843 ** height+1, and so on.
131844 **
131845 **
131846 **** Segment directory ****
131847 ** The segment directory in table %_segdir stores meta-information for
131848 ** merging and deleting segments, and also the root node of the
131849 ** segment's tree.
131850 **
131851 ** The root node is the top node of the segment's tree after encoding
131852 ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
131853 ** This could be either a leaf node or an interior node.  If the top
131854 ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
131855 ** and a new root interior node is generated (which should always fit
131856 ** within ROOT_MAX because it only needs space for 2 varints, the
131857 ** height and the blockid of the previous root).
131858 **
131859 ** The meta-information in the segment directory is:
131860 **   level               - segment level (see below)
131861 **   idx                 - index within level
131862 **                       - (level,idx uniquely identify a segment)
131863 **   start_block         - first leaf node
131864 **   leaves_end_block    - last leaf node
131865 **   end_block           - last block (including interior nodes)
131866 **   root                - contents of root node
131867 **
131868 ** If the root node is a leaf node, then start_block,
131869 ** leaves_end_block, and end_block are all 0.
131870 **
131871 **
131872 **** Segment merging ****
131873 ** To amortize update costs, segments are grouped into levels and
131874 ** merged in batches.  Each increase in level represents exponentially
131875 ** more documents.
131876 **
131877 ** New documents (actually, document updates) are tokenized and
131878 ** written individually (using LeafWriter) to a level 0 segment, with
131879 ** incrementing idx.  When idx reaches MERGE_COUNT (default 16), all
131880 ** level 0 segments are merged into a single level 1 segment.  Level 1
131881 ** is populated like level 0, and eventually MERGE_COUNT level 1
131882 ** segments are merged to a single level 2 segment (representing
131883 ** MERGE_COUNT^2 updates), and so on.
131884 **
131885 ** A segment merge traverses all segments at a given level in
131886 ** parallel, performing a straightforward sorted merge.  Since segment
131887 ** leaf nodes are written in to the %_segments table in order, this
131888 ** merge traverses the underlying sqlite disk structures efficiently.
131889 ** After the merge, all segment blocks from the merged level are
131890 ** deleted.
131891 **
131892 ** MERGE_COUNT controls how often we merge segments.  16 seems to be
131893 ** somewhat of a sweet spot for insertion performance.  32 and 64 show
131894 ** very similar performance numbers to 16 on insertion, though they're
131895 ** a tiny bit slower (perhaps due to more overhead in merge-time
131896 ** sorting).  8 is about 20% slower than 16, 4 about 50% slower than
131897 ** 16, 2 about 66% slower than 16.
131898 **
131899 ** At query time, high MERGE_COUNT increases the number of segments
131900 ** which need to be scanned and merged.  For instance, with 100k docs
131901 ** inserted:
131902 **
131903 **    MERGE_COUNT   segments
131904 **       16           25
131905 **        8           12
131906 **        4           10
131907 **        2            6
131908 **
131909 ** This appears to have only a moderate impact on queries for very
131910 ** frequent terms (which are somewhat dominated by segment merge
131911 ** costs), and infrequent and non-existent terms still seem to be fast
131912 ** even with many segments.
131913 **
131914 ** TODO(shess) That said, it would be nice to have a better query-side
131915 ** argument for MERGE_COUNT of 16.  Also, it is possible/likely that
131916 ** optimizations to things like doclist merging will swing the sweet
131917 ** spot around.
131918 **
131919 **
131920 **
131921 **** Handling of deletions and updates ****
131922 ** Since we're using a segmented structure, with no docid-oriented
131923 ** index into the term index, we clearly cannot simply update the term
131924 ** index when a document is deleted or updated.  For deletions, we
131925 ** write an empty doclist (varint(docid) varint(POS_END)), for updates
131926 ** we simply write the new doclist.  Segment merges overwrite older
131927 ** data for a particular docid with newer data, so deletes or updates
131928 ** will eventually overtake the earlier data and knock it out.  The
131929 ** query logic likewise merges doclists so that newer data knocks out
131930 ** older data.
131931 */
131932
131933 /************** Include fts3Int.h in the middle of fts3.c ********************/
131934 /************** Begin file fts3Int.h *****************************************/
131935 /*
131936 ** 2009 Nov 12
131937 **
131938 ** The author disclaims copyright to this source code.  In place of
131939 ** a legal notice, here is a blessing:
131940 **
131941 **    May you do good and not evil.
131942 **    May you find forgiveness for yourself and forgive others.
131943 **    May you share freely, never taking more than you give.
131944 **
131945 ******************************************************************************
131946 **
131947 */
131948 #ifndef _FTSINT_H
131949 #define _FTSINT_H
131950
131951 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
131952 # define NDEBUG 1
131953 #endif
131954
131955 /*
131956 ** FTS4 is really an extension for FTS3.  It is enabled using the
131957 ** SQLITE_ENABLE_FTS3 macro.  But to avoid confusion we also all
131958 ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
131959 */
131960 #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
131961 # define SQLITE_ENABLE_FTS3
131962 #endif
131963
131964 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
131965
131966 /* If not building as part of the core, include sqlite3ext.h. */
131967 #ifndef SQLITE_CORE
131968 SQLITE_EXTENSION_INIT3
131969 #endif
131970
131971 /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
131972 /************** Begin file fts3_tokenizer.h **********************************/
131973 /*
131974 ** 2006 July 10
131975 **
131976 ** The author disclaims copyright to this source code.
131977 **
131978 *************************************************************************
131979 ** Defines the interface to tokenizers used by fulltext-search.  There
131980 ** are three basic components:
131981 **
131982 ** sqlite3_tokenizer_module is a singleton defining the tokenizer
131983 ** interface functions.  This is essentially the class structure for
131984 ** tokenizers.
131985 **
131986 ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
131987 ** including customization information defined at creation time.
131988 **
131989 ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
131990 ** tokens from a particular input.
131991 */
131992 #ifndef _FTS3_TOKENIZER_H_
131993 #define _FTS3_TOKENIZER_H_
131994
131995 /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
131996 ** If tokenizers are to be allowed to call sqlite3_*() functions, then
131997 ** we will need a way to register the API consistently.
131998 */
131999
132000 /*
132001 ** Structures used by the tokenizer interface. When a new tokenizer
132002 ** implementation is registered, the caller provides a pointer to
132003 ** an sqlite3_tokenizer_module containing pointers to the callback
132004 ** functions that make up an implementation.
132005 **
132006 ** When an fts3 table is created, it passes any arguments passed to
132007 ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
132008 ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
132009 ** implementation. The xCreate() function in turn returns an 
132010 ** sqlite3_tokenizer structure representing the specific tokenizer to
132011 ** be used for the fts3 table (customized by the tokenizer clause arguments).
132012 **
132013 ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
132014 ** method is called. It returns an sqlite3_tokenizer_cursor object
132015 ** that may be used to tokenize a specific input buffer based on
132016 ** the tokenization rules supplied by a specific sqlite3_tokenizer
132017 ** object.
132018 */
132019 typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
132020 typedef struct sqlite3_tokenizer sqlite3_tokenizer;
132021 typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
132022
132023 struct sqlite3_tokenizer_module {
132024
132025   /*
132026   ** Structure version. Should always be set to 0 or 1.
132027   */
132028   int iVersion;
132029
132030   /*
132031   ** Create a new tokenizer. The values in the argv[] array are the
132032   ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
132033   ** TABLE statement that created the fts3 table. For example, if
132034   ** the following SQL is executed:
132035   **
132036   **   CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
132037   **
132038   ** then argc is set to 2, and the argv[] array contains pointers
132039   ** to the strings "arg1" and "arg2".
132040   **
132041   ** This method should return either SQLITE_OK (0), or an SQLite error 
132042   ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
132043   ** to point at the newly created tokenizer structure. The generic
132044   ** sqlite3_tokenizer.pModule variable should not be initialized by
132045   ** this callback. The caller will do so.
132046   */
132047   int (*xCreate)(
132048     int argc,                           /* Size of argv array */
132049     const char *const*argv,             /* Tokenizer argument strings */
132050     sqlite3_tokenizer **ppTokenizer     /* OUT: Created tokenizer */
132051   );
132052
132053   /*
132054   ** Destroy an existing tokenizer. The fts3 module calls this method
132055   ** exactly once for each successful call to xCreate().
132056   */
132057   int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
132058
132059   /*
132060   ** Create a tokenizer cursor to tokenize an input buffer. The caller
132061   ** is responsible for ensuring that the input buffer remains valid
132062   ** until the cursor is closed (using the xClose() method). 
132063   */
132064   int (*xOpen)(
132065     sqlite3_tokenizer *pTokenizer,       /* Tokenizer object */
132066     const char *pInput, int nBytes,      /* Input buffer */
132067     sqlite3_tokenizer_cursor **ppCursor  /* OUT: Created tokenizer cursor */
132068   );
132069
132070   /*
132071   ** Destroy an existing tokenizer cursor. The fts3 module calls this 
132072   ** method exactly once for each successful call to xOpen().
132073   */
132074   int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
132075
132076   /*
132077   ** Retrieve the next token from the tokenizer cursor pCursor. This
132078   ** method should either return SQLITE_OK and set the values of the
132079   ** "OUT" variables identified below, or SQLITE_DONE to indicate that
132080   ** the end of the buffer has been reached, or an SQLite error code.
132081   **
132082   ** *ppToken should be set to point at a buffer containing the 
132083   ** normalized version of the token (i.e. after any case-folding and/or
132084   ** stemming has been performed). *pnBytes should be set to the length
132085   ** of this buffer in bytes. The input text that generated the token is
132086   ** identified by the byte offsets returned in *piStartOffset and
132087   ** *piEndOffset. *piStartOffset should be set to the index of the first
132088   ** byte of the token in the input buffer. *piEndOffset should be set
132089   ** to the index of the first byte just past the end of the token in
132090   ** the input buffer.
132091   **
132092   ** The buffer *ppToken is set to point at is managed by the tokenizer
132093   ** implementation. It is only required to be valid until the next call
132094   ** to xNext() or xClose(). 
132095   */
132096   /* TODO(shess) current implementation requires pInput to be
132097   ** nul-terminated.  This should either be fixed, or pInput/nBytes
132098   ** should be converted to zInput.
132099   */
132100   int (*xNext)(
132101     sqlite3_tokenizer_cursor *pCursor,   /* Tokenizer cursor */
132102     const char **ppToken, int *pnBytes,  /* OUT: Normalized text for token */
132103     int *piStartOffset,  /* OUT: Byte offset of token in input buffer */
132104     int *piEndOffset,    /* OUT: Byte offset of end of token in input buffer */
132105     int *piPosition      /* OUT: Number of tokens returned before this one */
132106   );
132107
132108   /***********************************************************************
132109   ** Methods below this point are only available if iVersion>=1.
132110   */
132111
132112   /* 
132113   ** Configure the language id of a tokenizer cursor.
132114   */
132115   int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
132116 };
132117
132118 struct sqlite3_tokenizer {
132119   const sqlite3_tokenizer_module *pModule;  /* The module for this tokenizer */
132120   /* Tokenizer implementations will typically add additional fields */
132121 };
132122
132123 struct sqlite3_tokenizer_cursor {
132124   sqlite3_tokenizer *pTokenizer;       /* Tokenizer for this cursor. */
132125   /* Tokenizer implementations will typically add additional fields */
132126 };
132127
132128 int fts3_global_term_cnt(int iTerm, int iCol);
132129 int fts3_term_cnt(int iTerm, int iCol);
132130
132131
132132 #endif /* _FTS3_TOKENIZER_H_ */
132133
132134 /************** End of fts3_tokenizer.h **************************************/
132135 /************** Continuing where we left off in fts3Int.h ********************/
132136 /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
132137 /************** Begin file fts3_hash.h ***************************************/
132138 /*
132139 ** 2001 September 22
132140 **
132141 ** The author disclaims copyright to this source code.  In place of
132142 ** a legal notice, here is a blessing:
132143 **
132144 **    May you do good and not evil.
132145 **    May you find forgiveness for yourself and forgive others.
132146 **    May you share freely, never taking more than you give.
132147 **
132148 *************************************************************************
132149 ** This is the header file for the generic hash-table implementation
132150 ** used in SQLite.  We've modified it slightly to serve as a standalone
132151 ** hash table implementation for the full-text indexing module.
132152 **
132153 */
132154 #ifndef _FTS3_HASH_H_
132155 #define _FTS3_HASH_H_
132156
132157 /* Forward declarations of structures. */
132158 typedef struct Fts3Hash Fts3Hash;
132159 typedef struct Fts3HashElem Fts3HashElem;
132160
132161 /* A complete hash table is an instance of the following structure.
132162 ** The internals of this structure are intended to be opaque -- client
132163 ** code should not attempt to access or modify the fields of this structure
132164 ** directly.  Change this structure only by using the routines below.
132165 ** However, many of the "procedures" and "functions" for modifying and
132166 ** accessing this structure are really macros, so we can't really make
132167 ** this structure opaque.
132168 */
132169 struct Fts3Hash {
132170   char keyClass;          /* HASH_INT, _POINTER, _STRING, _BINARY */
132171   char copyKey;           /* True if copy of key made on insert */
132172   int count;              /* Number of entries in this table */
132173   Fts3HashElem *first;    /* The first element of the array */
132174   int htsize;             /* Number of buckets in the hash table */
132175   struct _fts3ht {        /* the hash table */
132176     int count;               /* Number of entries with this hash */
132177     Fts3HashElem *chain;     /* Pointer to first entry with this hash */
132178   } *ht;
132179 };
132180
132181 /* Each element in the hash table is an instance of the following 
132182 ** structure.  All elements are stored on a single doubly-linked list.
132183 **
132184 ** Again, this structure is intended to be opaque, but it can't really
132185 ** be opaque because it is used by macros.
132186 */
132187 struct Fts3HashElem {
132188   Fts3HashElem *next, *prev; /* Next and previous elements in the table */
132189   void *data;                /* Data associated with this element */
132190   void *pKey; int nKey;      /* Key associated with this element */
132191 };
132192
132193 /*
132194 ** There are 2 different modes of operation for a hash table:
132195 **
132196 **   FTS3_HASH_STRING        pKey points to a string that is nKey bytes long
132197 **                           (including the null-terminator, if any).  Case
132198 **                           is respected in comparisons.
132199 **
132200 **   FTS3_HASH_BINARY        pKey points to binary data nKey bytes long. 
132201 **                           memcmp() is used to compare keys.
132202 **
132203 ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.  
132204 */
132205 #define FTS3_HASH_STRING    1
132206 #define FTS3_HASH_BINARY    2
132207
132208 /*
132209 ** Access routines.  To delete, insert a NULL pointer.
132210 */
132211 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
132212 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
132213 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
132214 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
132215 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
132216
132217 /*
132218 ** Shorthand for the functions above
132219 */
132220 #define fts3HashInit     sqlite3Fts3HashInit
132221 #define fts3HashInsert   sqlite3Fts3HashInsert
132222 #define fts3HashFind     sqlite3Fts3HashFind
132223 #define fts3HashClear    sqlite3Fts3HashClear
132224 #define fts3HashFindElem sqlite3Fts3HashFindElem
132225
132226 /*
132227 ** Macros for looping over all elements of a hash table.  The idiom is
132228 ** like this:
132229 **
132230 **   Fts3Hash h;
132231 **   Fts3HashElem *p;
132232 **   ...
132233 **   for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
132234 **     SomeStructure *pData = fts3HashData(p);
132235 **     // do something with pData
132236 **   }
132237 */
132238 #define fts3HashFirst(H)  ((H)->first)
132239 #define fts3HashNext(E)   ((E)->next)
132240 #define fts3HashData(E)   ((E)->data)
132241 #define fts3HashKey(E)    ((E)->pKey)
132242 #define fts3HashKeysize(E) ((E)->nKey)
132243
132244 /*
132245 ** Number of entries in a hash table
132246 */
132247 #define fts3HashCount(H)  ((H)->count)
132248
132249 #endif /* _FTS3_HASH_H_ */
132250
132251 /************** End of fts3_hash.h *******************************************/
132252 /************** Continuing where we left off in fts3Int.h ********************/
132253
132254 /*
132255 ** This constant determines the maximum depth of an FTS expression tree
132256 ** that the library will create and use. FTS uses recursion to perform 
132257 ** various operations on the query tree, so the disadvantage of a large
132258 ** limit is that it may allow very large queries to use large amounts
132259 ** of stack space (perhaps causing a stack overflow).
132260 */
132261 #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
132262 # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
132263 #endif
132264
132265
132266 /*
132267 ** This constant controls how often segments are merged. Once there are
132268 ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
132269 ** segment of level N+1.
132270 */
132271 #define FTS3_MERGE_COUNT 16
132272
132273 /*
132274 ** This is the maximum amount of data (in bytes) to store in the 
132275 ** Fts3Table.pendingTerms hash table. Normally, the hash table is
132276 ** populated as documents are inserted/updated/deleted in a transaction
132277 ** and used to create a new segment when the transaction is committed.
132278 ** However if this limit is reached midway through a transaction, a new 
132279 ** segment is created and the hash table cleared immediately.
132280 */
132281 #define FTS3_MAX_PENDING_DATA (1*1024*1024)
132282
132283 /*
132284 ** Macro to return the number of elements in an array. SQLite has a
132285 ** similar macro called ArraySize(). Use a different name to avoid
132286 ** a collision when building an amalgamation with built-in FTS3.
132287 */
132288 #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
132289
132290
132291 #ifndef MIN
132292 # define MIN(x,y) ((x)<(y)?(x):(y))
132293 #endif
132294 #ifndef MAX
132295 # define MAX(x,y) ((x)>(y)?(x):(y))
132296 #endif
132297
132298 /*
132299 ** Maximum length of a varint encoded integer. The varint format is different
132300 ** from that used by SQLite, so the maximum length is 10, not 9.
132301 */
132302 #define FTS3_VARINT_MAX 10
132303
132304 /*
132305 ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
132306 ** in the document set and zero or more prefix indexes. All indexes are stored
132307 ** as one or more b+-trees in the %_segments and %_segdir tables. 
132308 **
132309 ** It is possible to determine which index a b+-tree belongs to based on the
132310 ** value stored in the "%_segdir.level" column. Given this value L, the index
132311 ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
132312 ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
132313 ** between 1024 and 2047 to index 1, and so on.
132314 **
132315 ** It is considered impossible for an index to use more than 1024 levels. In 
132316 ** theory though this may happen, but only after at least 
132317 ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
132318 */
132319 #define FTS3_SEGDIR_MAXLEVEL      1024
132320 #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
132321
132322 /*
132323 ** The testcase() macro is only used by the amalgamation.  If undefined,
132324 ** make it a no-op.
132325 */
132326 #ifndef testcase
132327 # define testcase(X)
132328 #endif
132329
132330 /*
132331 ** Terminator values for position-lists and column-lists.
132332 */
132333 #define POS_COLUMN  (1)     /* Column-list terminator */
132334 #define POS_END     (0)     /* Position-list terminator */ 
132335
132336 /*
132337 ** This section provides definitions to allow the
132338 ** FTS3 extension to be compiled outside of the 
132339 ** amalgamation.
132340 */
132341 #ifndef SQLITE_AMALGAMATION
132342 /*
132343 ** Macros indicating that conditional expressions are always true or
132344 ** false.
132345 */
132346 #ifdef SQLITE_COVERAGE_TEST
132347 # define ALWAYS(x) (1)
132348 # define NEVER(X)  (0)
132349 #else
132350 # define ALWAYS(x) (x)
132351 # define NEVER(x)  (x)
132352 #endif
132353
132354 /*
132355 ** Internal types used by SQLite.
132356 */
132357 typedef unsigned char u8;         /* 1-byte (or larger) unsigned integer */
132358 typedef short int i16;            /* 2-byte (or larger) signed integer */
132359 typedef unsigned int u32;         /* 4-byte unsigned integer */
132360 typedef sqlite3_uint64 u64;       /* 8-byte unsigned integer */
132361 typedef sqlite3_int64 i64;        /* 8-byte signed integer */
132362
132363 /*
132364 ** Macro used to suppress compiler warnings for unused parameters.
132365 */
132366 #define UNUSED_PARAMETER(x) (void)(x)
132367
132368 /*
132369 ** Activate assert() only if SQLITE_TEST is enabled.
132370 */
132371 #if !defined(NDEBUG) && !defined(SQLITE_DEBUG) 
132372 # define NDEBUG 1
132373 #endif
132374
132375 /*
132376 ** The TESTONLY macro is used to enclose variable declarations or
132377 ** other bits of code that are needed to support the arguments
132378 ** within testcase() and assert() macros.
132379 */
132380 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
132381 # define TESTONLY(X)  X
132382 #else
132383 # define TESTONLY(X)
132384 #endif
132385
132386 #endif /* SQLITE_AMALGAMATION */
132387
132388 #ifdef SQLITE_DEBUG
132389 SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
132390 # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
132391 #else
132392 # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
132393 #endif
132394
132395 typedef struct Fts3Table Fts3Table;
132396 typedef struct Fts3Cursor Fts3Cursor;
132397 typedef struct Fts3Expr Fts3Expr;
132398 typedef struct Fts3Phrase Fts3Phrase;
132399 typedef struct Fts3PhraseToken Fts3PhraseToken;
132400
132401 typedef struct Fts3Doclist Fts3Doclist;
132402 typedef struct Fts3SegFilter Fts3SegFilter;
132403 typedef struct Fts3DeferredToken Fts3DeferredToken;
132404 typedef struct Fts3SegReader Fts3SegReader;
132405 typedef struct Fts3MultiSegReader Fts3MultiSegReader;
132406
132407 /*
132408 ** A connection to a fulltext index is an instance of the following
132409 ** structure. The xCreate and xConnect methods create an instance
132410 ** of this structure and xDestroy and xDisconnect free that instance.
132411 ** All other methods receive a pointer to the structure as one of their
132412 ** arguments.
132413 */
132414 struct Fts3Table {
132415   sqlite3_vtab base;              /* Base class used by SQLite core */
132416   sqlite3 *db;                    /* The database connection */
132417   const char *zDb;                /* logical database name */
132418   const char *zName;              /* virtual table name */
132419   int nColumn;                    /* number of named columns in virtual table */
132420   char **azColumn;                /* column names.  malloced */
132421   u8 *abNotindexed;               /* True for 'notindexed' columns */
132422   sqlite3_tokenizer *pTokenizer;  /* tokenizer for inserts and queries */
132423   char *zContentTbl;              /* content=xxx option, or NULL */
132424   char *zLanguageid;              /* languageid=xxx option, or NULL */
132425   int nAutoincrmerge;             /* Value configured by 'automerge' */
132426   u32 nLeafAdd;                   /* Number of leaf blocks added this trans */
132427
132428   /* Precompiled statements used by the implementation. Each of these 
132429   ** statements is run and reset within a single virtual table API call. 
132430   */
132431   sqlite3_stmt *aStmt[40];
132432
132433   char *zReadExprlist;
132434   char *zWriteExprlist;
132435
132436   int nNodeSize;                  /* Soft limit for node size */
132437   u8 bFts4;                       /* True for FTS4, false for FTS3 */
132438   u8 bHasStat;                    /* True if %_stat table exists (2==unknown) */
132439   u8 bHasDocsize;                 /* True if %_docsize table exists */
132440   u8 bDescIdx;                    /* True if doclists are in reverse order */
132441   u8 bIgnoreSavepoint;            /* True to ignore xSavepoint invocations */
132442   int nPgsz;                      /* Page size for host database */
132443   char *zSegmentsTbl;             /* Name of %_segments table */
132444   sqlite3_blob *pSegments;        /* Blob handle open on %_segments table */
132445
132446   /* 
132447   ** The following array of hash tables is used to buffer pending index 
132448   ** updates during transactions. All pending updates buffered at any one
132449   ** time must share a common language-id (see the FTS4 langid= feature).
132450   ** The current language id is stored in variable iPrevLangid.
132451   **
132452   ** A single FTS4 table may have multiple full-text indexes. For each index
132453   ** there is an entry in the aIndex[] array. Index 0 is an index of all the
132454   ** terms that appear in the document set. Each subsequent index in aIndex[]
132455   ** is an index of prefixes of a specific length.
132456   **
132457   ** Variable nPendingData contains an estimate the memory consumed by the 
132458   ** pending data structures, including hash table overhead, but not including
132459   ** malloc overhead.  When nPendingData exceeds nMaxPendingData, all hash
132460   ** tables are flushed to disk. Variable iPrevDocid is the docid of the most 
132461   ** recently inserted record.
132462   */
132463   int nIndex;                     /* Size of aIndex[] */
132464   struct Fts3Index {
132465     int nPrefix;                  /* Prefix length (0 for main terms index) */
132466     Fts3Hash hPending;            /* Pending terms table for this index */
132467   } *aIndex;
132468   int nMaxPendingData;            /* Max pending data before flush to disk */
132469   int nPendingData;               /* Current bytes of pending data */
132470   sqlite_int64 iPrevDocid;        /* Docid of most recently inserted document */
132471   int iPrevLangid;                /* Langid of recently inserted document */
132472
132473 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
132474   /* State variables used for validating that the transaction control
132475   ** methods of the virtual table are called at appropriate times.  These
132476   ** values do not contribute to FTS functionality; they are used for
132477   ** verifying the operation of the SQLite core.
132478   */
132479   int inTransaction;     /* True after xBegin but before xCommit/xRollback */
132480   int mxSavepoint;       /* Largest valid xSavepoint integer */
132481 #endif
132482
132483 #ifdef SQLITE_TEST
132484   /* True to disable the incremental doclist optimization. This is controled
132485   ** by special insert command 'test-no-incr-doclist'.  */
132486   int bNoIncrDoclist;
132487 #endif
132488 };
132489
132490 /*
132491 ** When the core wants to read from the virtual table, it creates a
132492 ** virtual table cursor (an instance of the following structure) using
132493 ** the xOpen method. Cursors are destroyed using the xClose method.
132494 */
132495 struct Fts3Cursor {
132496   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
132497   i16 eSearch;                    /* Search strategy (see below) */
132498   u8 isEof;                       /* True if at End Of Results */
132499   u8 isRequireSeek;               /* True if must seek pStmt to %_content row */
132500   sqlite3_stmt *pStmt;            /* Prepared statement in use by the cursor */
132501   Fts3Expr *pExpr;                /* Parsed MATCH query string */
132502   int iLangid;                    /* Language being queried for */
132503   int nPhrase;                    /* Number of matchable phrases in query */
132504   Fts3DeferredToken *pDeferred;   /* Deferred search tokens, if any */
132505   sqlite3_int64 iPrevId;          /* Previous id read from aDoclist */
132506   char *pNextId;                  /* Pointer into the body of aDoclist */
132507   char *aDoclist;                 /* List of docids for full-text queries */
132508   int nDoclist;                   /* Size of buffer at aDoclist */
132509   u8 bDesc;                       /* True to sort in descending order */
132510   int eEvalmode;                  /* An FTS3_EVAL_XX constant */
132511   int nRowAvg;                    /* Average size of database rows, in pages */
132512   sqlite3_int64 nDoc;             /* Documents in table */
132513   i64 iMinDocid;                  /* Minimum docid to return */
132514   i64 iMaxDocid;                  /* Maximum docid to return */
132515   int isMatchinfoNeeded;          /* True when aMatchinfo[] needs filling in */
132516   u32 *aMatchinfo;                /* Information about most recent match */
132517   int nMatchinfo;                 /* Number of elements in aMatchinfo[] */
132518   char *zMatchinfo;               /* Matchinfo specification */
132519 };
132520
132521 #define FTS3_EVAL_FILTER    0
132522 #define FTS3_EVAL_NEXT      1
132523 #define FTS3_EVAL_MATCHINFO 2
132524
132525 /*
132526 ** The Fts3Cursor.eSearch member is always set to one of the following.
132527 ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
132528 ** FTS3_FULLTEXT_SEARCH.  If so, then Fts3Cursor.eSearch - 2 is the index
132529 ** of the column to be searched.  For example, in
132530 **
132531 **     CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
132532 **     SELECT docid FROM ex1 WHERE b MATCH 'one two three';
132533 ** 
132534 ** Because the LHS of the MATCH operator is 2nd column "b",
132535 ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1.  (+0 for a,
132536 ** +1 for b, +2 for c, +3 for d.)  If the LHS of MATCH were "ex1" 
132537 ** indicating that all columns should be searched,
132538 ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
132539 */
132540 #define FTS3_FULLSCAN_SEARCH 0    /* Linear scan of %_content table */
132541 #define FTS3_DOCID_SEARCH    1    /* Lookup by rowid on %_content table */
132542 #define FTS3_FULLTEXT_SEARCH 2    /* Full-text index search */
132543
132544 /*
132545 ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
132546 ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
132547 ** above. The upper 16-bits contain a combination of the following
132548 ** bits, used to describe extra constraints on full-text searches.
132549 */
132550 #define FTS3_HAVE_LANGID    0x00010000      /* languageid=? */
132551 #define FTS3_HAVE_DOCID_GE  0x00020000      /* docid>=? */
132552 #define FTS3_HAVE_DOCID_LE  0x00040000      /* docid<=? */
132553
132554 struct Fts3Doclist {
132555   char *aAll;                    /* Array containing doclist (or NULL) */
132556   int nAll;                      /* Size of a[] in bytes */
132557   char *pNextDocid;              /* Pointer to next docid */
132558
132559   sqlite3_int64 iDocid;          /* Current docid (if pList!=0) */
132560   int bFreeList;                 /* True if pList should be sqlite3_free()d */
132561   char *pList;                   /* Pointer to position list following iDocid */
132562   int nList;                     /* Length of position list */
132563 };
132564
132565 /*
132566 ** A "phrase" is a sequence of one or more tokens that must match in
132567 ** sequence.  A single token is the base case and the most common case.
132568 ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
132569 ** nToken will be the number of tokens in the string.
132570 */
132571 struct Fts3PhraseToken {
132572   char *z;                        /* Text of the token */
132573   int n;                          /* Number of bytes in buffer z */
132574   int isPrefix;                   /* True if token ends with a "*" character */
132575   int bFirst;                     /* True if token must appear at position 0 */
132576
132577   /* Variables above this point are populated when the expression is
132578   ** parsed (by code in fts3_expr.c). Below this point the variables are
132579   ** used when evaluating the expression. */
132580   Fts3DeferredToken *pDeferred;   /* Deferred token object for this token */
132581   Fts3MultiSegReader *pSegcsr;    /* Segment-reader for this token */
132582 };
132583
132584 struct Fts3Phrase {
132585   /* Cache of doclist for this phrase. */
132586   Fts3Doclist doclist;
132587   int bIncr;                 /* True if doclist is loaded incrementally */
132588   int iDoclistToken;
132589
132590   /* Used by sqlite3Fts3EvalPhrasePoslist() if this is a descendent of an
132591   ** OR condition.  */
132592   char *pOrPoslist;
132593   i64 iOrDocid;
132594
132595   /* Variables below this point are populated by fts3_expr.c when parsing 
132596   ** a MATCH expression. Everything above is part of the evaluation phase. 
132597   */
132598   int nToken;                /* Number of tokens in the phrase */
132599   int iColumn;               /* Index of column this phrase must match */
132600   Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
132601 };
132602
132603 /*
132604 ** A tree of these objects forms the RHS of a MATCH operator.
132605 **
132606 ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist 
132607 ** points to a malloced buffer, size nDoclist bytes, containing the results 
132608 ** of this phrase query in FTS3 doclist format. As usual, the initial 
132609 ** "Length" field found in doclists stored on disk is omitted from this 
132610 ** buffer.
132611 **
132612 ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
132613 ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
132614 ** where nCol is the number of columns in the queried FTS table. The array
132615 ** is populated as follows:
132616 **
132617 **   aMI[iCol*3 + 0] = Undefined
132618 **   aMI[iCol*3 + 1] = Number of occurrences
132619 **   aMI[iCol*3 + 2] = Number of rows containing at least one instance
132620 **
132621 ** The aMI array is allocated using sqlite3_malloc(). It should be freed 
132622 ** when the expression node is.
132623 */
132624 struct Fts3Expr {
132625   int eType;                 /* One of the FTSQUERY_XXX values defined below */
132626   int nNear;                 /* Valid if eType==FTSQUERY_NEAR */
132627   Fts3Expr *pParent;         /* pParent->pLeft==this or pParent->pRight==this */
132628   Fts3Expr *pLeft;           /* Left operand */
132629   Fts3Expr *pRight;          /* Right operand */
132630   Fts3Phrase *pPhrase;       /* Valid if eType==FTSQUERY_PHRASE */
132631
132632   /* The following are used by the fts3_eval.c module. */
132633   sqlite3_int64 iDocid;      /* Current docid */
132634   u8 bEof;                   /* True this expression is at EOF already */
132635   u8 bStart;                 /* True if iDocid is valid */
132636   u8 bDeferred;              /* True if this expression is entirely deferred */
132637
132638   u32 *aMI;
132639 };
132640
132641 /*
132642 ** Candidate values for Fts3Query.eType. Note that the order of the first
132643 ** four values is in order of precedence when parsing expressions. For 
132644 ** example, the following:
132645 **
132646 **   "a OR b AND c NOT d NEAR e"
132647 **
132648 ** is equivalent to:
132649 **
132650 **   "a OR (b AND (c NOT (d NEAR e)))"
132651 */
132652 #define FTSQUERY_NEAR   1
132653 #define FTSQUERY_NOT    2
132654 #define FTSQUERY_AND    3
132655 #define FTSQUERY_OR     4
132656 #define FTSQUERY_PHRASE 5
132657
132658
132659 /* fts3_write.c */
132660 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
132661 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
132662 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
132663 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
132664 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
132665   sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
132666 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
132667   Fts3Table*,int,const char*,int,int,Fts3SegReader**);
132668 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
132669 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
132670 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
132671
132672 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
132673 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
132674
132675 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
132676 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
132677 SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
132678 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
132679 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
132680 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
132681 #else
132682 # define sqlite3Fts3FreeDeferredTokens(x)
132683 # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
132684 # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
132685 # define sqlite3Fts3FreeDeferredDoclists(x)
132686 # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
132687 #endif
132688
132689 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
132690 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
132691
132692 /* Special values interpreted by sqlite3SegReaderCursor() */
132693 #define FTS3_SEGCURSOR_PENDING        -1
132694 #define FTS3_SEGCURSOR_ALL            -2
132695
132696 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
132697 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
132698 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
132699
132700 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *, 
132701     int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
132702
132703 /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
132704 #define FTS3_SEGMENT_REQUIRE_POS   0x00000001
132705 #define FTS3_SEGMENT_IGNORE_EMPTY  0x00000002
132706 #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
132707 #define FTS3_SEGMENT_PREFIX        0x00000008
132708 #define FTS3_SEGMENT_SCAN          0x00000010
132709 #define FTS3_SEGMENT_FIRST         0x00000020
132710
132711 /* Type passed as 4th argument to SegmentReaderIterate() */
132712 struct Fts3SegFilter {
132713   const char *zTerm;
132714   int nTerm;
132715   int iCol;
132716   int flags;
132717 };
132718
132719 struct Fts3MultiSegReader {
132720   /* Used internally by sqlite3Fts3SegReaderXXX() calls */
132721   Fts3SegReader **apSegment;      /* Array of Fts3SegReader objects */
132722   int nSegment;                   /* Size of apSegment array */
132723   int nAdvance;                   /* How many seg-readers to advance */
132724   Fts3SegFilter *pFilter;         /* Pointer to filter object */
132725   char *aBuffer;                  /* Buffer to merge doclists in */
132726   int nBuffer;                    /* Allocated size of aBuffer[] in bytes */
132727
132728   int iColFilter;                 /* If >=0, filter for this column */
132729   int bRestart;
132730
132731   /* Used by fts3.c only. */
132732   int nCost;                      /* Cost of running iterator */
132733   int bLookup;                    /* True if a lookup of a single entry. */
132734
132735   /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
132736   char *zTerm;                    /* Pointer to term buffer */
132737   int nTerm;                      /* Size of zTerm in bytes */
132738   char *aDoclist;                 /* Pointer to doclist buffer */
132739   int nDoclist;                   /* Size of aDoclist[] in bytes */
132740 };
132741
132742 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
132743
132744 #define fts3GetVarint32(p, piVal) (                                           \
132745   (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
132746 )
132747
132748 /* fts3.c */
132749 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
132750 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
132751 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
132752 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
132753 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
132754 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
132755 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
132756 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
132757 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
132758
132759 /* fts3_tokenizer.c */
132760 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
132761 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
132762 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *, 
132763     sqlite3_tokenizer **, char **
132764 );
132765 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
132766
132767 /* fts3_snippet.c */
132768 SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
132769 SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
132770   const char *, const char *, int, int
132771 );
132772 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
132773
132774 /* fts3_expr.c */
132775 SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
132776   char **, int, int, int, const char *, int, Fts3Expr **, char **
132777 );
132778 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
132779 #ifdef SQLITE_TEST
132780 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
132781 SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
132782 #endif
132783
132784 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
132785   sqlite3_tokenizer_cursor **
132786 );
132787
132788 /* fts3_aux.c */
132789 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
132790
132791 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
132792
132793 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
132794     Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
132795 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
132796     Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
132797 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **); 
132798 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
132799 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
132800
132801 /* fts3_tokenize_vtab.c */
132802 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
132803
132804 /* fts3_unicode2.c (functions generated by parsing unicode text files) */
132805 #ifndef SQLITE_DISABLE_FTS3_UNICODE
132806 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
132807 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
132808 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
132809 #endif
132810
132811 #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
132812 #endif /* _FTSINT_H */
132813
132814 /************** End of fts3Int.h *********************************************/
132815 /************** Continuing where we left off in fts3.c ***********************/
132816 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
132817
132818 #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
132819 # define SQLITE_CORE 1
132820 #endif
132821
132822 /* #include <assert.h> */
132823 /* #include <stdlib.h> */
132824 /* #include <stddef.h> */
132825 /* #include <stdio.h> */
132826 /* #include <string.h> */
132827 /* #include <stdarg.h> */
132828
132829 #ifndef SQLITE_CORE 
132830   SQLITE_EXTENSION_INIT1
132831 #endif
132832
132833 static int fts3EvalNext(Fts3Cursor *pCsr);
132834 static int fts3EvalStart(Fts3Cursor *pCsr);
132835 static int fts3TermSegReaderCursor(
132836     Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
132837
132838 /* 
132839 ** Write a 64-bit variable-length integer to memory starting at p[0].
132840 ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
132841 ** The number of bytes written is returned.
132842 */
132843 SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
132844   unsigned char *q = (unsigned char *) p;
132845   sqlite_uint64 vu = v;
132846   do{
132847     *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
132848     vu >>= 7;
132849   }while( vu!=0 );
132850   q[-1] &= 0x7f;  /* turn off high bit in final byte */
132851   assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
132852   return (int) (q - (unsigned char *)p);
132853 }
132854
132855 #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
132856   v = (v & mask1) | ( (*ptr++) << shift );                    \
132857   if( (v & mask2)==0 ){ var = v; return ret; }
132858 #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
132859   v = (*ptr++);                                               \
132860   if( (v & mask2)==0 ){ var = v; return ret; }
132861
132862 /* 
132863 ** Read a 64-bit variable-length integer from memory starting at p[0].
132864 ** Return the number of bytes read, or 0 on error.
132865 ** The value is stored in *v.
132866 */
132867 SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
132868   const char *pStart = p;
132869   u32 a;
132870   u64 b;
132871   int shift;
132872
132873   GETVARINT_INIT(a, p, 0,  0x00,     0x80, *v, 1);
132874   GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *v, 2);
132875   GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *v, 3);
132876   GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
132877   b = (a & 0x0FFFFFFF );
132878
132879   for(shift=28; shift<=63; shift+=7){
132880     u64 c = *p++;
132881     b += (c&0x7F) << shift;
132882     if( (c & 0x80)==0 ) break;
132883   }
132884   *v = b;
132885   return (int)(p - pStart);
132886 }
132887
132888 /*
132889 ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
132890 ** 32-bit integer before it is returned.
132891 */
132892 SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
132893   u32 a;
132894
132895 #ifndef fts3GetVarint32
132896   GETVARINT_INIT(a, p, 0,  0x00,     0x80, *pi, 1);
132897 #else
132898   a = (*p++);
132899   assert( a & 0x80 );
132900 #endif
132901
132902   GETVARINT_STEP(a, p, 7,  0x7F,     0x4000, *pi, 2);
132903   GETVARINT_STEP(a, p, 14, 0x3FFF,   0x200000, *pi, 3);
132904   GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
132905   a = (a & 0x0FFFFFFF );
132906   *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
132907   return 5;
132908 }
132909
132910 /*
132911 ** Return the number of bytes required to encode v as a varint
132912 */
132913 SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
132914   int i = 0;
132915   do{
132916     i++;
132917     v >>= 7;
132918   }while( v!=0 );
132919   return i;
132920 }
132921
132922 /*
132923 ** Convert an SQL-style quoted string into a normal string by removing
132924 ** the quote characters.  The conversion is done in-place.  If the
132925 ** input does not begin with a quote character, then this routine
132926 ** is a no-op.
132927 **
132928 ** Examples:
132929 **
132930 **     "abc"   becomes   abc
132931 **     'xyz'   becomes   xyz
132932 **     [pqr]   becomes   pqr
132933 **     `mno`   becomes   mno
132934 **
132935 */
132936 SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
132937   char quote;                     /* Quote character (if any ) */
132938
132939   quote = z[0];
132940   if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
132941     int iIn = 1;                  /* Index of next byte to read from input */
132942     int iOut = 0;                 /* Index of next byte to write to output */
132943
132944     /* If the first byte was a '[', then the close-quote character is a ']' */
132945     if( quote=='[' ) quote = ']';  
132946
132947     while( ALWAYS(z[iIn]) ){
132948       if( z[iIn]==quote ){
132949         if( z[iIn+1]!=quote ) break;
132950         z[iOut++] = quote;
132951         iIn += 2;
132952       }else{
132953         z[iOut++] = z[iIn++];
132954       }
132955     }
132956     z[iOut] = '\0';
132957   }
132958 }
132959
132960 /*
132961 ** Read a single varint from the doclist at *pp and advance *pp to point
132962 ** to the first byte past the end of the varint.  Add the value of the varint
132963 ** to *pVal.
132964 */
132965 static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
132966   sqlite3_int64 iVal;
132967   *pp += sqlite3Fts3GetVarint(*pp, &iVal);
132968   *pVal += iVal;
132969 }
132970
132971 /*
132972 ** When this function is called, *pp points to the first byte following a
132973 ** varint that is part of a doclist (or position-list, or any other list
132974 ** of varints). This function moves *pp to point to the start of that varint,
132975 ** and sets *pVal by the varint value.
132976 **
132977 ** Argument pStart points to the first byte of the doclist that the
132978 ** varint is part of.
132979 */
132980 static void fts3GetReverseVarint(
132981   char **pp, 
132982   char *pStart, 
132983   sqlite3_int64 *pVal
132984 ){
132985   sqlite3_int64 iVal;
132986   char *p;
132987
132988   /* Pointer p now points at the first byte past the varint we are 
132989   ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
132990   ** clear on character p[-1]. */
132991   for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
132992   p++;
132993   *pp = p;
132994
132995   sqlite3Fts3GetVarint(p, &iVal);
132996   *pVal = iVal;
132997 }
132998
132999 /*
133000 ** The xDisconnect() virtual table method.
133001 */
133002 static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
133003   Fts3Table *p = (Fts3Table *)pVtab;
133004   int i;
133005
133006   assert( p->nPendingData==0 );
133007   assert( p->pSegments==0 );
133008
133009   /* Free any prepared statements held */
133010   for(i=0; i<SizeofArray(p->aStmt); i++){
133011     sqlite3_finalize(p->aStmt[i]);
133012   }
133013   sqlite3_free(p->zSegmentsTbl);
133014   sqlite3_free(p->zReadExprlist);
133015   sqlite3_free(p->zWriteExprlist);
133016   sqlite3_free(p->zContentTbl);
133017   sqlite3_free(p->zLanguageid);
133018
133019   /* Invoke the tokenizer destructor to free the tokenizer. */
133020   p->pTokenizer->pModule->xDestroy(p->pTokenizer);
133021
133022   sqlite3_free(p);
133023   return SQLITE_OK;
133024 }
133025
133026 /*
133027 ** Construct one or more SQL statements from the format string given
133028 ** and then evaluate those statements. The success code is written
133029 ** into *pRc.
133030 **
133031 ** If *pRc is initially non-zero then this routine is a no-op.
133032 */
133033 static void fts3DbExec(
133034   int *pRc,              /* Success code */
133035   sqlite3 *db,           /* Database in which to run SQL */
133036   const char *zFormat,   /* Format string for SQL */
133037   ...                    /* Arguments to the format string */
133038 ){
133039   va_list ap;
133040   char *zSql;
133041   if( *pRc ) return;
133042   va_start(ap, zFormat);
133043   zSql = sqlite3_vmprintf(zFormat, ap);
133044   va_end(ap);
133045   if( zSql==0 ){
133046     *pRc = SQLITE_NOMEM;
133047   }else{
133048     *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
133049     sqlite3_free(zSql);
133050   }
133051 }
133052
133053 /*
133054 ** The xDestroy() virtual table method.
133055 */
133056 static int fts3DestroyMethod(sqlite3_vtab *pVtab){
133057   Fts3Table *p = (Fts3Table *)pVtab;
133058   int rc = SQLITE_OK;              /* Return code */
133059   const char *zDb = p->zDb;        /* Name of database (e.g. "main", "temp") */
133060   sqlite3 *db = p->db;             /* Database handle */
133061
133062   /* Drop the shadow tables */
133063   if( p->zContentTbl==0 ){
133064     fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
133065   }
133066   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
133067   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
133068   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
133069   fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
133070
133071   /* If everything has worked, invoke fts3DisconnectMethod() to free the
133072   ** memory associated with the Fts3Table structure and return SQLITE_OK.
133073   ** Otherwise, return an SQLite error code.
133074   */
133075   return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
133076 }
133077
133078
133079 /*
133080 ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
133081 ** passed as the first argument. This is done as part of the xConnect()
133082 ** and xCreate() methods.
133083 **
133084 ** If *pRc is non-zero when this function is called, it is a no-op. 
133085 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
133086 ** before returning.
133087 */
133088 static void fts3DeclareVtab(int *pRc, Fts3Table *p){
133089   if( *pRc==SQLITE_OK ){
133090     int i;                        /* Iterator variable */
133091     int rc;                       /* Return code */
133092     char *zSql;                   /* SQL statement passed to declare_vtab() */
133093     char *zCols;                  /* List of user defined columns */
133094     const char *zLanguageid;
133095
133096     zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
133097     sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
133098
133099     /* Create a list of user columns for the virtual table */
133100     zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
133101     for(i=1; zCols && i<p->nColumn; i++){
133102       zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
133103     }
133104
133105     /* Create the whole "CREATE TABLE" statement to pass to SQLite */
133106     zSql = sqlite3_mprintf(
133107         "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)", 
133108         zCols, p->zName, zLanguageid
133109     );
133110     if( !zCols || !zSql ){
133111       rc = SQLITE_NOMEM;
133112     }else{
133113       rc = sqlite3_declare_vtab(p->db, zSql);
133114     }
133115
133116     sqlite3_free(zSql);
133117     sqlite3_free(zCols);
133118     *pRc = rc;
133119   }
133120 }
133121
133122 /*
133123 ** Create the %_stat table if it does not already exist.
133124 */
133125 SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
133126   fts3DbExec(pRc, p->db, 
133127       "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
133128           "(id INTEGER PRIMARY KEY, value BLOB);",
133129       p->zDb, p->zName
133130   );
133131   if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
133132 }
133133
133134 /*
133135 ** Create the backing store tables (%_content, %_segments and %_segdir)
133136 ** required by the FTS3 table passed as the only argument. This is done
133137 ** as part of the vtab xCreate() method.
133138 **
133139 ** If the p->bHasDocsize boolean is true (indicating that this is an
133140 ** FTS4 table, not an FTS3 table) then also create the %_docsize and
133141 ** %_stat tables required by FTS4.
133142 */
133143 static int fts3CreateTables(Fts3Table *p){
133144   int rc = SQLITE_OK;             /* Return code */
133145   int i;                          /* Iterator variable */
133146   sqlite3 *db = p->db;            /* The database connection */
133147
133148   if( p->zContentTbl==0 ){
133149     const char *zLanguageid = p->zLanguageid;
133150     char *zContentCols;           /* Columns of %_content table */
133151
133152     /* Create a list of user columns for the content table */
133153     zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
133154     for(i=0; zContentCols && i<p->nColumn; i++){
133155       char *z = p->azColumn[i];
133156       zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
133157     }
133158     if( zLanguageid && zContentCols ){
133159       zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
133160     }
133161     if( zContentCols==0 ) rc = SQLITE_NOMEM;
133162   
133163     /* Create the content table */
133164     fts3DbExec(&rc, db, 
133165        "CREATE TABLE %Q.'%q_content'(%s)",
133166        p->zDb, p->zName, zContentCols
133167     );
133168     sqlite3_free(zContentCols);
133169   }
133170
133171   /* Create other tables */
133172   fts3DbExec(&rc, db, 
133173       "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
133174       p->zDb, p->zName
133175   );
133176   fts3DbExec(&rc, db, 
133177       "CREATE TABLE %Q.'%q_segdir'("
133178         "level INTEGER,"
133179         "idx INTEGER,"
133180         "start_block INTEGER,"
133181         "leaves_end_block INTEGER,"
133182         "end_block INTEGER,"
133183         "root BLOB,"
133184         "PRIMARY KEY(level, idx)"
133185       ");",
133186       p->zDb, p->zName
133187   );
133188   if( p->bHasDocsize ){
133189     fts3DbExec(&rc, db, 
133190         "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
133191         p->zDb, p->zName
133192     );
133193   }
133194   assert( p->bHasStat==p->bFts4 );
133195   if( p->bHasStat ){
133196     sqlite3Fts3CreateStatTable(&rc, p);
133197   }
133198   return rc;
133199 }
133200
133201 /*
133202 ** Store the current database page-size in bytes in p->nPgsz.
133203 **
133204 ** If *pRc is non-zero when this function is called, it is a no-op. 
133205 ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
133206 ** before returning.
133207 */
133208 static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
133209   if( *pRc==SQLITE_OK ){
133210     int rc;                       /* Return code */
133211     char *zSql;                   /* SQL text "PRAGMA %Q.page_size" */
133212     sqlite3_stmt *pStmt;          /* Compiled "PRAGMA %Q.page_size" statement */
133213   
133214     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
133215     if( !zSql ){
133216       rc = SQLITE_NOMEM;
133217     }else{
133218       rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
133219       if( rc==SQLITE_OK ){
133220         sqlite3_step(pStmt);
133221         p->nPgsz = sqlite3_column_int(pStmt, 0);
133222         rc = sqlite3_finalize(pStmt);
133223       }else if( rc==SQLITE_AUTH ){
133224         p->nPgsz = 1024;
133225         rc = SQLITE_OK;
133226       }
133227     }
133228     assert( p->nPgsz>0 || rc!=SQLITE_OK );
133229     sqlite3_free(zSql);
133230     *pRc = rc;
133231   }
133232 }
133233
133234 /*
133235 ** "Special" FTS4 arguments are column specifications of the following form:
133236 **
133237 **   <key> = <value>
133238 **
133239 ** There may not be whitespace surrounding the "=" character. The <value> 
133240 ** term may be quoted, but the <key> may not.
133241 */
133242 static int fts3IsSpecialColumn(
133243   const char *z, 
133244   int *pnKey,
133245   char **pzValue
133246 ){
133247   char *zValue;
133248   const char *zCsr = z;
133249
133250   while( *zCsr!='=' ){
133251     if( *zCsr=='\0' ) return 0;
133252     zCsr++;
133253   }
133254
133255   *pnKey = (int)(zCsr-z);
133256   zValue = sqlite3_mprintf("%s", &zCsr[1]);
133257   if( zValue ){
133258     sqlite3Fts3Dequote(zValue);
133259   }
133260   *pzValue = zValue;
133261   return 1;
133262 }
133263
133264 /*
133265 ** Append the output of a printf() style formatting to an existing string.
133266 */
133267 static void fts3Appendf(
133268   int *pRc,                       /* IN/OUT: Error code */
133269   char **pz,                      /* IN/OUT: Pointer to string buffer */
133270   const char *zFormat,            /* Printf format string to append */
133271   ...                             /* Arguments for printf format string */
133272 ){
133273   if( *pRc==SQLITE_OK ){
133274     va_list ap;
133275     char *z;
133276     va_start(ap, zFormat);
133277     z = sqlite3_vmprintf(zFormat, ap);
133278     va_end(ap);
133279     if( z && *pz ){
133280       char *z2 = sqlite3_mprintf("%s%s", *pz, z);
133281       sqlite3_free(z);
133282       z = z2;
133283     }
133284     if( z==0 ) *pRc = SQLITE_NOMEM;
133285     sqlite3_free(*pz);
133286     *pz = z;
133287   }
133288 }
133289
133290 /*
133291 ** Return a copy of input string zInput enclosed in double-quotes (") and
133292 ** with all double quote characters escaped. For example:
133293 **
133294 **     fts3QuoteId("un \"zip\"")   ->    "un \"\"zip\"\""
133295 **
133296 ** The pointer returned points to memory obtained from sqlite3_malloc(). It
133297 ** is the callers responsibility to call sqlite3_free() to release this
133298 ** memory.
133299 */
133300 static char *fts3QuoteId(char const *zInput){
133301   int nRet;
133302   char *zRet;
133303   nRet = 2 + (int)strlen(zInput)*2 + 1;
133304   zRet = sqlite3_malloc(nRet);
133305   if( zRet ){
133306     int i;
133307     char *z = zRet;
133308     *(z++) = '"';
133309     for(i=0; zInput[i]; i++){
133310       if( zInput[i]=='"' ) *(z++) = '"';
133311       *(z++) = zInput[i];
133312     }
133313     *(z++) = '"';
133314     *(z++) = '\0';
133315   }
133316   return zRet;
133317 }
133318
133319 /*
133320 ** Return a list of comma separated SQL expressions and a FROM clause that 
133321 ** could be used in a SELECT statement such as the following:
133322 **
133323 **     SELECT <list of expressions> FROM %_content AS x ...
133324 **
133325 ** to return the docid, followed by each column of text data in order
133326 ** from left to write. If parameter zFunc is not NULL, then instead of
133327 ** being returned directly each column of text data is passed to an SQL
133328 ** function named zFunc first. For example, if zFunc is "unzip" and the
133329 ** table has the three user-defined columns "a", "b", and "c", the following
133330 ** string is returned:
133331 **
133332 **     "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
133333 **
133334 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
133335 ** is the responsibility of the caller to eventually free it.
133336 **
133337 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
133338 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
133339 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
133340 ** no error occurs, *pRc is left unmodified.
133341 */
133342 static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
133343   char *zRet = 0;
133344   char *zFree = 0;
133345   char *zFunction;
133346   int i;
133347
133348   if( p->zContentTbl==0 ){
133349     if( !zFunc ){
133350       zFunction = "";
133351     }else{
133352       zFree = zFunction = fts3QuoteId(zFunc);
133353     }
133354     fts3Appendf(pRc, &zRet, "docid");
133355     for(i=0; i<p->nColumn; i++){
133356       fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
133357     }
133358     if( p->zLanguageid ){
133359       fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
133360     }
133361     sqlite3_free(zFree);
133362   }else{
133363     fts3Appendf(pRc, &zRet, "rowid");
133364     for(i=0; i<p->nColumn; i++){
133365       fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
133366     }
133367     if( p->zLanguageid ){
133368       fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
133369     }
133370   }
133371   fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x", 
133372       p->zDb,
133373       (p->zContentTbl ? p->zContentTbl : p->zName),
133374       (p->zContentTbl ? "" : "_content")
133375   );
133376   return zRet;
133377 }
133378
133379 /*
133380 ** Return a list of N comma separated question marks, where N is the number
133381 ** of columns in the %_content table (one for the docid plus one for each
133382 ** user-defined text column).
133383 **
133384 ** If argument zFunc is not NULL, then all but the first question mark
133385 ** is preceded by zFunc and an open bracket, and followed by a closed
133386 ** bracket. For example, if zFunc is "zip" and the FTS3 table has three 
133387 ** user-defined text columns, the following string is returned:
133388 **
133389 **     "?, zip(?), zip(?), zip(?)"
133390 **
133391 ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
133392 ** is the responsibility of the caller to eventually free it.
133393 **
133394 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
133395 ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
133396 ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
133397 ** no error occurs, *pRc is left unmodified.
133398 */
133399 static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
133400   char *zRet = 0;
133401   char *zFree = 0;
133402   char *zFunction;
133403   int i;
133404
133405   if( !zFunc ){
133406     zFunction = "";
133407   }else{
133408     zFree = zFunction = fts3QuoteId(zFunc);
133409   }
133410   fts3Appendf(pRc, &zRet, "?");
133411   for(i=0; i<p->nColumn; i++){
133412     fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
133413   }
133414   if( p->zLanguageid ){
133415     fts3Appendf(pRc, &zRet, ", ?");
133416   }
133417   sqlite3_free(zFree);
133418   return zRet;
133419 }
133420
133421 /*
133422 ** This function interprets the string at (*pp) as a non-negative integer
133423 ** value. It reads the integer and sets *pnOut to the value read, then 
133424 ** sets *pp to point to the byte immediately following the last byte of
133425 ** the integer value.
133426 **
133427 ** Only decimal digits ('0'..'9') may be part of an integer value. 
133428 **
133429 ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
133430 ** the output value undefined. Otherwise SQLITE_OK is returned.
133431 **
133432 ** This function is used when parsing the "prefix=" FTS4 parameter.
133433 */
133434 static int fts3GobbleInt(const char **pp, int *pnOut){
133435   const int MAX_NPREFIX = 10000000;
133436   const char *p;                  /* Iterator pointer */
133437   int nInt = 0;                   /* Output value */
133438
133439   for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
133440     nInt = nInt * 10 + (p[0] - '0');
133441     if( nInt>MAX_NPREFIX ){
133442       nInt = 0;
133443       break;
133444     }
133445   }
133446   if( p==*pp ) return SQLITE_ERROR;
133447   *pnOut = nInt;
133448   *pp = p;
133449   return SQLITE_OK;
133450 }
133451
133452 /*
133453 ** This function is called to allocate an array of Fts3Index structures
133454 ** representing the indexes maintained by the current FTS table. FTS tables
133455 ** always maintain the main "terms" index, but may also maintain one or
133456 ** more "prefix" indexes, depending on the value of the "prefix=" parameter
133457 ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
133458 **
133459 ** Argument zParam is passed the value of the "prefix=" option if one was
133460 ** specified, or NULL otherwise.
133461 **
133462 ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
133463 ** the allocated array. *pnIndex is set to the number of elements in the
133464 ** array. If an error does occur, an SQLite error code is returned.
133465 **
133466 ** Regardless of whether or not an error is returned, it is the responsibility
133467 ** of the caller to call sqlite3_free() on the output array to free it.
133468 */
133469 static int fts3PrefixParameter(
133470   const char *zParam,             /* ABC in prefix=ABC parameter to parse */
133471   int *pnIndex,                   /* OUT: size of *apIndex[] array */
133472   struct Fts3Index **apIndex      /* OUT: Array of indexes for this table */
133473 ){
133474   struct Fts3Index *aIndex;       /* Allocated array */
133475   int nIndex = 1;                 /* Number of entries in array */
133476
133477   if( zParam && zParam[0] ){
133478     const char *p;
133479     nIndex++;
133480     for(p=zParam; *p; p++){
133481       if( *p==',' ) nIndex++;
133482     }
133483   }
133484
133485   aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
133486   *apIndex = aIndex;
133487   if( !aIndex ){
133488     return SQLITE_NOMEM;
133489   }
133490
133491   memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
133492   if( zParam ){
133493     const char *p = zParam;
133494     int i;
133495     for(i=1; i<nIndex; i++){
133496       int nPrefix = 0;
133497       if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
133498       assert( nPrefix>=0 );
133499       if( nPrefix==0 ){
133500         nIndex--;
133501         i--;
133502       }else{
133503         aIndex[i].nPrefix = nPrefix;
133504       }
133505       p++;
133506     }
133507   }
133508
133509   *pnIndex = nIndex;
133510   return SQLITE_OK;
133511 }
133512
133513 /*
133514 ** This function is called when initializing an FTS4 table that uses the
133515 ** content=xxx option. It determines the number of and names of the columns
133516 ** of the new FTS4 table.
133517 **
133518 ** The third argument passed to this function is the value passed to the
133519 ** config=xxx option (i.e. "xxx"). This function queries the database for
133520 ** a table of that name. If found, the output variables are populated
133521 ** as follows:
133522 **
133523 **   *pnCol:   Set to the number of columns table xxx has,
133524 **
133525 **   *pnStr:   Set to the total amount of space required to store a copy
133526 **             of each columns name, including the nul-terminator.
133527 **
133528 **   *pazCol:  Set to point to an array of *pnCol strings. Each string is
133529 **             the name of the corresponding column in table xxx. The array
133530 **             and its contents are allocated using a single allocation. It
133531 **             is the responsibility of the caller to free this allocation
133532 **             by eventually passing the *pazCol value to sqlite3_free().
133533 **
133534 ** If the table cannot be found, an error code is returned and the output
133535 ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
133536 ** returned (and the output variables are undefined).
133537 */
133538 static int fts3ContentColumns(
133539   sqlite3 *db,                    /* Database handle */
133540   const char *zDb,                /* Name of db (i.e. "main", "temp" etc.) */
133541   const char *zTbl,               /* Name of content table */
133542   const char ***pazCol,           /* OUT: Malloc'd array of column names */
133543   int *pnCol,                     /* OUT: Size of array *pazCol */
133544   int *pnStr                      /* OUT: Bytes of string content */
133545 ){
133546   int rc = SQLITE_OK;             /* Return code */
133547   char *zSql;                     /* "SELECT *" statement on zTbl */  
133548   sqlite3_stmt *pStmt = 0;        /* Compiled version of zSql */
133549
133550   zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
133551   if( !zSql ){
133552     rc = SQLITE_NOMEM;
133553   }else{
133554     rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
133555   }
133556   sqlite3_free(zSql);
133557
133558   if( rc==SQLITE_OK ){
133559     const char **azCol;           /* Output array */
133560     int nStr = 0;                 /* Size of all column names (incl. 0x00) */
133561     int nCol;                     /* Number of table columns */
133562     int i;                        /* Used to iterate through columns */
133563
133564     /* Loop through the returned columns. Set nStr to the number of bytes of
133565     ** space required to store a copy of each column name, including the
133566     ** nul-terminator byte.  */
133567     nCol = sqlite3_column_count(pStmt);
133568     for(i=0; i<nCol; i++){
133569       const char *zCol = sqlite3_column_name(pStmt, i);
133570       nStr += (int)strlen(zCol) + 1;
133571     }
133572
133573     /* Allocate and populate the array to return. */
133574     azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
133575     if( azCol==0 ){
133576       rc = SQLITE_NOMEM;
133577     }else{
133578       char *p = (char *)&azCol[nCol];
133579       for(i=0; i<nCol; i++){
133580         const char *zCol = sqlite3_column_name(pStmt, i);
133581         int n = (int)strlen(zCol)+1;
133582         memcpy(p, zCol, n);
133583         azCol[i] = p;
133584         p += n;
133585       }
133586     }
133587     sqlite3_finalize(pStmt);
133588
133589     /* Set the output variables. */
133590     *pnCol = nCol;
133591     *pnStr = nStr;
133592     *pazCol = azCol;
133593   }
133594
133595   return rc;
133596 }
133597
133598 /*
133599 ** This function is the implementation of both the xConnect and xCreate
133600 ** methods of the FTS3 virtual table.
133601 **
133602 ** The argv[] array contains the following:
133603 **
133604 **   argv[0]   -> module name  ("fts3" or "fts4")
133605 **   argv[1]   -> database name
133606 **   argv[2]   -> table name
133607 **   argv[...] -> "column name" and other module argument fields.
133608 */
133609 static int fts3InitVtab(
133610   int isCreate,                   /* True for xCreate, false for xConnect */
133611   sqlite3 *db,                    /* The SQLite database connection */
133612   void *pAux,                     /* Hash table containing tokenizers */
133613   int argc,                       /* Number of elements in argv array */
133614   const char * const *argv,       /* xCreate/xConnect argument array */
133615   sqlite3_vtab **ppVTab,          /* Write the resulting vtab structure here */
133616   char **pzErr                    /* Write any error message here */
133617 ){
133618   Fts3Hash *pHash = (Fts3Hash *)pAux;
133619   Fts3Table *p = 0;               /* Pointer to allocated vtab */
133620   int rc = SQLITE_OK;             /* Return code */
133621   int i;                          /* Iterator variable */
133622   int nByte;                      /* Size of allocation used for *p */
133623   int iCol;                       /* Column index */
133624   int nString = 0;                /* Bytes required to hold all column names */
133625   int nCol = 0;                   /* Number of columns in the FTS table */
133626   char *zCsr;                     /* Space for holding column names */
133627   int nDb;                        /* Bytes required to hold database name */
133628   int nName;                      /* Bytes required to hold table name */
133629   int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
133630   const char **aCol;              /* Array of column names */
133631   sqlite3_tokenizer *pTokenizer = 0;        /* Tokenizer for this table */
133632
133633   int nIndex = 0;                 /* Size of aIndex[] array */
133634   struct Fts3Index *aIndex = 0;   /* Array of indexes for this table */
133635
133636   /* The results of parsing supported FTS4 key=value options: */
133637   int bNoDocsize = 0;             /* True to omit %_docsize table */
133638   int bDescIdx = 0;               /* True to store descending indexes */
133639   char *zPrefix = 0;              /* Prefix parameter value (or NULL) */
133640   char *zCompress = 0;            /* compress=? parameter (or NULL) */
133641   char *zUncompress = 0;          /* uncompress=? parameter (or NULL) */
133642   char *zContent = 0;             /* content=? parameter (or NULL) */
133643   char *zLanguageid = 0;          /* languageid=? parameter (or NULL) */
133644   char **azNotindexed = 0;        /* The set of notindexed= columns */
133645   int nNotindexed = 0;            /* Size of azNotindexed[] array */
133646
133647   assert( strlen(argv[0])==4 );
133648   assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
133649        || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
133650   );
133651
133652   nDb = (int)strlen(argv[1]) + 1;
133653   nName = (int)strlen(argv[2]) + 1;
133654
133655   nByte = sizeof(const char *) * (argc-2);
133656   aCol = (const char **)sqlite3_malloc(nByte);
133657   if( aCol ){
133658     memset((void*)aCol, 0, nByte);
133659     azNotindexed = (char **)sqlite3_malloc(nByte);
133660   }
133661   if( azNotindexed ){
133662     memset(azNotindexed, 0, nByte);
133663   }
133664   if( !aCol || !azNotindexed ){
133665     rc = SQLITE_NOMEM;
133666     goto fts3_init_out;
133667   }
133668
133669   /* Loop through all of the arguments passed by the user to the FTS3/4
133670   ** module (i.e. all the column names and special arguments). This loop
133671   ** does the following:
133672   **
133673   **   + Figures out the number of columns the FTSX table will have, and
133674   **     the number of bytes of space that must be allocated to store copies
133675   **     of the column names.
133676   **
133677   **   + If there is a tokenizer specification included in the arguments,
133678   **     initializes the tokenizer pTokenizer.
133679   */
133680   for(i=3; rc==SQLITE_OK && i<argc; i++){
133681     char const *z = argv[i];
133682     int nKey;
133683     char *zVal;
133684
133685     /* Check if this is a tokenizer specification */
133686     if( !pTokenizer 
133687      && strlen(z)>8
133688      && 0==sqlite3_strnicmp(z, "tokenize", 8) 
133689      && 0==sqlite3Fts3IsIdChar(z[8])
133690     ){
133691       rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
133692     }
133693
133694     /* Check if it is an FTS4 special argument. */
133695     else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
133696       struct Fts4Option {
133697         const char *zOpt;
133698         int nOpt;
133699       } aFts4Opt[] = {
133700         { "matchinfo",   9 },     /* 0 -> MATCHINFO */
133701         { "prefix",      6 },     /* 1 -> PREFIX */
133702         { "compress",    8 },     /* 2 -> COMPRESS */
133703         { "uncompress", 10 },     /* 3 -> UNCOMPRESS */
133704         { "order",       5 },     /* 4 -> ORDER */
133705         { "content",     7 },     /* 5 -> CONTENT */
133706         { "languageid", 10 },     /* 6 -> LANGUAGEID */
133707         { "notindexed", 10 }      /* 7 -> NOTINDEXED */
133708       };
133709
133710       int iOpt;
133711       if( !zVal ){
133712         rc = SQLITE_NOMEM;
133713       }else{
133714         for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
133715           struct Fts4Option *pOp = &aFts4Opt[iOpt];
133716           if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
133717             break;
133718           }
133719         }
133720         if( iOpt==SizeofArray(aFts4Opt) ){
133721           *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
133722           rc = SQLITE_ERROR;
133723         }else{
133724           switch( iOpt ){
133725             case 0:               /* MATCHINFO */
133726               if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
133727                 *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
133728                 rc = SQLITE_ERROR;
133729               }
133730               bNoDocsize = 1;
133731               break;
133732
133733             case 1:               /* PREFIX */
133734               sqlite3_free(zPrefix);
133735               zPrefix = zVal;
133736               zVal = 0;
133737               break;
133738
133739             case 2:               /* COMPRESS */
133740               sqlite3_free(zCompress);
133741               zCompress = zVal;
133742               zVal = 0;
133743               break;
133744
133745             case 3:               /* UNCOMPRESS */
133746               sqlite3_free(zUncompress);
133747               zUncompress = zVal;
133748               zVal = 0;
133749               break;
133750
133751             case 4:               /* ORDER */
133752               if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3)) 
133753                && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4)) 
133754               ){
133755                 *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
133756                 rc = SQLITE_ERROR;
133757               }
133758               bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
133759               break;
133760
133761             case 5:              /* CONTENT */
133762               sqlite3_free(zContent);
133763               zContent = zVal;
133764               zVal = 0;
133765               break;
133766
133767             case 6:              /* LANGUAGEID */
133768               assert( iOpt==6 );
133769               sqlite3_free(zLanguageid);
133770               zLanguageid = zVal;
133771               zVal = 0;
133772               break;
133773
133774             case 7:              /* NOTINDEXED */
133775               azNotindexed[nNotindexed++] = zVal;
133776               zVal = 0;
133777               break;
133778           }
133779         }
133780         sqlite3_free(zVal);
133781       }
133782     }
133783
133784     /* Otherwise, the argument is a column name. */
133785     else {
133786       nString += (int)(strlen(z) + 1);
133787       aCol[nCol++] = z;
133788     }
133789   }
133790
133791   /* If a content=xxx option was specified, the following:
133792   **
133793   **   1. Ignore any compress= and uncompress= options.
133794   **
133795   **   2. If no column names were specified as part of the CREATE VIRTUAL
133796   **      TABLE statement, use all columns from the content table.
133797   */
133798   if( rc==SQLITE_OK && zContent ){
133799     sqlite3_free(zCompress); 
133800     sqlite3_free(zUncompress); 
133801     zCompress = 0;
133802     zUncompress = 0;
133803     if( nCol==0 ){
133804       sqlite3_free((void*)aCol); 
133805       aCol = 0;
133806       rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
133807
133808       /* If a languageid= option was specified, remove the language id
133809       ** column from the aCol[] array. */ 
133810       if( rc==SQLITE_OK && zLanguageid ){
133811         int j;
133812         for(j=0; j<nCol; j++){
133813           if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
133814             int k;
133815             for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
133816             nCol--;
133817             break;
133818           }
133819         }
133820       }
133821     }
133822   }
133823   if( rc!=SQLITE_OK ) goto fts3_init_out;
133824
133825   if( nCol==0 ){
133826     assert( nString==0 );
133827     aCol[0] = "content";
133828     nString = 8;
133829     nCol = 1;
133830   }
133831
133832   if( pTokenizer==0 ){
133833     rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
133834     if( rc!=SQLITE_OK ) goto fts3_init_out;
133835   }
133836   assert( pTokenizer );
133837
133838   rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
133839   if( rc==SQLITE_ERROR ){
133840     assert( zPrefix );
133841     *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
133842   }
133843   if( rc!=SQLITE_OK ) goto fts3_init_out;
133844
133845   /* Allocate and populate the Fts3Table structure. */
133846   nByte = sizeof(Fts3Table) +                  /* Fts3Table */
133847           nCol * sizeof(char *) +              /* azColumn */
133848           nIndex * sizeof(struct Fts3Index) +  /* aIndex */
133849           nCol * sizeof(u8) +                  /* abNotindexed */
133850           nName +                              /* zName */
133851           nDb +                                /* zDb */
133852           nString;                             /* Space for azColumn strings */
133853   p = (Fts3Table*)sqlite3_malloc(nByte);
133854   if( p==0 ){
133855     rc = SQLITE_NOMEM;
133856     goto fts3_init_out;
133857   }
133858   memset(p, 0, nByte);
133859   p->db = db;
133860   p->nColumn = nCol;
133861   p->nPendingData = 0;
133862   p->azColumn = (char **)&p[1];
133863   p->pTokenizer = pTokenizer;
133864   p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
133865   p->bHasDocsize = (isFts4 && bNoDocsize==0);
133866   p->bHasStat = isFts4;
133867   p->bFts4 = isFts4;
133868   p->bDescIdx = bDescIdx;
133869   p->nAutoincrmerge = 0xff;   /* 0xff means setting unknown */
133870   p->zContentTbl = zContent;
133871   p->zLanguageid = zLanguageid;
133872   zContent = 0;
133873   zLanguageid = 0;
133874   TESTONLY( p->inTransaction = -1 );
133875   TESTONLY( p->mxSavepoint = -1 );
133876
133877   p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
133878   memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
133879   p->nIndex = nIndex;
133880   for(i=0; i<nIndex; i++){
133881     fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
133882   }
133883   p->abNotindexed = (u8 *)&p->aIndex[nIndex];
133884
133885   /* Fill in the zName and zDb fields of the vtab structure. */
133886   zCsr = (char *)&p->abNotindexed[nCol];
133887   p->zName = zCsr;
133888   memcpy(zCsr, argv[2], nName);
133889   zCsr += nName;
133890   p->zDb = zCsr;
133891   memcpy(zCsr, argv[1], nDb);
133892   zCsr += nDb;
133893
133894   /* Fill in the azColumn array */
133895   for(iCol=0; iCol<nCol; iCol++){
133896     char *z; 
133897     int n = 0;
133898     z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
133899     memcpy(zCsr, z, n);
133900     zCsr[n] = '\0';
133901     sqlite3Fts3Dequote(zCsr);
133902     p->azColumn[iCol] = zCsr;
133903     zCsr += n+1;
133904     assert( zCsr <= &((char *)p)[nByte] );
133905   }
133906
133907   /* Fill in the abNotindexed array */
133908   for(iCol=0; iCol<nCol; iCol++){
133909     int n = (int)strlen(p->azColumn[iCol]);
133910     for(i=0; i<nNotindexed; i++){
133911       char *zNot = azNotindexed[i];
133912       if( zNot && n==(int)strlen(zNot)
133913        && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n) 
133914       ){
133915         p->abNotindexed[iCol] = 1;
133916         sqlite3_free(zNot);
133917         azNotindexed[i] = 0;
133918       }
133919     }
133920   }
133921   for(i=0; i<nNotindexed; i++){
133922     if( azNotindexed[i] ){
133923       *pzErr = sqlite3_mprintf("no such column: %s", azNotindexed[i]);
133924       rc = SQLITE_ERROR;
133925     }
133926   }
133927
133928   if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
133929     char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
133930     rc = SQLITE_ERROR;
133931     *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
133932   }
133933   p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
133934   p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
133935   if( rc!=SQLITE_OK ) goto fts3_init_out;
133936
133937   /* If this is an xCreate call, create the underlying tables in the 
133938   ** database. TODO: For xConnect(), it could verify that said tables exist.
133939   */
133940   if( isCreate ){
133941     rc = fts3CreateTables(p);
133942   }
133943
133944   /* Check to see if a legacy fts3 table has been "upgraded" by the
133945   ** addition of a %_stat table so that it can use incremental merge.
133946   */
133947   if( !isFts4 && !isCreate ){
133948     p->bHasStat = 2;
133949   }
133950
133951   /* Figure out the page-size for the database. This is required in order to
133952   ** estimate the cost of loading large doclists from the database.  */
133953   fts3DatabasePageSize(&rc, p);
133954   p->nNodeSize = p->nPgsz-35;
133955
133956   /* Declare the table schema to SQLite. */
133957   fts3DeclareVtab(&rc, p);
133958
133959 fts3_init_out:
133960   sqlite3_free(zPrefix);
133961   sqlite3_free(aIndex);
133962   sqlite3_free(zCompress);
133963   sqlite3_free(zUncompress);
133964   sqlite3_free(zContent);
133965   sqlite3_free(zLanguageid);
133966   for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
133967   sqlite3_free((void *)aCol);
133968   sqlite3_free((void *)azNotindexed);
133969   if( rc!=SQLITE_OK ){
133970     if( p ){
133971       fts3DisconnectMethod((sqlite3_vtab *)p);
133972     }else if( pTokenizer ){
133973       pTokenizer->pModule->xDestroy(pTokenizer);
133974     }
133975   }else{
133976     assert( p->pSegments==0 );
133977     *ppVTab = &p->base;
133978   }
133979   return rc;
133980 }
133981
133982 /*
133983 ** The xConnect() and xCreate() methods for the virtual table. All the
133984 ** work is done in function fts3InitVtab().
133985 */
133986 static int fts3ConnectMethod(
133987   sqlite3 *db,                    /* Database connection */
133988   void *pAux,                     /* Pointer to tokenizer hash table */
133989   int argc,                       /* Number of elements in argv array */
133990   const char * const *argv,       /* xCreate/xConnect argument array */
133991   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
133992   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
133993 ){
133994   return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
133995 }
133996 static int fts3CreateMethod(
133997   sqlite3 *db,                    /* Database connection */
133998   void *pAux,                     /* Pointer to tokenizer hash table */
133999   int argc,                       /* Number of elements in argv array */
134000   const char * const *argv,       /* xCreate/xConnect argument array */
134001   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
134002   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
134003 ){
134004   return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
134005 }
134006
134007 /*
134008 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
134009 ** extension is currently being used by a version of SQLite too old to
134010 ** support estimatedRows. In that case this function is a no-op.
134011 */
134012 static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
134013 #if SQLITE_VERSION_NUMBER>=3008002
134014   if( sqlite3_libversion_number()>=3008002 ){
134015     pIdxInfo->estimatedRows = nRow;
134016   }
134017 #endif
134018 }
134019
134020 /* 
134021 ** Implementation of the xBestIndex method for FTS3 tables. There
134022 ** are three possible strategies, in order of preference:
134023 **
134024 **   1. Direct lookup by rowid or docid. 
134025 **   2. Full-text search using a MATCH operator on a non-docid column.
134026 **   3. Linear scan of %_content table.
134027 */
134028 static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
134029   Fts3Table *p = (Fts3Table *)pVTab;
134030   int i;                          /* Iterator variable */
134031   int iCons = -1;                 /* Index of constraint to use */
134032
134033   int iLangidCons = -1;           /* Index of langid=x constraint, if present */
134034   int iDocidGe = -1;              /* Index of docid>=x constraint, if present */
134035   int iDocidLe = -1;              /* Index of docid<=x constraint, if present */
134036   int iIdx;
134037
134038   /* By default use a full table scan. This is an expensive option,
134039   ** so search through the constraints to see if a more efficient 
134040   ** strategy is possible.
134041   */
134042   pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
134043   pInfo->estimatedCost = 5000000;
134044   for(i=0; i<pInfo->nConstraint; i++){
134045     int bDocid;                 /* True if this constraint is on docid */
134046     struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
134047     if( pCons->usable==0 ){
134048       if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
134049         /* There exists an unusable MATCH constraint. This means that if
134050         ** the planner does elect to use the results of this call as part
134051         ** of the overall query plan the user will see an "unable to use
134052         ** function MATCH in the requested context" error. To discourage
134053         ** this, return a very high cost here.  */
134054         pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
134055         pInfo->estimatedCost = 1e50;
134056         fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
134057         return SQLITE_OK;
134058       }
134059       continue;
134060     }
134061
134062     bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
134063
134064     /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
134065     if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
134066       pInfo->idxNum = FTS3_DOCID_SEARCH;
134067       pInfo->estimatedCost = 1.0;
134068       iCons = i;
134069     }
134070
134071     /* A MATCH constraint. Use a full-text search.
134072     **
134073     ** If there is more than one MATCH constraint available, use the first
134074     ** one encountered. If there is both a MATCH constraint and a direct
134075     ** rowid/docid lookup, prefer the MATCH strategy. This is done even 
134076     ** though the rowid/docid lookup is faster than a MATCH query, selecting
134077     ** it would lead to an "unable to use function MATCH in the requested 
134078     ** context" error.
134079     */
134080     if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH 
134081      && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
134082     ){
134083       pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
134084       pInfo->estimatedCost = 2.0;
134085       iCons = i;
134086     }
134087
134088     /* Equality constraint on the langid column */
134089     if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ 
134090      && pCons->iColumn==p->nColumn + 2
134091     ){
134092       iLangidCons = i;
134093     }
134094
134095     if( bDocid ){
134096       switch( pCons->op ){
134097         case SQLITE_INDEX_CONSTRAINT_GE:
134098         case SQLITE_INDEX_CONSTRAINT_GT:
134099           iDocidGe = i;
134100           break;
134101
134102         case SQLITE_INDEX_CONSTRAINT_LE:
134103         case SQLITE_INDEX_CONSTRAINT_LT:
134104           iDocidLe = i;
134105           break;
134106       }
134107     }
134108   }
134109
134110   iIdx = 1;
134111   if( iCons>=0 ){
134112     pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
134113     pInfo->aConstraintUsage[iCons].omit = 1;
134114   } 
134115   if( iLangidCons>=0 ){
134116     pInfo->idxNum |= FTS3_HAVE_LANGID;
134117     pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
134118   } 
134119   if( iDocidGe>=0 ){
134120     pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
134121     pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
134122   } 
134123   if( iDocidLe>=0 ){
134124     pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
134125     pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
134126   } 
134127
134128   /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
134129   ** docid) order. Both ascending and descending are possible. 
134130   */
134131   if( pInfo->nOrderBy==1 ){
134132     struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
134133     if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
134134       if( pOrder->desc ){
134135         pInfo->idxStr = "DESC";
134136       }else{
134137         pInfo->idxStr = "ASC";
134138       }
134139       pInfo->orderByConsumed = 1;
134140     }
134141   }
134142
134143   assert( p->pSegments==0 );
134144   return SQLITE_OK;
134145 }
134146
134147 /*
134148 ** Implementation of xOpen method.
134149 */
134150 static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
134151   sqlite3_vtab_cursor *pCsr;               /* Allocated cursor */
134152
134153   UNUSED_PARAMETER(pVTab);
134154
134155   /* Allocate a buffer large enough for an Fts3Cursor structure. If the
134156   ** allocation succeeds, zero it and return SQLITE_OK. Otherwise, 
134157   ** if the allocation fails, return SQLITE_NOMEM.
134158   */
134159   *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
134160   if( !pCsr ){
134161     return SQLITE_NOMEM;
134162   }
134163   memset(pCsr, 0, sizeof(Fts3Cursor));
134164   return SQLITE_OK;
134165 }
134166
134167 /*
134168 ** Close the cursor.  For additional information see the documentation
134169 ** on the xClose method of the virtual table interface.
134170 */
134171 static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
134172   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
134173   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
134174   sqlite3_finalize(pCsr->pStmt);
134175   sqlite3Fts3ExprFree(pCsr->pExpr);
134176   sqlite3Fts3FreeDeferredTokens(pCsr);
134177   sqlite3_free(pCsr->aDoclist);
134178   sqlite3_free(pCsr->aMatchinfo);
134179   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
134180   sqlite3_free(pCsr);
134181   return SQLITE_OK;
134182 }
134183
134184 /*
134185 ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
134186 ** compose and prepare an SQL statement of the form:
134187 **
134188 **    "SELECT <columns> FROM %_content WHERE rowid = ?"
134189 **
134190 ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
134191 ** it. If an error occurs, return an SQLite error code.
134192 **
134193 ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
134194 */
134195 static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
134196   int rc = SQLITE_OK;
134197   if( pCsr->pStmt==0 ){
134198     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
134199     char *zSql;
134200     zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
134201     if( !zSql ) return SQLITE_NOMEM;
134202     rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
134203     sqlite3_free(zSql);
134204   }
134205   *ppStmt = pCsr->pStmt;
134206   return rc;
134207 }
134208
134209 /*
134210 ** Position the pCsr->pStmt statement so that it is on the row
134211 ** of the %_content table that contains the last match.  Return
134212 ** SQLITE_OK on success.  
134213 */
134214 static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
134215   int rc = SQLITE_OK;
134216   if( pCsr->isRequireSeek ){
134217     sqlite3_stmt *pStmt = 0;
134218
134219     rc = fts3CursorSeekStmt(pCsr, &pStmt);
134220     if( rc==SQLITE_OK ){
134221       sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
134222       pCsr->isRequireSeek = 0;
134223       if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
134224         return SQLITE_OK;
134225       }else{
134226         rc = sqlite3_reset(pCsr->pStmt);
134227         if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
134228           /* If no row was found and no error has occurred, then the %_content
134229           ** table is missing a row that is present in the full-text index.
134230           ** The data structures are corrupt.  */
134231           rc = FTS_CORRUPT_VTAB;
134232           pCsr->isEof = 1;
134233         }
134234       }
134235     }
134236   }
134237
134238   if( rc!=SQLITE_OK && pContext ){
134239     sqlite3_result_error_code(pContext, rc);
134240   }
134241   return rc;
134242 }
134243
134244 /*
134245 ** This function is used to process a single interior node when searching
134246 ** a b-tree for a term or term prefix. The node data is passed to this 
134247 ** function via the zNode/nNode parameters. The term to search for is
134248 ** passed in zTerm/nTerm.
134249 **
134250 ** If piFirst is not NULL, then this function sets *piFirst to the blockid
134251 ** of the child node that heads the sub-tree that may contain the term.
134252 **
134253 ** If piLast is not NULL, then *piLast is set to the right-most child node
134254 ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
134255 ** a prefix.
134256 **
134257 ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
134258 */
134259 static int fts3ScanInteriorNode(
134260   const char *zTerm,              /* Term to select leaves for */
134261   int nTerm,                      /* Size of term zTerm in bytes */
134262   const char *zNode,              /* Buffer containing segment interior node */
134263   int nNode,                      /* Size of buffer at zNode */
134264   sqlite3_int64 *piFirst,         /* OUT: Selected child node */
134265   sqlite3_int64 *piLast           /* OUT: Selected child node */
134266 ){
134267   int rc = SQLITE_OK;             /* Return code */
134268   const char *zCsr = zNode;       /* Cursor to iterate through node */
134269   const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
134270   char *zBuffer = 0;              /* Buffer to load terms into */
134271   int nAlloc = 0;                 /* Size of allocated buffer */
134272   int isFirstTerm = 1;            /* True when processing first term on page */
134273   sqlite3_int64 iChild;           /* Block id of child node to descend to */
134274
134275   /* Skip over the 'height' varint that occurs at the start of every 
134276   ** interior node. Then load the blockid of the left-child of the b-tree
134277   ** node into variable iChild.  
134278   **
134279   ** Even if the data structure on disk is corrupted, this (reading two
134280   ** varints from the buffer) does not risk an overread. If zNode is a
134281   ** root node, then the buffer comes from a SELECT statement. SQLite does
134282   ** not make this guarantee explicitly, but in practice there are always
134283   ** either more than 20 bytes of allocated space following the nNode bytes of
134284   ** contents, or two zero bytes. Or, if the node is read from the %_segments
134285   ** table, then there are always 20 bytes of zeroed padding following the
134286   ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
134287   */
134288   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
134289   zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
134290   if( zCsr>zEnd ){
134291     return FTS_CORRUPT_VTAB;
134292   }
134293   
134294   while( zCsr<zEnd && (piFirst || piLast) ){
134295     int cmp;                      /* memcmp() result */
134296     int nSuffix;                  /* Size of term suffix */
134297     int nPrefix = 0;              /* Size of term prefix */
134298     int nBuffer;                  /* Total term size */
134299   
134300     /* Load the next term on the node into zBuffer. Use realloc() to expand
134301     ** the size of zBuffer if required.  */
134302     if( !isFirstTerm ){
134303       zCsr += fts3GetVarint32(zCsr, &nPrefix);
134304     }
134305     isFirstTerm = 0;
134306     zCsr += fts3GetVarint32(zCsr, &nSuffix);
134307     
134308     if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
134309       rc = FTS_CORRUPT_VTAB;
134310       goto finish_scan;
134311     }
134312     if( nPrefix+nSuffix>nAlloc ){
134313       char *zNew;
134314       nAlloc = (nPrefix+nSuffix) * 2;
134315       zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
134316       if( !zNew ){
134317         rc = SQLITE_NOMEM;
134318         goto finish_scan;
134319       }
134320       zBuffer = zNew;
134321     }
134322     assert( zBuffer );
134323     memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
134324     nBuffer = nPrefix + nSuffix;
134325     zCsr += nSuffix;
134326
134327     /* Compare the term we are searching for with the term just loaded from
134328     ** the interior node. If the specified term is greater than or equal
134329     ** to the term from the interior node, then all terms on the sub-tree 
134330     ** headed by node iChild are smaller than zTerm. No need to search 
134331     ** iChild.
134332     **
134333     ** If the interior node term is larger than the specified term, then
134334     ** the tree headed by iChild may contain the specified term.
134335     */
134336     cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
134337     if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
134338       *piFirst = iChild;
134339       piFirst = 0;
134340     }
134341
134342     if( piLast && cmp<0 ){
134343       *piLast = iChild;
134344       piLast = 0;
134345     }
134346
134347     iChild++;
134348   };
134349
134350   if( piFirst ) *piFirst = iChild;
134351   if( piLast ) *piLast = iChild;
134352
134353  finish_scan:
134354   sqlite3_free(zBuffer);
134355   return rc;
134356 }
134357
134358
134359 /*
134360 ** The buffer pointed to by argument zNode (size nNode bytes) contains an
134361 ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
134362 ** contains a term. This function searches the sub-tree headed by the zNode
134363 ** node for the range of leaf nodes that may contain the specified term
134364 ** or terms for which the specified term is a prefix.
134365 **
134366 ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the 
134367 ** left-most leaf node in the tree that may contain the specified term.
134368 ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
134369 ** right-most leaf node that may contain a term for which the specified
134370 ** term is a prefix.
134371 **
134372 ** It is possible that the range of returned leaf nodes does not contain 
134373 ** the specified term or any terms for which it is a prefix. However, if the 
134374 ** segment does contain any such terms, they are stored within the identified
134375 ** range. Because this function only inspects interior segment nodes (and
134376 ** never loads leaf nodes into memory), it is not possible to be sure.
134377 **
134378 ** If an error occurs, an error code other than SQLITE_OK is returned.
134379 */ 
134380 static int fts3SelectLeaf(
134381   Fts3Table *p,                   /* Virtual table handle */
134382   const char *zTerm,              /* Term to select leaves for */
134383   int nTerm,                      /* Size of term zTerm in bytes */
134384   const char *zNode,              /* Buffer containing segment interior node */
134385   int nNode,                      /* Size of buffer at zNode */
134386   sqlite3_int64 *piLeaf,          /* Selected leaf node */
134387   sqlite3_int64 *piLeaf2          /* Selected leaf node */
134388 ){
134389   int rc = SQLITE_OK;             /* Return code */
134390   int iHeight;                    /* Height of this node in tree */
134391
134392   assert( piLeaf || piLeaf2 );
134393
134394   fts3GetVarint32(zNode, &iHeight);
134395   rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
134396   assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
134397
134398   if( rc==SQLITE_OK && iHeight>1 ){
134399     char *zBlob = 0;              /* Blob read from %_segments table */
134400     int nBlob = 0;                /* Size of zBlob in bytes */
134401
134402     if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
134403       rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
134404       if( rc==SQLITE_OK ){
134405         rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
134406       }
134407       sqlite3_free(zBlob);
134408       piLeaf = 0;
134409       zBlob = 0;
134410     }
134411
134412     if( rc==SQLITE_OK ){
134413       rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
134414     }
134415     if( rc==SQLITE_OK ){
134416       rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
134417     }
134418     sqlite3_free(zBlob);
134419   }
134420
134421   return rc;
134422 }
134423
134424 /*
134425 ** This function is used to create delta-encoded serialized lists of FTS3 
134426 ** varints. Each call to this function appends a single varint to a list.
134427 */
134428 static void fts3PutDeltaVarint(
134429   char **pp,                      /* IN/OUT: Output pointer */
134430   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
134431   sqlite3_int64 iVal              /* Write this value to the list */
134432 ){
134433   assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
134434   *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
134435   *piPrev = iVal;
134436 }
134437
134438 /*
134439 ** When this function is called, *ppPoslist is assumed to point to the 
134440 ** start of a position-list. After it returns, *ppPoslist points to the
134441 ** first byte after the position-list.
134442 **
134443 ** A position list is list of positions (delta encoded) and columns for 
134444 ** a single document record of a doclist.  So, in other words, this
134445 ** routine advances *ppPoslist so that it points to the next docid in
134446 ** the doclist, or to the first byte past the end of the doclist.
134447 **
134448 ** If pp is not NULL, then the contents of the position list are copied
134449 ** to *pp. *pp is set to point to the first byte past the last byte copied
134450 ** before this function returns.
134451 */
134452 static void fts3PoslistCopy(char **pp, char **ppPoslist){
134453   char *pEnd = *ppPoslist;
134454   char c = 0;
134455
134456   /* The end of a position list is marked by a zero encoded as an FTS3 
134457   ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
134458   ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
134459   ** of some other, multi-byte, value.
134460   **
134461   ** The following while-loop moves pEnd to point to the first byte that is not 
134462   ** immediately preceded by a byte with the 0x80 bit set. Then increments
134463   ** pEnd once more so that it points to the byte immediately following the
134464   ** last byte in the position-list.
134465   */
134466   while( *pEnd | c ){
134467     c = *pEnd++ & 0x80;
134468     testcase( c!=0 && (*pEnd)==0 );
134469   }
134470   pEnd++;  /* Advance past the POS_END terminator byte */
134471
134472   if( pp ){
134473     int n = (int)(pEnd - *ppPoslist);
134474     char *p = *pp;
134475     memcpy(p, *ppPoslist, n);
134476     p += n;
134477     *pp = p;
134478   }
134479   *ppPoslist = pEnd;
134480 }
134481
134482 /*
134483 ** When this function is called, *ppPoslist is assumed to point to the 
134484 ** start of a column-list. After it returns, *ppPoslist points to the
134485 ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
134486 **
134487 ** A column-list is list of delta-encoded positions for a single column
134488 ** within a single document within a doclist.
134489 **
134490 ** The column-list is terminated either by a POS_COLUMN varint (1) or
134491 ** a POS_END varint (0).  This routine leaves *ppPoslist pointing to
134492 ** the POS_COLUMN or POS_END that terminates the column-list.
134493 **
134494 ** If pp is not NULL, then the contents of the column-list are copied
134495 ** to *pp. *pp is set to point to the first byte past the last byte copied
134496 ** before this function returns.  The POS_COLUMN or POS_END terminator
134497 ** is not copied into *pp.
134498 */
134499 static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
134500   char *pEnd = *ppPoslist;
134501   char c = 0;
134502
134503   /* A column-list is terminated by either a 0x01 or 0x00 byte that is
134504   ** not part of a multi-byte varint.
134505   */
134506   while( 0xFE & (*pEnd | c) ){
134507     c = *pEnd++ & 0x80;
134508     testcase( c!=0 && ((*pEnd)&0xfe)==0 );
134509   }
134510   if( pp ){
134511     int n = (int)(pEnd - *ppPoslist);
134512     char *p = *pp;
134513     memcpy(p, *ppPoslist, n);
134514     p += n;
134515     *pp = p;
134516   }
134517   *ppPoslist = pEnd;
134518 }
134519
134520 /*
134521 ** Value used to signify the end of an position-list. This is safe because
134522 ** it is not possible to have a document with 2^31 terms.
134523 */
134524 #define POSITION_LIST_END 0x7fffffff
134525
134526 /*
134527 ** This function is used to help parse position-lists. When this function is
134528 ** called, *pp may point to the start of the next varint in the position-list
134529 ** being parsed, or it may point to 1 byte past the end of the position-list
134530 ** (in which case **pp will be a terminator bytes POS_END (0) or
134531 ** (1)).
134532 **
134533 ** If *pp points past the end of the current position-list, set *pi to 
134534 ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
134535 ** increment the current value of *pi by the value read, and set *pp to
134536 ** point to the next value before returning.
134537 **
134538 ** Before calling this routine *pi must be initialized to the value of
134539 ** the previous position, or zero if we are reading the first position
134540 ** in the position-list.  Because positions are delta-encoded, the value
134541 ** of the previous position is needed in order to compute the value of
134542 ** the next position.
134543 */
134544 static void fts3ReadNextPos(
134545   char **pp,                    /* IN/OUT: Pointer into position-list buffer */
134546   sqlite3_int64 *pi             /* IN/OUT: Value read from position-list */
134547 ){
134548   if( (**pp)&0xFE ){
134549     fts3GetDeltaVarint(pp, pi);
134550     *pi -= 2;
134551   }else{
134552     *pi = POSITION_LIST_END;
134553   }
134554 }
134555
134556 /*
134557 ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
134558 ** the value of iCol encoded as a varint to *pp.   This will start a new
134559 ** column list.
134560 **
134561 ** Set *pp to point to the byte just after the last byte written before 
134562 ** returning (do not modify it if iCol==0). Return the total number of bytes
134563 ** written (0 if iCol==0).
134564 */
134565 static int fts3PutColNumber(char **pp, int iCol){
134566   int n = 0;                      /* Number of bytes written */
134567   if( iCol ){
134568     char *p = *pp;                /* Output pointer */
134569     n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
134570     *p = 0x01;
134571     *pp = &p[n];
134572   }
134573   return n;
134574 }
134575
134576 /*
134577 ** Compute the union of two position lists.  The output written
134578 ** into *pp contains all positions of both *pp1 and *pp2 in sorted
134579 ** order and with any duplicates removed.  All pointers are
134580 ** updated appropriately.   The caller is responsible for insuring
134581 ** that there is enough space in *pp to hold the complete output.
134582 */
134583 static void fts3PoslistMerge(
134584   char **pp,                      /* Output buffer */
134585   char **pp1,                     /* Left input list */
134586   char **pp2                      /* Right input list */
134587 ){
134588   char *p = *pp;
134589   char *p1 = *pp1;
134590   char *p2 = *pp2;
134591
134592   while( *p1 || *p2 ){
134593     int iCol1;         /* The current column index in pp1 */
134594     int iCol2;         /* The current column index in pp2 */
134595
134596     if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
134597     else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
134598     else iCol1 = 0;
134599
134600     if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
134601     else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
134602     else iCol2 = 0;
134603
134604     if( iCol1==iCol2 ){
134605       sqlite3_int64 i1 = 0;       /* Last position from pp1 */
134606       sqlite3_int64 i2 = 0;       /* Last position from pp2 */
134607       sqlite3_int64 iPrev = 0;
134608       int n = fts3PutColNumber(&p, iCol1);
134609       p1 += n;
134610       p2 += n;
134611
134612       /* At this point, both p1 and p2 point to the start of column-lists
134613       ** for the same column (the column with index iCol1 and iCol2).
134614       ** A column-list is a list of non-negative delta-encoded varints, each 
134615       ** incremented by 2 before being stored. Each list is terminated by a
134616       ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
134617       ** and writes the results to buffer p. p is left pointing to the byte
134618       ** after the list written. No terminator (POS_END or POS_COLUMN) is
134619       ** written to the output.
134620       */
134621       fts3GetDeltaVarint(&p1, &i1);
134622       fts3GetDeltaVarint(&p2, &i2);
134623       do {
134624         fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2); 
134625         iPrev -= 2;
134626         if( i1==i2 ){
134627           fts3ReadNextPos(&p1, &i1);
134628           fts3ReadNextPos(&p2, &i2);
134629         }else if( i1<i2 ){
134630           fts3ReadNextPos(&p1, &i1);
134631         }else{
134632           fts3ReadNextPos(&p2, &i2);
134633         }
134634       }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
134635     }else if( iCol1<iCol2 ){
134636       p1 += fts3PutColNumber(&p, iCol1);
134637       fts3ColumnlistCopy(&p, &p1);
134638     }else{
134639       p2 += fts3PutColNumber(&p, iCol2);
134640       fts3ColumnlistCopy(&p, &p2);
134641     }
134642   }
134643
134644   *p++ = POS_END;
134645   *pp = p;
134646   *pp1 = p1 + 1;
134647   *pp2 = p2 + 1;
134648 }
134649
134650 /*
134651 ** This function is used to merge two position lists into one. When it is
134652 ** called, *pp1 and *pp2 must both point to position lists. A position-list is
134653 ** the part of a doclist that follows each document id. For example, if a row
134654 ** contains:
134655 **
134656 **     'a b c'|'x y z'|'a b b a'
134657 **
134658 ** Then the position list for this row for token 'b' would consist of:
134659 **
134660 **     0x02 0x01 0x02 0x03 0x03 0x00
134661 **
134662 ** When this function returns, both *pp1 and *pp2 are left pointing to the
134663 ** byte following the 0x00 terminator of their respective position lists.
134664 **
134665 ** If isSaveLeft is 0, an entry is added to the output position list for 
134666 ** each position in *pp2 for which there exists one or more positions in
134667 ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
134668 ** when the *pp1 token appears before the *pp2 token, but not more than nToken
134669 ** slots before it.
134670 **
134671 ** e.g. nToken==1 searches for adjacent positions.
134672 */
134673 static int fts3PoslistPhraseMerge(
134674   char **pp,                      /* IN/OUT: Preallocated output buffer */
134675   int nToken,                     /* Maximum difference in token positions */
134676   int isSaveLeft,                 /* Save the left position */
134677   int isExact,                    /* If *pp1 is exactly nTokens before *pp2 */
134678   char **pp1,                     /* IN/OUT: Left input list */
134679   char **pp2                      /* IN/OUT: Right input list */
134680 ){
134681   char *p = *pp;
134682   char *p1 = *pp1;
134683   char *p2 = *pp2;
134684   int iCol1 = 0;
134685   int iCol2 = 0;
134686
134687   /* Never set both isSaveLeft and isExact for the same invocation. */
134688   assert( isSaveLeft==0 || isExact==0 );
134689
134690   assert( p!=0 && *p1!=0 && *p2!=0 );
134691   if( *p1==POS_COLUMN ){ 
134692     p1++;
134693     p1 += fts3GetVarint32(p1, &iCol1);
134694   }
134695   if( *p2==POS_COLUMN ){ 
134696     p2++;
134697     p2 += fts3GetVarint32(p2, &iCol2);
134698   }
134699
134700   while( 1 ){
134701     if( iCol1==iCol2 ){
134702       char *pSave = p;
134703       sqlite3_int64 iPrev = 0;
134704       sqlite3_int64 iPos1 = 0;
134705       sqlite3_int64 iPos2 = 0;
134706
134707       if( iCol1 ){
134708         *p++ = POS_COLUMN;
134709         p += sqlite3Fts3PutVarint(p, iCol1);
134710       }
134711
134712       assert( *p1!=POS_END && *p1!=POS_COLUMN );
134713       assert( *p2!=POS_END && *p2!=POS_COLUMN );
134714       fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
134715       fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
134716
134717       while( 1 ){
134718         if( iPos2==iPos1+nToken 
134719          || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken) 
134720         ){
134721           sqlite3_int64 iSave;
134722           iSave = isSaveLeft ? iPos1 : iPos2;
134723           fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
134724           pSave = 0;
134725           assert( p );
134726         }
134727         if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
134728           if( (*p2&0xFE)==0 ) break;
134729           fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
134730         }else{
134731           if( (*p1&0xFE)==0 ) break;
134732           fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
134733         }
134734       }
134735
134736       if( pSave ){
134737         assert( pp && p );
134738         p = pSave;
134739       }
134740
134741       fts3ColumnlistCopy(0, &p1);
134742       fts3ColumnlistCopy(0, &p2);
134743       assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
134744       if( 0==*p1 || 0==*p2 ) break;
134745
134746       p1++;
134747       p1 += fts3GetVarint32(p1, &iCol1);
134748       p2++;
134749       p2 += fts3GetVarint32(p2, &iCol2);
134750     }
134751
134752     /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
134753     ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
134754     ** end of the position list, or the 0x01 that precedes the next 
134755     ** column-number in the position list. 
134756     */
134757     else if( iCol1<iCol2 ){
134758       fts3ColumnlistCopy(0, &p1);
134759       if( 0==*p1 ) break;
134760       p1++;
134761       p1 += fts3GetVarint32(p1, &iCol1);
134762     }else{
134763       fts3ColumnlistCopy(0, &p2);
134764       if( 0==*p2 ) break;
134765       p2++;
134766       p2 += fts3GetVarint32(p2, &iCol2);
134767     }
134768   }
134769
134770   fts3PoslistCopy(0, &p2);
134771   fts3PoslistCopy(0, &p1);
134772   *pp1 = p1;
134773   *pp2 = p2;
134774   if( *pp==p ){
134775     return 0;
134776   }
134777   *p++ = 0x00;
134778   *pp = p;
134779   return 1;
134780 }
134781
134782 /*
134783 ** Merge two position-lists as required by the NEAR operator. The argument
134784 ** position lists correspond to the left and right phrases of an expression 
134785 ** like:
134786 **
134787 **     "phrase 1" NEAR "phrase number 2"
134788 **
134789 ** Position list *pp1 corresponds to the left-hand side of the NEAR 
134790 ** expression and *pp2 to the right. As usual, the indexes in the position 
134791 ** lists are the offsets of the last token in each phrase (tokens "1" and "2" 
134792 ** in the example above).
134793 **
134794 ** The output position list - written to *pp - is a copy of *pp2 with those
134795 ** entries that are not sufficiently NEAR entries in *pp1 removed.
134796 */
134797 static int fts3PoslistNearMerge(
134798   char **pp,                      /* Output buffer */
134799   char *aTmp,                     /* Temporary buffer space */
134800   int nRight,                     /* Maximum difference in token positions */
134801   int nLeft,                      /* Maximum difference in token positions */
134802   char **pp1,                     /* IN/OUT: Left input list */
134803   char **pp2                      /* IN/OUT: Right input list */
134804 ){
134805   char *p1 = *pp1;
134806   char *p2 = *pp2;
134807
134808   char *pTmp1 = aTmp;
134809   char *pTmp2;
134810   char *aTmp2;
134811   int res = 1;
134812
134813   fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
134814   aTmp2 = pTmp2 = pTmp1;
134815   *pp1 = p1;
134816   *pp2 = p2;
134817   fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
134818   if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
134819     fts3PoslistMerge(pp, &aTmp, &aTmp2);
134820   }else if( pTmp1!=aTmp ){
134821     fts3PoslistCopy(pp, &aTmp);
134822   }else if( pTmp2!=aTmp2 ){
134823     fts3PoslistCopy(pp, &aTmp2);
134824   }else{
134825     res = 0;
134826   }
134827
134828   return res;
134829 }
134830
134831 /* 
134832 ** An instance of this function is used to merge together the (potentially
134833 ** large number of) doclists for each term that matches a prefix query.
134834 ** See function fts3TermSelectMerge() for details.
134835 */
134836 typedef struct TermSelect TermSelect;
134837 struct TermSelect {
134838   char *aaOutput[16];             /* Malloc'd output buffers */
134839   int anOutput[16];               /* Size each output buffer in bytes */
134840 };
134841
134842 /*
134843 ** This function is used to read a single varint from a buffer. Parameter
134844 ** pEnd points 1 byte past the end of the buffer. When this function is
134845 ** called, if *pp points to pEnd or greater, then the end of the buffer
134846 ** has been reached. In this case *pp is set to 0 and the function returns.
134847 **
134848 ** If *pp does not point to or past pEnd, then a single varint is read
134849 ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
134850 **
134851 ** If bDescIdx is false, the value read is added to *pVal before returning.
134852 ** If it is true, the value read is subtracted from *pVal before this 
134853 ** function returns.
134854 */
134855 static void fts3GetDeltaVarint3(
134856   char **pp,                      /* IN/OUT: Point to read varint from */
134857   char *pEnd,                     /* End of buffer */
134858   int bDescIdx,                   /* True if docids are descending */
134859   sqlite3_int64 *pVal             /* IN/OUT: Integer value */
134860 ){
134861   if( *pp>=pEnd ){
134862     *pp = 0;
134863   }else{
134864     sqlite3_int64 iVal;
134865     *pp += sqlite3Fts3GetVarint(*pp, &iVal);
134866     if( bDescIdx ){
134867       *pVal -= iVal;
134868     }else{
134869       *pVal += iVal;
134870     }
134871   }
134872 }
134873
134874 /*
134875 ** This function is used to write a single varint to a buffer. The varint
134876 ** is written to *pp. Before returning, *pp is set to point 1 byte past the
134877 ** end of the value written.
134878 **
134879 ** If *pbFirst is zero when this function is called, the value written to
134880 ** the buffer is that of parameter iVal. 
134881 **
134882 ** If *pbFirst is non-zero when this function is called, then the value 
134883 ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
134884 ** (if bDescIdx is non-zero).
134885 **
134886 ** Before returning, this function always sets *pbFirst to 1 and *piPrev
134887 ** to the value of parameter iVal.
134888 */
134889 static void fts3PutDeltaVarint3(
134890   char **pp,                      /* IN/OUT: Output pointer */
134891   int bDescIdx,                   /* True for descending docids */
134892   sqlite3_int64 *piPrev,          /* IN/OUT: Previous value written to list */
134893   int *pbFirst,                   /* IN/OUT: True after first int written */
134894   sqlite3_int64 iVal              /* Write this value to the list */
134895 ){
134896   sqlite3_int64 iWrite;
134897   if( bDescIdx==0 || *pbFirst==0 ){
134898     iWrite = iVal - *piPrev;
134899   }else{
134900     iWrite = *piPrev - iVal;
134901   }
134902   assert( *pbFirst || *piPrev==0 );
134903   assert( *pbFirst==0 || iWrite>0 );
134904   *pp += sqlite3Fts3PutVarint(*pp, iWrite);
134905   *piPrev = iVal;
134906   *pbFirst = 1;
134907 }
134908
134909
134910 /*
134911 ** This macro is used by various functions that merge doclists. The two
134912 ** arguments are 64-bit docid values. If the value of the stack variable
134913 ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2). 
134914 ** Otherwise, (i2-i1).
134915 **
134916 ** Using this makes it easier to write code that can merge doclists that are
134917 ** sorted in either ascending or descending order.
134918 */
134919 #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
134920
134921 /*
134922 ** This function does an "OR" merge of two doclists (output contains all
134923 ** positions contained in either argument doclist). If the docids in the 
134924 ** input doclists are sorted in ascending order, parameter bDescDoclist
134925 ** should be false. If they are sorted in ascending order, it should be
134926 ** passed a non-zero value.
134927 **
134928 ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
134929 ** containing the output doclist and SQLITE_OK is returned. In this case
134930 ** *pnOut is set to the number of bytes in the output doclist.
134931 **
134932 ** If an error occurs, an SQLite error code is returned. The output values
134933 ** are undefined in this case.
134934 */
134935 static int fts3DoclistOrMerge(
134936   int bDescDoclist,               /* True if arguments are desc */
134937   char *a1, int n1,               /* First doclist */
134938   char *a2, int n2,               /* Second doclist */
134939   char **paOut, int *pnOut        /* OUT: Malloc'd doclist */
134940 ){
134941   sqlite3_int64 i1 = 0;
134942   sqlite3_int64 i2 = 0;
134943   sqlite3_int64 iPrev = 0;
134944   char *pEnd1 = &a1[n1];
134945   char *pEnd2 = &a2[n2];
134946   char *p1 = a1;
134947   char *p2 = a2;
134948   char *p;
134949   char *aOut;
134950   int bFirstOut = 0;
134951
134952   *paOut = 0;
134953   *pnOut = 0;
134954
134955   /* Allocate space for the output. Both the input and output doclists
134956   ** are delta encoded. If they are in ascending order (bDescDoclist==0),
134957   ** then the first docid in each list is simply encoded as a varint. For
134958   ** each subsequent docid, the varint stored is the difference between the
134959   ** current and previous docid (a positive number - since the list is in
134960   ** ascending order).
134961   **
134962   ** The first docid written to the output is therefore encoded using the 
134963   ** same number of bytes as it is in whichever of the input lists it is
134964   ** read from. And each subsequent docid read from the same input list 
134965   ** consumes either the same or less bytes as it did in the input (since
134966   ** the difference between it and the previous value in the output must
134967   ** be a positive value less than or equal to the delta value read from 
134968   ** the input list). The same argument applies to all but the first docid
134969   ** read from the 'other' list. And to the contents of all position lists
134970   ** that will be copied and merged from the input to the output.
134971   **
134972   ** However, if the first docid copied to the output is a negative number,
134973   ** then the encoding of the first docid from the 'other' input list may
134974   ** be larger in the output than it was in the input (since the delta value
134975   ** may be a larger positive integer than the actual docid).
134976   **
134977   ** The space required to store the output is therefore the sum of the
134978   ** sizes of the two inputs, plus enough space for exactly one of the input
134979   ** docids to grow. 
134980   **
134981   ** A symetric argument may be made if the doclists are in descending 
134982   ** order.
134983   */
134984   aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
134985   if( !aOut ) return SQLITE_NOMEM;
134986
134987   p = aOut;
134988   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
134989   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
134990   while( p1 || p2 ){
134991     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
134992
134993     if( p2 && p1 && iDiff==0 ){
134994       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
134995       fts3PoslistMerge(&p, &p1, &p2);
134996       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
134997       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
134998     }else if( !p2 || (p1 && iDiff<0) ){
134999       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
135000       fts3PoslistCopy(&p, &p1);
135001       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
135002     }else{
135003       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
135004       fts3PoslistCopy(&p, &p2);
135005       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
135006     }
135007   }
135008
135009   *paOut = aOut;
135010   *pnOut = (int)(p-aOut);
135011   assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
135012   return SQLITE_OK;
135013 }
135014
135015 /*
135016 ** This function does a "phrase" merge of two doclists. In a phrase merge,
135017 ** the output contains a copy of each position from the right-hand input
135018 ** doclist for which there is a position in the left-hand input doclist
135019 ** exactly nDist tokens before it.
135020 **
135021 ** If the docids in the input doclists are sorted in ascending order,
135022 ** parameter bDescDoclist should be false. If they are sorted in ascending 
135023 ** order, it should be passed a non-zero value.
135024 **
135025 ** The right-hand input doclist is overwritten by this function.
135026 */
135027 static int fts3DoclistPhraseMerge(
135028   int bDescDoclist,               /* True if arguments are desc */
135029   int nDist,                      /* Distance from left to right (1=adjacent) */
135030   char *aLeft, int nLeft,         /* Left doclist */
135031   char **paRight, int *pnRight    /* IN/OUT: Right/output doclist */
135032 ){
135033   sqlite3_int64 i1 = 0;
135034   sqlite3_int64 i2 = 0;
135035   sqlite3_int64 iPrev = 0;
135036   char *aRight = *paRight;
135037   char *pEnd1 = &aLeft[nLeft];
135038   char *pEnd2 = &aRight[*pnRight];
135039   char *p1 = aLeft;
135040   char *p2 = aRight;
135041   char *p;
135042   int bFirstOut = 0;
135043   char *aOut;
135044
135045   assert( nDist>0 );
135046   if( bDescDoclist ){
135047     aOut = sqlite3_malloc(*pnRight + FTS3_VARINT_MAX);
135048     if( aOut==0 ) return SQLITE_NOMEM;
135049   }else{
135050     aOut = aRight;
135051   }
135052   p = aOut;
135053
135054   fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
135055   fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
135056
135057   while( p1 && p2 ){
135058     sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
135059     if( iDiff==0 ){
135060       char *pSave = p;
135061       sqlite3_int64 iPrevSave = iPrev;
135062       int bFirstOutSave = bFirstOut;
135063
135064       fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
135065       if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
135066         p = pSave;
135067         iPrev = iPrevSave;
135068         bFirstOut = bFirstOutSave;
135069       }
135070       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
135071       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
135072     }else if( iDiff<0 ){
135073       fts3PoslistCopy(0, &p1);
135074       fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
135075     }else{
135076       fts3PoslistCopy(0, &p2);
135077       fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
135078     }
135079   }
135080
135081   *pnRight = (int)(p - aOut);
135082   if( bDescDoclist ){
135083     sqlite3_free(aRight);
135084     *paRight = aOut;
135085   }
135086
135087   return SQLITE_OK;
135088 }
135089
135090 /*
135091 ** Argument pList points to a position list nList bytes in size. This
135092 ** function checks to see if the position list contains any entries for
135093 ** a token in position 0 (of any column). If so, it writes argument iDelta
135094 ** to the output buffer pOut, followed by a position list consisting only
135095 ** of the entries from pList at position 0, and terminated by an 0x00 byte.
135096 ** The value returned is the number of bytes written to pOut (if any).
135097 */
135098 SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
135099   sqlite3_int64 iDelta,           /* Varint that may be written to pOut */
135100   char *pList,                    /* Position list (no 0x00 term) */
135101   int nList,                      /* Size of pList in bytes */
135102   char *pOut                      /* Write output here */
135103 ){
135104   int nOut = 0;
135105   int bWritten = 0;               /* True once iDelta has been written */
135106   char *p = pList;
135107   char *pEnd = &pList[nList];
135108
135109   if( *p!=0x01 ){
135110     if( *p==0x02 ){
135111       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
135112       pOut[nOut++] = 0x02;
135113       bWritten = 1;
135114     }
135115     fts3ColumnlistCopy(0, &p);
135116   }
135117
135118   while( p<pEnd && *p==0x01 ){
135119     sqlite3_int64 iCol;
135120     p++;
135121     p += sqlite3Fts3GetVarint(p, &iCol);
135122     if( *p==0x02 ){
135123       if( bWritten==0 ){
135124         nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
135125         bWritten = 1;
135126       }
135127       pOut[nOut++] = 0x01;
135128       nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
135129       pOut[nOut++] = 0x02;
135130     }
135131     fts3ColumnlistCopy(0, &p);
135132   }
135133   if( bWritten ){
135134     pOut[nOut++] = 0x00;
135135   }
135136
135137   return nOut;
135138 }
135139
135140
135141 /*
135142 ** Merge all doclists in the TermSelect.aaOutput[] array into a single
135143 ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
135144 ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
135145 **
135146 ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
135147 ** the responsibility of the caller to free any doclists left in the
135148 ** TermSelect.aaOutput[] array.
135149 */
135150 static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
135151   char *aOut = 0;
135152   int nOut = 0;
135153   int i;
135154
135155   /* Loop through the doclists in the aaOutput[] array. Merge them all
135156   ** into a single doclist.
135157   */
135158   for(i=0; i<SizeofArray(pTS->aaOutput); i++){
135159     if( pTS->aaOutput[i] ){
135160       if( !aOut ){
135161         aOut = pTS->aaOutput[i];
135162         nOut = pTS->anOutput[i];
135163         pTS->aaOutput[i] = 0;
135164       }else{
135165         int nNew;
135166         char *aNew;
135167
135168         int rc = fts3DoclistOrMerge(p->bDescIdx, 
135169             pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
135170         );
135171         if( rc!=SQLITE_OK ){
135172           sqlite3_free(aOut);
135173           return rc;
135174         }
135175
135176         sqlite3_free(pTS->aaOutput[i]);
135177         sqlite3_free(aOut);
135178         pTS->aaOutput[i] = 0;
135179         aOut = aNew;
135180         nOut = nNew;
135181       }
135182     }
135183   }
135184
135185   pTS->aaOutput[0] = aOut;
135186   pTS->anOutput[0] = nOut;
135187   return SQLITE_OK;
135188 }
135189
135190 /*
135191 ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
135192 ** as the first argument. The merge is an "OR" merge (see function
135193 ** fts3DoclistOrMerge() for details).
135194 **
135195 ** This function is called with the doclist for each term that matches
135196 ** a queried prefix. It merges all these doclists into one, the doclist
135197 ** for the specified prefix. Since there can be a very large number of
135198 ** doclists to merge, the merging is done pair-wise using the TermSelect
135199 ** object.
135200 **
135201 ** This function returns SQLITE_OK if the merge is successful, or an
135202 ** SQLite error code (SQLITE_NOMEM) if an error occurs.
135203 */
135204 static int fts3TermSelectMerge(
135205   Fts3Table *p,                   /* FTS table handle */
135206   TermSelect *pTS,                /* TermSelect object to merge into */
135207   char *aDoclist,                 /* Pointer to doclist */
135208   int nDoclist                    /* Size of aDoclist in bytes */
135209 ){
135210   if( pTS->aaOutput[0]==0 ){
135211     /* If this is the first term selected, copy the doclist to the output
135212     ** buffer using memcpy(). 
135213     **
135214     ** Add FTS3_VARINT_MAX bytes of unused space to the end of the 
135215     ** allocation. This is so as to ensure that the buffer is big enough
135216     ** to hold the current doclist AND'd with any other doclist. If the
135217     ** doclists are stored in order=ASC order, this padding would not be
135218     ** required (since the size of [doclistA AND doclistB] is always less
135219     ** than or equal to the size of [doclistA] in that case). But this is
135220     ** not true for order=DESC. For example, a doclist containing (1, -1) 
135221     ** may be smaller than (-1), as in the first example the -1 may be stored
135222     ** as a single-byte delta, whereas in the second it must be stored as a
135223     ** FTS3_VARINT_MAX byte varint.
135224     **
135225     ** Similar padding is added in the fts3DoclistOrMerge() function.
135226     */
135227     pTS->aaOutput[0] = sqlite3_malloc(nDoclist + FTS3_VARINT_MAX + 1);
135228     pTS->anOutput[0] = nDoclist;
135229     if( pTS->aaOutput[0] ){
135230       memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
135231     }else{
135232       return SQLITE_NOMEM;
135233     }
135234   }else{
135235     char *aMerge = aDoclist;
135236     int nMerge = nDoclist;
135237     int iOut;
135238
135239     for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
135240       if( pTS->aaOutput[iOut]==0 ){
135241         assert( iOut>0 );
135242         pTS->aaOutput[iOut] = aMerge;
135243         pTS->anOutput[iOut] = nMerge;
135244         break;
135245       }else{
135246         char *aNew;
135247         int nNew;
135248
135249         int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge, 
135250             pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
135251         );
135252         if( rc!=SQLITE_OK ){
135253           if( aMerge!=aDoclist ) sqlite3_free(aMerge);
135254           return rc;
135255         }
135256
135257         if( aMerge!=aDoclist ) sqlite3_free(aMerge);
135258         sqlite3_free(pTS->aaOutput[iOut]);
135259         pTS->aaOutput[iOut] = 0;
135260   
135261         aMerge = aNew;
135262         nMerge = nNew;
135263         if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
135264           pTS->aaOutput[iOut] = aMerge;
135265           pTS->anOutput[iOut] = nMerge;
135266         }
135267       }
135268     }
135269   }
135270   return SQLITE_OK;
135271 }
135272
135273 /*
135274 ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
135275 */
135276 static int fts3SegReaderCursorAppend(
135277   Fts3MultiSegReader *pCsr, 
135278   Fts3SegReader *pNew
135279 ){
135280   if( (pCsr->nSegment%16)==0 ){
135281     Fts3SegReader **apNew;
135282     int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
135283     apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
135284     if( !apNew ){
135285       sqlite3Fts3SegReaderFree(pNew);
135286       return SQLITE_NOMEM;
135287     }
135288     pCsr->apSegment = apNew;
135289   }
135290   pCsr->apSegment[pCsr->nSegment++] = pNew;
135291   return SQLITE_OK;
135292 }
135293
135294 /*
135295 ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
135296 ** 8th argument.
135297 **
135298 ** This function returns SQLITE_OK if successful, or an SQLite error code
135299 ** otherwise.
135300 */
135301 static int fts3SegReaderCursor(
135302   Fts3Table *p,                   /* FTS3 table handle */
135303   int iLangid,                    /* Language id */
135304   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
135305   int iLevel,                     /* Level of segments to scan */
135306   const char *zTerm,              /* Term to query for */
135307   int nTerm,                      /* Size of zTerm in bytes */
135308   int isPrefix,                   /* True for a prefix search */
135309   int isScan,                     /* True to scan from zTerm to EOF */
135310   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
135311 ){
135312   int rc = SQLITE_OK;             /* Error code */
135313   sqlite3_stmt *pStmt = 0;        /* Statement to iterate through segments */
135314   int rc2;                        /* Result of sqlite3_reset() */
135315
135316   /* If iLevel is less than 0 and this is not a scan, include a seg-reader 
135317   ** for the pending-terms. If this is a scan, then this call must be being
135318   ** made by an fts4aux module, not an FTS table. In this case calling
135319   ** Fts3SegReaderPending might segfault, as the data structures used by 
135320   ** fts4aux are not completely populated. So it's easiest to filter these
135321   ** calls out here.  */
135322   if( iLevel<0 && p->aIndex ){
135323     Fts3SegReader *pSeg = 0;
135324     rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
135325     if( rc==SQLITE_OK && pSeg ){
135326       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
135327     }
135328   }
135329
135330   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
135331     if( rc==SQLITE_OK ){
135332       rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
135333     }
135334
135335     while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
135336       Fts3SegReader *pSeg = 0;
135337
135338       /* Read the values returned by the SELECT into local variables. */
135339       sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
135340       sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
135341       sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
135342       int nRoot = sqlite3_column_bytes(pStmt, 4);
135343       char const *zRoot = sqlite3_column_blob(pStmt, 4);
135344
135345       /* If zTerm is not NULL, and this segment is not stored entirely on its
135346       ** root node, the range of leaves scanned can be reduced. Do this. */
135347       if( iStartBlock && zTerm ){
135348         sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
135349         rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
135350         if( rc!=SQLITE_OK ) goto finished;
135351         if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
135352       }
135353  
135354       rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1, 
135355           (isPrefix==0 && isScan==0),
135356           iStartBlock, iLeavesEndBlock, 
135357           iEndBlock, zRoot, nRoot, &pSeg
135358       );
135359       if( rc!=SQLITE_OK ) goto finished;
135360       rc = fts3SegReaderCursorAppend(pCsr, pSeg);
135361     }
135362   }
135363
135364  finished:
135365   rc2 = sqlite3_reset(pStmt);
135366   if( rc==SQLITE_DONE ) rc = rc2;
135367
135368   return rc;
135369 }
135370
135371 /*
135372 ** Set up a cursor object for iterating through a full-text index or a 
135373 ** single level therein.
135374 */
135375 SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
135376   Fts3Table *p,                   /* FTS3 table handle */
135377   int iLangid,                    /* Language-id to search */
135378   int iIndex,                     /* Index to search (from 0 to p->nIndex-1) */
135379   int iLevel,                     /* Level of segments to scan */
135380   const char *zTerm,              /* Term to query for */
135381   int nTerm,                      /* Size of zTerm in bytes */
135382   int isPrefix,                   /* True for a prefix search */
135383   int isScan,                     /* True to scan from zTerm to EOF */
135384   Fts3MultiSegReader *pCsr       /* Cursor object to populate */
135385 ){
135386   assert( iIndex>=0 && iIndex<p->nIndex );
135387   assert( iLevel==FTS3_SEGCURSOR_ALL
135388       ||  iLevel==FTS3_SEGCURSOR_PENDING 
135389       ||  iLevel>=0
135390   );
135391   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
135392   assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
135393   assert( isPrefix==0 || isScan==0 );
135394
135395   memset(pCsr, 0, sizeof(Fts3MultiSegReader));
135396   return fts3SegReaderCursor(
135397       p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
135398   );
135399 }
135400
135401 /*
135402 ** In addition to its current configuration, have the Fts3MultiSegReader
135403 ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
135404 **
135405 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
135406 */
135407 static int fts3SegReaderCursorAddZero(
135408   Fts3Table *p,                   /* FTS virtual table handle */
135409   int iLangid,
135410   const char *zTerm,              /* Term to scan doclist of */
135411   int nTerm,                      /* Number of bytes in zTerm */
135412   Fts3MultiSegReader *pCsr        /* Fts3MultiSegReader to modify */
135413 ){
135414   return fts3SegReaderCursor(p, 
135415       iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
135416   );
135417 }
135418
135419 /*
135420 ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
135421 ** if isPrefix is true, to scan the doclist for all terms for which 
135422 ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
135423 ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
135424 ** an SQLite error code.
135425 **
135426 ** It is the responsibility of the caller to free this object by eventually
135427 ** passing it to fts3SegReaderCursorFree() 
135428 **
135429 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
135430 ** Output parameter *ppSegcsr is set to 0 if an error occurs.
135431 */
135432 static int fts3TermSegReaderCursor(
135433   Fts3Cursor *pCsr,               /* Virtual table cursor handle */
135434   const char *zTerm,              /* Term to query for */
135435   int nTerm,                      /* Size of zTerm in bytes */
135436   int isPrefix,                   /* True for a prefix search */
135437   Fts3MultiSegReader **ppSegcsr   /* OUT: Allocated seg-reader cursor */
135438 ){
135439   Fts3MultiSegReader *pSegcsr;    /* Object to allocate and return */
135440   int rc = SQLITE_NOMEM;          /* Return code */
135441
135442   pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
135443   if( pSegcsr ){
135444     int i;
135445     int bFound = 0;               /* True once an index has been found */
135446     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
135447
135448     if( isPrefix ){
135449       for(i=1; bFound==0 && i<p->nIndex; i++){
135450         if( p->aIndex[i].nPrefix==nTerm ){
135451           bFound = 1;
135452           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
135453               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
135454           );
135455           pSegcsr->bLookup = 1;
135456         }
135457       }
135458
135459       for(i=1; bFound==0 && i<p->nIndex; i++){
135460         if( p->aIndex[i].nPrefix==nTerm+1 ){
135461           bFound = 1;
135462           rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
135463               i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
135464           );
135465           if( rc==SQLITE_OK ){
135466             rc = fts3SegReaderCursorAddZero(
135467                 p, pCsr->iLangid, zTerm, nTerm, pSegcsr
135468             );
135469           }
135470         }
135471       }
135472     }
135473
135474     if( bFound==0 ){
135475       rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid, 
135476           0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
135477       );
135478       pSegcsr->bLookup = !isPrefix;
135479     }
135480   }
135481
135482   *ppSegcsr = pSegcsr;
135483   return rc;
135484 }
135485
135486 /*
135487 ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
135488 */
135489 static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
135490   sqlite3Fts3SegReaderFinish(pSegcsr);
135491   sqlite3_free(pSegcsr);
135492 }
135493
135494 /*
135495 ** This function retrieves the doclist for the specified term (or term
135496 ** prefix) from the database.
135497 */
135498 static int fts3TermSelect(
135499   Fts3Table *p,                   /* Virtual table handle */
135500   Fts3PhraseToken *pTok,          /* Token to query for */
135501   int iColumn,                    /* Column to query (or -ve for all columns) */
135502   int *pnOut,                     /* OUT: Size of buffer at *ppOut */
135503   char **ppOut                    /* OUT: Malloced result buffer */
135504 ){
135505   int rc;                         /* Return code */
135506   Fts3MultiSegReader *pSegcsr;    /* Seg-reader cursor for this term */
135507   TermSelect tsc;                 /* Object for pair-wise doclist merging */
135508   Fts3SegFilter filter;           /* Segment term filter configuration */
135509
135510   pSegcsr = pTok->pSegcsr;
135511   memset(&tsc, 0, sizeof(TermSelect));
135512
135513   filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
135514         | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
135515         | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
135516         | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
135517   filter.iCol = iColumn;
135518   filter.zTerm = pTok->z;
135519   filter.nTerm = pTok->n;
135520
135521   rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
135522   while( SQLITE_OK==rc
135523       && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr)) 
135524   ){
135525     rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
135526   }
135527
135528   if( rc==SQLITE_OK ){
135529     rc = fts3TermSelectFinishMerge(p, &tsc);
135530   }
135531   if( rc==SQLITE_OK ){
135532     *ppOut = tsc.aaOutput[0];
135533     *pnOut = tsc.anOutput[0];
135534   }else{
135535     int i;
135536     for(i=0; i<SizeofArray(tsc.aaOutput); i++){
135537       sqlite3_free(tsc.aaOutput[i]);
135538     }
135539   }
135540
135541   fts3SegReaderCursorFree(pSegcsr);
135542   pTok->pSegcsr = 0;
135543   return rc;
135544 }
135545
135546 /*
135547 ** This function counts the total number of docids in the doclist stored
135548 ** in buffer aList[], size nList bytes.
135549 **
135550 ** If the isPoslist argument is true, then it is assumed that the doclist
135551 ** contains a position-list following each docid. Otherwise, it is assumed
135552 ** that the doclist is simply a list of docids stored as delta encoded 
135553 ** varints.
135554 */
135555 static int fts3DoclistCountDocids(char *aList, int nList){
135556   int nDoc = 0;                   /* Return value */
135557   if( aList ){
135558     char *aEnd = &aList[nList];   /* Pointer to one byte after EOF */
135559     char *p = aList;              /* Cursor */
135560     while( p<aEnd ){
135561       nDoc++;
135562       while( (*p++)&0x80 );     /* Skip docid varint */
135563       fts3PoslistCopy(0, &p);   /* Skip over position list */
135564     }
135565   }
135566
135567   return nDoc;
135568 }
135569
135570 /*
135571 ** Advance the cursor to the next row in the %_content table that
135572 ** matches the search criteria.  For a MATCH search, this will be
135573 ** the next row that matches. For a full-table scan, this will be
135574 ** simply the next row in the %_content table.  For a docid lookup,
135575 ** this routine simply sets the EOF flag.
135576 **
135577 ** Return SQLITE_OK if nothing goes wrong.  SQLITE_OK is returned
135578 ** even if we reach end-of-file.  The fts3EofMethod() will be called
135579 ** subsequently to determine whether or not an EOF was hit.
135580 */
135581 static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
135582   int rc;
135583   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
135584   if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
135585     if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
135586       pCsr->isEof = 1;
135587       rc = sqlite3_reset(pCsr->pStmt);
135588     }else{
135589       pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
135590       rc = SQLITE_OK;
135591     }
135592   }else{
135593     rc = fts3EvalNext((Fts3Cursor *)pCursor);
135594   }
135595   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
135596   return rc;
135597 }
135598
135599 /*
135600 ** The following are copied from sqliteInt.h.
135601 **
135602 ** Constants for the largest and smallest possible 64-bit signed integers.
135603 ** These macros are designed to work correctly on both 32-bit and 64-bit
135604 ** compilers.
135605 */
135606 #ifndef SQLITE_AMALGAMATION
135607 # define LARGEST_INT64  (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
135608 # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
135609 #endif
135610
135611 /*
135612 ** If the numeric type of argument pVal is "integer", then return it
135613 ** converted to a 64-bit signed integer. Otherwise, return a copy of
135614 ** the second parameter, iDefault.
135615 */
135616 static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
135617   if( pVal ){
135618     int eType = sqlite3_value_numeric_type(pVal);
135619     if( eType==SQLITE_INTEGER ){
135620       return sqlite3_value_int64(pVal);
135621     }
135622   }
135623   return iDefault;
135624 }
135625
135626 /*
135627 ** This is the xFilter interface for the virtual table.  See
135628 ** the virtual table xFilter method documentation for additional
135629 ** information.
135630 **
135631 ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
135632 ** the %_content table.
135633 **
135634 ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
135635 ** in the %_content table.
135636 **
135637 ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index.  The
135638 ** column on the left-hand side of the MATCH operator is column
135639 ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed.  argv[0] is the right-hand
135640 ** side of the MATCH operator.
135641 */
135642 static int fts3FilterMethod(
135643   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
135644   int idxNum,                     /* Strategy index */
135645   const char *idxStr,             /* Unused */
135646   int nVal,                       /* Number of elements in apVal */
135647   sqlite3_value **apVal           /* Arguments for the indexing scheme */
135648 ){
135649   int rc = SQLITE_OK;
135650   char *zSql;                     /* SQL statement used to access %_content */
135651   int eSearch;
135652   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
135653   Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
135654
135655   sqlite3_value *pCons = 0;       /* The MATCH or rowid constraint, if any */
135656   sqlite3_value *pLangid = 0;     /* The "langid = ?" constraint, if any */
135657   sqlite3_value *pDocidGe = 0;    /* The "docid >= ?" constraint, if any */
135658   sqlite3_value *pDocidLe = 0;    /* The "docid <= ?" constraint, if any */
135659   int iIdx;
135660
135661   UNUSED_PARAMETER(idxStr);
135662   UNUSED_PARAMETER(nVal);
135663
135664   eSearch = (idxNum & 0x0000FFFF);
135665   assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
135666   assert( p->pSegments==0 );
135667
135668   /* Collect arguments into local variables */
135669   iIdx = 0;
135670   if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
135671   if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
135672   if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
135673   if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
135674   assert( iIdx==nVal );
135675
135676   /* In case the cursor has been used before, clear it now. */
135677   sqlite3_finalize(pCsr->pStmt);
135678   sqlite3_free(pCsr->aDoclist);
135679   sqlite3_free(pCsr->aMatchinfo);
135680   sqlite3Fts3ExprFree(pCsr->pExpr);
135681   memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
135682
135683   /* Set the lower and upper bounds on docids to return */
135684   pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
135685   pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
135686
135687   if( idxStr ){
135688     pCsr->bDesc = (idxStr[0]=='D');
135689   }else{
135690     pCsr->bDesc = p->bDescIdx;
135691   }
135692   pCsr->eSearch = (i16)eSearch;
135693
135694   if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
135695     int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
135696     const char *zQuery = (const char *)sqlite3_value_text(pCons);
135697
135698     if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
135699       return SQLITE_NOMEM;
135700     }
135701
135702     pCsr->iLangid = 0;
135703     if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
135704
135705     assert( p->base.zErrMsg==0 );
135706     rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
135707         p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr, 
135708         &p->base.zErrMsg
135709     );
135710     if( rc!=SQLITE_OK ){
135711       return rc;
135712     }
135713
135714     rc = fts3EvalStart(pCsr);
135715     sqlite3Fts3SegmentsClose(p);
135716     if( rc!=SQLITE_OK ) return rc;
135717     pCsr->pNextId = pCsr->aDoclist;
135718     pCsr->iPrevId = 0;
135719   }
135720
135721   /* Compile a SELECT statement for this cursor. For a full-table-scan, the
135722   ** statement loops through all rows of the %_content table. For a
135723   ** full-text query or docid lookup, the statement retrieves a single
135724   ** row by docid.
135725   */
135726   if( eSearch==FTS3_FULLSCAN_SEARCH ){
135727     if( pDocidGe || pDocidLe ){
135728       zSql = sqlite3_mprintf(
135729           "SELECT %s WHERE rowid BETWEEN %lld AND %lld ORDER BY rowid %s",
135730           p->zReadExprlist, pCsr->iMinDocid, pCsr->iMaxDocid,
135731           (pCsr->bDesc ? "DESC" : "ASC")
135732       );
135733     }else{
135734       zSql = sqlite3_mprintf("SELECT %s ORDER BY rowid %s", 
135735           p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
135736       );
135737     }
135738     if( zSql ){
135739       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
135740       sqlite3_free(zSql);
135741     }else{
135742       rc = SQLITE_NOMEM;
135743     }
135744   }else if( eSearch==FTS3_DOCID_SEARCH ){
135745     rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
135746     if( rc==SQLITE_OK ){
135747       rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
135748     }
135749   }
135750   if( rc!=SQLITE_OK ) return rc;
135751
135752   return fts3NextMethod(pCursor);
135753 }
135754
135755 /* 
135756 ** This is the xEof method of the virtual table. SQLite calls this 
135757 ** routine to find out if it has reached the end of a result set.
135758 */
135759 static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
135760   return ((Fts3Cursor *)pCursor)->isEof;
135761 }
135762
135763 /* 
135764 ** This is the xRowid method. The SQLite core calls this routine to
135765 ** retrieve the rowid for the current row of the result set. fts3
135766 ** exposes %_content.docid as the rowid for the virtual table. The
135767 ** rowid should be written to *pRowid.
135768 */
135769 static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
135770   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
135771   *pRowid = pCsr->iPrevId;
135772   return SQLITE_OK;
135773 }
135774
135775 /* 
135776 ** This is the xColumn method, called by SQLite to request a value from
135777 ** the row that the supplied cursor currently points to.
135778 **
135779 ** If:
135780 **
135781 **   (iCol <  p->nColumn)   -> The value of the iCol'th user column.
135782 **   (iCol == p->nColumn)   -> Magic column with the same name as the table.
135783 **   (iCol == p->nColumn+1) -> Docid column
135784 **   (iCol == p->nColumn+2) -> Langid column
135785 */
135786 static int fts3ColumnMethod(
135787   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
135788   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
135789   int iCol                        /* Index of column to read value from */
135790 ){
135791   int rc = SQLITE_OK;             /* Return Code */
135792   Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
135793   Fts3Table *p = (Fts3Table *)pCursor->pVtab;
135794
135795   /* The column value supplied by SQLite must be in range. */
135796   assert( iCol>=0 && iCol<=p->nColumn+2 );
135797
135798   if( iCol==p->nColumn+1 ){
135799     /* This call is a request for the "docid" column. Since "docid" is an 
135800     ** alias for "rowid", use the xRowid() method to obtain the value.
135801     */
135802     sqlite3_result_int64(pCtx, pCsr->iPrevId);
135803   }else if( iCol==p->nColumn ){
135804     /* The extra column whose name is the same as the table.
135805     ** Return a blob which is a pointer to the cursor.  */
135806     sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
135807   }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
135808     sqlite3_result_int64(pCtx, pCsr->iLangid);
135809   }else{
135810     /* The requested column is either a user column (one that contains 
135811     ** indexed data), or the language-id column.  */
135812     rc = fts3CursorSeek(0, pCsr);
135813
135814     if( rc==SQLITE_OK ){
135815       if( iCol==p->nColumn+2 ){
135816         int iLangid = 0;
135817         if( p->zLanguageid ){
135818           iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
135819         }
135820         sqlite3_result_int(pCtx, iLangid);
135821       }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
135822         sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
135823       }
135824     }
135825   }
135826
135827   assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
135828   return rc;
135829 }
135830
135831 /* 
135832 ** This function is the implementation of the xUpdate callback used by 
135833 ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
135834 ** inserted, updated or deleted.
135835 */
135836 static int fts3UpdateMethod(
135837   sqlite3_vtab *pVtab,            /* Virtual table handle */
135838   int nArg,                       /* Size of argument array */
135839   sqlite3_value **apVal,          /* Array of arguments */
135840   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
135841 ){
135842   return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
135843 }
135844
135845 /*
135846 ** Implementation of xSync() method. Flush the contents of the pending-terms
135847 ** hash-table to the database.
135848 */
135849 static int fts3SyncMethod(sqlite3_vtab *pVtab){
135850
135851   /* Following an incremental-merge operation, assuming that the input
135852   ** segments are not completely consumed (the usual case), they are updated
135853   ** in place to remove the entries that have already been merged. This
135854   ** involves updating the leaf block that contains the smallest unmerged
135855   ** entry and each block (if any) between the leaf and the root node. So
135856   ** if the height of the input segment b-trees is N, and input segments
135857   ** are merged eight at a time, updating the input segments at the end
135858   ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
135859   ** small - often between 0 and 2. So the overhead of the incremental
135860   ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
135861   ** dwarfing the actual productive work accomplished, the incremental merge
135862   ** is only attempted if it will write at least 64 leaf blocks. Hence
135863   ** nMinMerge.
135864   **
135865   ** Of course, updating the input segments also involves deleting a bunch
135866   ** of blocks from the segments table. But this is not considered overhead
135867   ** as it would also be required by a crisis-merge that used the same input 
135868   ** segments.
135869   */
135870   const u32 nMinMerge = 64;       /* Minimum amount of incr-merge work to do */
135871
135872   Fts3Table *p = (Fts3Table*)pVtab;
135873   int rc = sqlite3Fts3PendingTermsFlush(p);
135874
135875   if( rc==SQLITE_OK 
135876    && p->nLeafAdd>(nMinMerge/16) 
135877    && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
135878   ){
135879     int mxLevel = 0;              /* Maximum relative level value in db */
135880     int A;                        /* Incr-merge parameter A */
135881
135882     rc = sqlite3Fts3MaxLevel(p, &mxLevel);
135883     assert( rc==SQLITE_OK || mxLevel==0 );
135884     A = p->nLeafAdd * mxLevel;
135885     A += (A/2);
135886     if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
135887   }
135888   sqlite3Fts3SegmentsClose(p);
135889   return rc;
135890 }
135891
135892 /*
135893 ** If it is currently unknown whether or not the FTS table has an %_stat
135894 ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
135895 ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
135896 ** if an error occurs.
135897 */
135898 static int fts3SetHasStat(Fts3Table *p){
135899   int rc = SQLITE_OK;
135900   if( p->bHasStat==2 ){
135901     const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
135902     char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName);
135903     if( zSql ){
135904       sqlite3_stmt *pStmt = 0;
135905       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
135906       if( rc==SQLITE_OK ){
135907         int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW);
135908         rc = sqlite3_finalize(pStmt);
135909         if( rc==SQLITE_OK ) p->bHasStat = bHasStat;
135910       }
135911       sqlite3_free(zSql);
135912     }else{
135913       rc = SQLITE_NOMEM;
135914     }
135915   }
135916   return rc;
135917 }
135918
135919 /*
135920 ** Implementation of xBegin() method. 
135921 */
135922 static int fts3BeginMethod(sqlite3_vtab *pVtab){
135923   Fts3Table *p = (Fts3Table*)pVtab;
135924   UNUSED_PARAMETER(pVtab);
135925   assert( p->pSegments==0 );
135926   assert( p->nPendingData==0 );
135927   assert( p->inTransaction!=1 );
135928   TESTONLY( p->inTransaction = 1 );
135929   TESTONLY( p->mxSavepoint = -1; );
135930   p->nLeafAdd = 0;
135931   return fts3SetHasStat(p);
135932 }
135933
135934 /*
135935 ** Implementation of xCommit() method. This is a no-op. The contents of
135936 ** the pending-terms hash-table have already been flushed into the database
135937 ** by fts3SyncMethod().
135938 */
135939 static int fts3CommitMethod(sqlite3_vtab *pVtab){
135940   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
135941   UNUSED_PARAMETER(pVtab);
135942   assert( p->nPendingData==0 );
135943   assert( p->inTransaction!=0 );
135944   assert( p->pSegments==0 );
135945   TESTONLY( p->inTransaction = 0 );
135946   TESTONLY( p->mxSavepoint = -1; );
135947   return SQLITE_OK;
135948 }
135949
135950 /*
135951 ** Implementation of xRollback(). Discard the contents of the pending-terms
135952 ** hash-table. Any changes made to the database are reverted by SQLite.
135953 */
135954 static int fts3RollbackMethod(sqlite3_vtab *pVtab){
135955   Fts3Table *p = (Fts3Table*)pVtab;
135956   sqlite3Fts3PendingTermsClear(p);
135957   assert( p->inTransaction!=0 );
135958   TESTONLY( p->inTransaction = 0 );
135959   TESTONLY( p->mxSavepoint = -1; );
135960   return SQLITE_OK;
135961 }
135962
135963 /*
135964 ** When called, *ppPoslist must point to the byte immediately following the
135965 ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
135966 ** moves *ppPoslist so that it instead points to the first byte of the
135967 ** same position list.
135968 */
135969 static void fts3ReversePoslist(char *pStart, char **ppPoslist){
135970   char *p = &(*ppPoslist)[-2];
135971   char c = 0;
135972
135973   while( p>pStart && (c=*p--)==0 );
135974   while( p>pStart && (*p & 0x80) | c ){ 
135975     c = *p--; 
135976   }
135977   if( p>pStart ){ p = &p[2]; }
135978   while( *p++&0x80 );
135979   *ppPoslist = p;
135980 }
135981
135982 /*
135983 ** Helper function used by the implementation of the overloaded snippet(),
135984 ** offsets() and optimize() SQL functions.
135985 **
135986 ** If the value passed as the third argument is a blob of size
135987 ** sizeof(Fts3Cursor*), then the blob contents are copied to the 
135988 ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
135989 ** message is written to context pContext and SQLITE_ERROR returned. The
135990 ** string passed via zFunc is used as part of the error message.
135991 */
135992 static int fts3FunctionArg(
135993   sqlite3_context *pContext,      /* SQL function call context */
135994   const char *zFunc,              /* Function name */
135995   sqlite3_value *pVal,            /* argv[0] passed to function */
135996   Fts3Cursor **ppCsr              /* OUT: Store cursor handle here */
135997 ){
135998   Fts3Cursor *pRet;
135999   if( sqlite3_value_type(pVal)!=SQLITE_BLOB 
136000    || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
136001   ){
136002     char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
136003     sqlite3_result_error(pContext, zErr, -1);
136004     sqlite3_free(zErr);
136005     return SQLITE_ERROR;
136006   }
136007   memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
136008   *ppCsr = pRet;
136009   return SQLITE_OK;
136010 }
136011
136012 /*
136013 ** Implementation of the snippet() function for FTS3
136014 */
136015 static void fts3SnippetFunc(
136016   sqlite3_context *pContext,      /* SQLite function call context */
136017   int nVal,                       /* Size of apVal[] array */
136018   sqlite3_value **apVal           /* Array of arguments */
136019 ){
136020   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
136021   const char *zStart = "<b>";
136022   const char *zEnd = "</b>";
136023   const char *zEllipsis = "<b>...</b>";
136024   int iCol = -1;
136025   int nToken = 15;                /* Default number of tokens in snippet */
136026
136027   /* There must be at least one argument passed to this function (otherwise
136028   ** the non-overloaded version would have been called instead of this one).
136029   */
136030   assert( nVal>=1 );
136031
136032   if( nVal>6 ){
136033     sqlite3_result_error(pContext, 
136034         "wrong number of arguments to function snippet()", -1);
136035     return;
136036   }
136037   if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
136038
136039   switch( nVal ){
136040     case 6: nToken = sqlite3_value_int(apVal[5]);
136041     case 5: iCol = sqlite3_value_int(apVal[4]);
136042     case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
136043     case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
136044     case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
136045   }
136046   if( !zEllipsis || !zEnd || !zStart ){
136047     sqlite3_result_error_nomem(pContext);
136048   }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
136049     sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
136050   }
136051 }
136052
136053 /*
136054 ** Implementation of the offsets() function for FTS3
136055 */
136056 static void fts3OffsetsFunc(
136057   sqlite3_context *pContext,      /* SQLite function call context */
136058   int nVal,                       /* Size of argument array */
136059   sqlite3_value **apVal           /* Array of arguments */
136060 ){
136061   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
136062
136063   UNUSED_PARAMETER(nVal);
136064
136065   assert( nVal==1 );
136066   if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
136067   assert( pCsr );
136068   if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
136069     sqlite3Fts3Offsets(pContext, pCsr);
136070   }
136071 }
136072
136073 /* 
136074 ** Implementation of the special optimize() function for FTS3. This 
136075 ** function merges all segments in the database to a single segment.
136076 ** Example usage is:
136077 **
136078 **   SELECT optimize(t) FROM t LIMIT 1;
136079 **
136080 ** where 't' is the name of an FTS3 table.
136081 */
136082 static void fts3OptimizeFunc(
136083   sqlite3_context *pContext,      /* SQLite function call context */
136084   int nVal,                       /* Size of argument array */
136085   sqlite3_value **apVal           /* Array of arguments */
136086 ){
136087   int rc;                         /* Return code */
136088   Fts3Table *p;                   /* Virtual table handle */
136089   Fts3Cursor *pCursor;            /* Cursor handle passed through apVal[0] */
136090
136091   UNUSED_PARAMETER(nVal);
136092
136093   assert( nVal==1 );
136094   if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
136095   p = (Fts3Table *)pCursor->base.pVtab;
136096   assert( p );
136097
136098   rc = sqlite3Fts3Optimize(p);
136099
136100   switch( rc ){
136101     case SQLITE_OK:
136102       sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
136103       break;
136104     case SQLITE_DONE:
136105       sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
136106       break;
136107     default:
136108       sqlite3_result_error_code(pContext, rc);
136109       break;
136110   }
136111 }
136112
136113 /*
136114 ** Implementation of the matchinfo() function for FTS3
136115 */
136116 static void fts3MatchinfoFunc(
136117   sqlite3_context *pContext,      /* SQLite function call context */
136118   int nVal,                       /* Size of argument array */
136119   sqlite3_value **apVal           /* Array of arguments */
136120 ){
136121   Fts3Cursor *pCsr;               /* Cursor handle passed through apVal[0] */
136122   assert( nVal==1 || nVal==2 );
136123   if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
136124     const char *zArg = 0;
136125     if( nVal>1 ){
136126       zArg = (const char *)sqlite3_value_text(apVal[1]);
136127     }
136128     sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
136129   }
136130 }
136131
136132 /*
136133 ** This routine implements the xFindFunction method for the FTS3
136134 ** virtual table.
136135 */
136136 static int fts3FindFunctionMethod(
136137   sqlite3_vtab *pVtab,            /* Virtual table handle */
136138   int nArg,                       /* Number of SQL function arguments */
136139   const char *zName,              /* Name of SQL function */
136140   void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
136141   void **ppArg                    /* Unused */
136142 ){
136143   struct Overloaded {
136144     const char *zName;
136145     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
136146   } aOverload[] = {
136147     { "snippet", fts3SnippetFunc },
136148     { "offsets", fts3OffsetsFunc },
136149     { "optimize", fts3OptimizeFunc },
136150     { "matchinfo", fts3MatchinfoFunc },
136151   };
136152   int i;                          /* Iterator variable */
136153
136154   UNUSED_PARAMETER(pVtab);
136155   UNUSED_PARAMETER(nArg);
136156   UNUSED_PARAMETER(ppArg);
136157
136158   for(i=0; i<SizeofArray(aOverload); i++){
136159     if( strcmp(zName, aOverload[i].zName)==0 ){
136160       *pxFunc = aOverload[i].xFunc;
136161       return 1;
136162     }
136163   }
136164
136165   /* No function of the specified name was found. Return 0. */
136166   return 0;
136167 }
136168
136169 /*
136170 ** Implementation of FTS3 xRename method. Rename an fts3 table.
136171 */
136172 static int fts3RenameMethod(
136173   sqlite3_vtab *pVtab,            /* Virtual table handle */
136174   const char *zName               /* New name of table */
136175 ){
136176   Fts3Table *p = (Fts3Table *)pVtab;
136177   sqlite3 *db = p->db;            /* Database connection */
136178   int rc;                         /* Return Code */
136179
136180   /* At this point it must be known if the %_stat table exists or not.
136181   ** So bHasStat may not be 2.  */
136182   rc = fts3SetHasStat(p);
136183   
136184   /* As it happens, the pending terms table is always empty here. This is
136185   ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction 
136186   ** always opens a savepoint transaction. And the xSavepoint() method 
136187   ** flushes the pending terms table. But leave the (no-op) call to
136188   ** PendingTermsFlush() in in case that changes.
136189   */
136190   assert( p->nPendingData==0 );
136191   if( rc==SQLITE_OK ){
136192     rc = sqlite3Fts3PendingTermsFlush(p);
136193   }
136194
136195   if( p->zContentTbl==0 ){
136196     fts3DbExec(&rc, db,
136197       "ALTER TABLE %Q.'%q_content'  RENAME TO '%q_content';",
136198       p->zDb, p->zName, zName
136199     );
136200   }
136201
136202   if( p->bHasDocsize ){
136203     fts3DbExec(&rc, db,
136204       "ALTER TABLE %Q.'%q_docsize'  RENAME TO '%q_docsize';",
136205       p->zDb, p->zName, zName
136206     );
136207   }
136208   if( p->bHasStat ){
136209     fts3DbExec(&rc, db,
136210       "ALTER TABLE %Q.'%q_stat'  RENAME TO '%q_stat';",
136211       p->zDb, p->zName, zName
136212     );
136213   }
136214   fts3DbExec(&rc, db,
136215     "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
136216     p->zDb, p->zName, zName
136217   );
136218   fts3DbExec(&rc, db,
136219     "ALTER TABLE %Q.'%q_segdir'   RENAME TO '%q_segdir';",
136220     p->zDb, p->zName, zName
136221   );
136222   return rc;
136223 }
136224
136225 /*
136226 ** The xSavepoint() method.
136227 **
136228 ** Flush the contents of the pending-terms table to disk.
136229 */
136230 static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
136231   int rc = SQLITE_OK;
136232   UNUSED_PARAMETER(iSavepoint);
136233   assert( ((Fts3Table *)pVtab)->inTransaction );
136234   assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
136235   TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
136236   if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
136237     rc = fts3SyncMethod(pVtab);
136238   }
136239   return rc;
136240 }
136241
136242 /*
136243 ** The xRelease() method.
136244 **
136245 ** This is a no-op.
136246 */
136247 static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
136248   TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
136249   UNUSED_PARAMETER(iSavepoint);
136250   UNUSED_PARAMETER(pVtab);
136251   assert( p->inTransaction );
136252   assert( p->mxSavepoint >= iSavepoint );
136253   TESTONLY( p->mxSavepoint = iSavepoint-1 );
136254   return SQLITE_OK;
136255 }
136256
136257 /*
136258 ** The xRollbackTo() method.
136259 **
136260 ** Discard the contents of the pending terms table.
136261 */
136262 static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
136263   Fts3Table *p = (Fts3Table*)pVtab;
136264   UNUSED_PARAMETER(iSavepoint);
136265   assert( p->inTransaction );
136266   assert( p->mxSavepoint >= iSavepoint );
136267   TESTONLY( p->mxSavepoint = iSavepoint );
136268   sqlite3Fts3PendingTermsClear(p);
136269   return SQLITE_OK;
136270 }
136271
136272 static const sqlite3_module fts3Module = {
136273   /* iVersion      */ 2,
136274   /* xCreate       */ fts3CreateMethod,
136275   /* xConnect      */ fts3ConnectMethod,
136276   /* xBestIndex    */ fts3BestIndexMethod,
136277   /* xDisconnect   */ fts3DisconnectMethod,
136278   /* xDestroy      */ fts3DestroyMethod,
136279   /* xOpen         */ fts3OpenMethod,
136280   /* xClose        */ fts3CloseMethod,
136281   /* xFilter       */ fts3FilterMethod,
136282   /* xNext         */ fts3NextMethod,
136283   /* xEof          */ fts3EofMethod,
136284   /* xColumn       */ fts3ColumnMethod,
136285   /* xRowid        */ fts3RowidMethod,
136286   /* xUpdate       */ fts3UpdateMethod,
136287   /* xBegin        */ fts3BeginMethod,
136288   /* xSync         */ fts3SyncMethod,
136289   /* xCommit       */ fts3CommitMethod,
136290   /* xRollback     */ fts3RollbackMethod,
136291   /* xFindFunction */ fts3FindFunctionMethod,
136292   /* xRename */       fts3RenameMethod,
136293   /* xSavepoint    */ fts3SavepointMethod,
136294   /* xRelease      */ fts3ReleaseMethod,
136295   /* xRollbackTo   */ fts3RollbackToMethod,
136296 };
136297
136298 /*
136299 ** This function is registered as the module destructor (called when an
136300 ** FTS3 enabled database connection is closed). It frees the memory
136301 ** allocated for the tokenizer hash table.
136302 */
136303 static void hashDestroy(void *p){
136304   Fts3Hash *pHash = (Fts3Hash *)p;
136305   sqlite3Fts3HashClear(pHash);
136306   sqlite3_free(pHash);
136307 }
136308
136309 /*
136310 ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are 
136311 ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
136312 ** respectively. The following three forward declarations are for functions
136313 ** declared in these files used to retrieve the respective implementations.
136314 **
136315 ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
136316 ** to by the argument to point to the "simple" tokenizer implementation.
136317 ** And so on.
136318 */
136319 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
136320 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
136321 #ifndef SQLITE_DISABLE_FTS3_UNICODE
136322 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
136323 #endif
136324 #ifdef SQLITE_ENABLE_ICU
136325 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
136326 #endif
136327
136328 /*
136329 ** Initialize the fts3 extension. If this extension is built as part
136330 ** of the sqlite library, then this function is called directly by
136331 ** SQLite. If fts3 is built as a dynamically loadable extension, this
136332 ** function is called by the sqlite3_extension_init() entry point.
136333 */
136334 SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
136335   int rc = SQLITE_OK;
136336   Fts3Hash *pHash = 0;
136337   const sqlite3_tokenizer_module *pSimple = 0;
136338   const sqlite3_tokenizer_module *pPorter = 0;
136339 #ifndef SQLITE_DISABLE_FTS3_UNICODE
136340   const sqlite3_tokenizer_module *pUnicode = 0;
136341 #endif
136342
136343 #ifdef SQLITE_ENABLE_ICU
136344   const sqlite3_tokenizer_module *pIcu = 0;
136345   sqlite3Fts3IcuTokenizerModule(&pIcu);
136346 #endif
136347
136348 #ifndef SQLITE_DISABLE_FTS3_UNICODE
136349   sqlite3Fts3UnicodeTokenizer(&pUnicode);
136350 #endif
136351
136352 #ifdef SQLITE_TEST
136353   rc = sqlite3Fts3InitTerm(db);
136354   if( rc!=SQLITE_OK ) return rc;
136355 #endif
136356
136357   rc = sqlite3Fts3InitAux(db);
136358   if( rc!=SQLITE_OK ) return rc;
136359
136360   sqlite3Fts3SimpleTokenizerModule(&pSimple);
136361   sqlite3Fts3PorterTokenizerModule(&pPorter);
136362
136363   /* Allocate and initialize the hash-table used to store tokenizers. */
136364   pHash = sqlite3_malloc(sizeof(Fts3Hash));
136365   if( !pHash ){
136366     rc = SQLITE_NOMEM;
136367   }else{
136368     sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
136369   }
136370
136371   /* Load the built-in tokenizers into the hash table */
136372   if( rc==SQLITE_OK ){
136373     if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
136374      || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter) 
136375
136376 #ifndef SQLITE_DISABLE_FTS3_UNICODE
136377      || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode) 
136378 #endif
136379 #ifdef SQLITE_ENABLE_ICU
136380      || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
136381 #endif
136382     ){
136383       rc = SQLITE_NOMEM;
136384     }
136385   }
136386
136387 #ifdef SQLITE_TEST
136388   if( rc==SQLITE_OK ){
136389     rc = sqlite3Fts3ExprInitTestInterface(db);
136390   }
136391 #endif
136392
136393   /* Create the virtual table wrapper around the hash-table and overload 
136394   ** the two scalar functions. If this is successful, register the
136395   ** module with sqlite.
136396   */
136397   if( SQLITE_OK==rc 
136398    && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
136399    && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
136400    && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
136401    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
136402    && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
136403    && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
136404   ){
136405     rc = sqlite3_create_module_v2(
136406         db, "fts3", &fts3Module, (void *)pHash, hashDestroy
136407     );
136408     if( rc==SQLITE_OK ){
136409       rc = sqlite3_create_module_v2(
136410           db, "fts4", &fts3Module, (void *)pHash, 0
136411       );
136412     }
136413     if( rc==SQLITE_OK ){
136414       rc = sqlite3Fts3InitTok(db, (void *)pHash);
136415     }
136416     return rc;
136417   }
136418
136419
136420   /* An error has occurred. Delete the hash table and return the error code. */
136421   assert( rc!=SQLITE_OK );
136422   if( pHash ){
136423     sqlite3Fts3HashClear(pHash);
136424     sqlite3_free(pHash);
136425   }
136426   return rc;
136427 }
136428
136429 /*
136430 ** Allocate an Fts3MultiSegReader for each token in the expression headed
136431 ** by pExpr. 
136432 **
136433 ** An Fts3SegReader object is a cursor that can seek or scan a range of
136434 ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
136435 ** Fts3SegReader objects internally to provide an interface to seek or scan
136436 ** within the union of all segments of a b-tree. Hence the name.
136437 **
136438 ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
136439 ** segment b-tree (if the term is not a prefix or it is a prefix for which
136440 ** there exists prefix b-tree of the right length) then it may be traversed
136441 ** and merged incrementally. Otherwise, it has to be merged into an in-memory 
136442 ** doclist and then traversed.
136443 */
136444 static void fts3EvalAllocateReaders(
136445   Fts3Cursor *pCsr,               /* FTS cursor handle */
136446   Fts3Expr *pExpr,                /* Allocate readers for this expression */
136447   int *pnToken,                   /* OUT: Total number of tokens in phrase. */
136448   int *pnOr,                      /* OUT: Total number of OR nodes in expr. */
136449   int *pRc                        /* IN/OUT: Error code */
136450 ){
136451   if( pExpr && SQLITE_OK==*pRc ){
136452     if( pExpr->eType==FTSQUERY_PHRASE ){
136453       int i;
136454       int nToken = pExpr->pPhrase->nToken;
136455       *pnToken += nToken;
136456       for(i=0; i<nToken; i++){
136457         Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
136458         int rc = fts3TermSegReaderCursor(pCsr, 
136459             pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
136460         );
136461         if( rc!=SQLITE_OK ){
136462           *pRc = rc;
136463           return;
136464         }
136465       }
136466       assert( pExpr->pPhrase->iDoclistToken==0 );
136467       pExpr->pPhrase->iDoclistToken = -1;
136468     }else{
136469       *pnOr += (pExpr->eType==FTSQUERY_OR);
136470       fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
136471       fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
136472     }
136473   }
136474 }
136475
136476 /*
136477 ** Arguments pList/nList contain the doclist for token iToken of phrase p.
136478 ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
136479 **
136480 ** This function assumes that pList points to a buffer allocated using
136481 ** sqlite3_malloc(). This function takes responsibility for eventually
136482 ** freeing the buffer.
136483 **
136484 ** SQLITE_OK is returned if successful, or SQLITE_NOMEM if an error occurs.
136485 */
136486 static int fts3EvalPhraseMergeToken(
136487   Fts3Table *pTab,                /* FTS Table pointer */
136488   Fts3Phrase *p,                  /* Phrase to merge pList/nList into */
136489   int iToken,                     /* Token pList/nList corresponds to */
136490   char *pList,                    /* Pointer to doclist */
136491   int nList                       /* Number of bytes in pList */
136492 ){
136493   int rc = SQLITE_OK;
136494   assert( iToken!=p->iDoclistToken );
136495
136496   if( pList==0 ){
136497     sqlite3_free(p->doclist.aAll);
136498     p->doclist.aAll = 0;
136499     p->doclist.nAll = 0;
136500   }
136501
136502   else if( p->iDoclistToken<0 ){
136503     p->doclist.aAll = pList;
136504     p->doclist.nAll = nList;
136505   }
136506
136507   else if( p->doclist.aAll==0 ){
136508     sqlite3_free(pList);
136509   }
136510
136511   else {
136512     char *pLeft;
136513     char *pRight;
136514     int nLeft;
136515     int nRight;
136516     int nDiff;
136517
136518     if( p->iDoclistToken<iToken ){
136519       pLeft = p->doclist.aAll;
136520       nLeft = p->doclist.nAll;
136521       pRight = pList;
136522       nRight = nList;
136523       nDiff = iToken - p->iDoclistToken;
136524     }else{
136525       pRight = p->doclist.aAll;
136526       nRight = p->doclist.nAll;
136527       pLeft = pList;
136528       nLeft = nList;
136529       nDiff = p->iDoclistToken - iToken;
136530     }
136531
136532     rc = fts3DoclistPhraseMerge(
136533         pTab->bDescIdx, nDiff, pLeft, nLeft, &pRight, &nRight
136534     );
136535     sqlite3_free(pLeft);
136536     p->doclist.aAll = pRight;
136537     p->doclist.nAll = nRight;
136538   }
136539
136540   if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
136541   return rc;
136542 }
136543
136544 /*
136545 ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
136546 ** does not take deferred tokens into account.
136547 **
136548 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
136549 */
136550 static int fts3EvalPhraseLoad(
136551   Fts3Cursor *pCsr,               /* FTS Cursor handle */
136552   Fts3Phrase *p                   /* Phrase object */
136553 ){
136554   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
136555   int iToken;
136556   int rc = SQLITE_OK;
136557
136558   for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
136559     Fts3PhraseToken *pToken = &p->aToken[iToken];
136560     assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
136561
136562     if( pToken->pSegcsr ){
136563       int nThis = 0;
136564       char *pThis = 0;
136565       rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
136566       if( rc==SQLITE_OK ){
136567         rc = fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
136568       }
136569     }
136570     assert( pToken->pSegcsr==0 );
136571   }
136572
136573   return rc;
136574 }
136575
136576 /*
136577 ** This function is called on each phrase after the position lists for
136578 ** any deferred tokens have been loaded into memory. It updates the phrases
136579 ** current position list to include only those positions that are really
136580 ** instances of the phrase (after considering deferred tokens). If this
136581 ** means that the phrase does not appear in the current row, doclist.pList
136582 ** and doclist.nList are both zeroed.
136583 **
136584 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
136585 */
136586 static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
136587   int iToken;                     /* Used to iterate through phrase tokens */
136588   char *aPoslist = 0;             /* Position list for deferred tokens */
136589   int nPoslist = 0;               /* Number of bytes in aPoslist */
136590   int iPrev = -1;                 /* Token number of previous deferred token */
136591
136592   assert( pPhrase->doclist.bFreeList==0 );
136593
136594   for(iToken=0; iToken<pPhrase->nToken; iToken++){
136595     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
136596     Fts3DeferredToken *pDeferred = pToken->pDeferred;
136597
136598     if( pDeferred ){
136599       char *pList;
136600       int nList;
136601       int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
136602       if( rc!=SQLITE_OK ) return rc;
136603
136604       if( pList==0 ){
136605         sqlite3_free(aPoslist);
136606         pPhrase->doclist.pList = 0;
136607         pPhrase->doclist.nList = 0;
136608         return SQLITE_OK;
136609
136610       }else if( aPoslist==0 ){
136611         aPoslist = pList;
136612         nPoslist = nList;
136613
136614       }else{
136615         char *aOut = pList;
136616         char *p1 = aPoslist;
136617         char *p2 = aOut;
136618
136619         assert( iPrev>=0 );
136620         fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
136621         sqlite3_free(aPoslist);
136622         aPoslist = pList;
136623         nPoslist = (int)(aOut - aPoslist);
136624         if( nPoslist==0 ){
136625           sqlite3_free(aPoslist);
136626           pPhrase->doclist.pList = 0;
136627           pPhrase->doclist.nList = 0;
136628           return SQLITE_OK;
136629         }
136630       }
136631       iPrev = iToken;
136632     }
136633   }
136634
136635   if( iPrev>=0 ){
136636     int nMaxUndeferred = pPhrase->iDoclistToken;
136637     if( nMaxUndeferred<0 ){
136638       pPhrase->doclist.pList = aPoslist;
136639       pPhrase->doclist.nList = nPoslist;
136640       pPhrase->doclist.iDocid = pCsr->iPrevId;
136641       pPhrase->doclist.bFreeList = 1;
136642     }else{
136643       int nDistance;
136644       char *p1;
136645       char *p2;
136646       char *aOut;
136647
136648       if( nMaxUndeferred>iPrev ){
136649         p1 = aPoslist;
136650         p2 = pPhrase->doclist.pList;
136651         nDistance = nMaxUndeferred - iPrev;
136652       }else{
136653         p1 = pPhrase->doclist.pList;
136654         p2 = aPoslist;
136655         nDistance = iPrev - nMaxUndeferred;
136656       }
136657
136658       aOut = (char *)sqlite3_malloc(nPoslist+8);
136659       if( !aOut ){
136660         sqlite3_free(aPoslist);
136661         return SQLITE_NOMEM;
136662       }
136663       
136664       pPhrase->doclist.pList = aOut;
136665       if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
136666         pPhrase->doclist.bFreeList = 1;
136667         pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
136668       }else{
136669         sqlite3_free(aOut);
136670         pPhrase->doclist.pList = 0;
136671         pPhrase->doclist.nList = 0;
136672       }
136673       sqlite3_free(aPoslist);
136674     }
136675   }
136676
136677   return SQLITE_OK;
136678 }
136679
136680 /*
136681 ** Maximum number of tokens a phrase may have to be considered for the
136682 ** incremental doclists strategy.
136683 */
136684 #define MAX_INCR_PHRASE_TOKENS 4
136685
136686 /*
136687 ** This function is called for each Fts3Phrase in a full-text query 
136688 ** expression to initialize the mechanism for returning rows. Once this
136689 ** function has been called successfully on an Fts3Phrase, it may be
136690 ** used with fts3EvalPhraseNext() to iterate through the matching docids.
136691 **
136692 ** If parameter bOptOk is true, then the phrase may (or may not) use the
136693 ** incremental loading strategy. Otherwise, the entire doclist is loaded into
136694 ** memory within this call.
136695 **
136696 ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
136697 */
136698 static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
136699   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
136700   int rc = SQLITE_OK;             /* Error code */
136701   int i;
136702
136703   /* Determine if doclists may be loaded from disk incrementally. This is
136704   ** possible if the bOptOk argument is true, the FTS doclists will be
136705   ** scanned in forward order, and the phrase consists of 
136706   ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
136707   ** tokens or prefix tokens that cannot use a prefix-index.  */
136708   int bHaveIncr = 0;
136709   int bIncrOk = (bOptOk 
136710    && pCsr->bDesc==pTab->bDescIdx 
136711    && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
136712    && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
136713 #ifdef SQLITE_TEST
136714    && pTab->bNoIncrDoclist==0
136715 #endif
136716   );
136717   for(i=0; bIncrOk==1 && i<p->nToken; i++){
136718     Fts3PhraseToken *pToken = &p->aToken[i];
136719     if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
136720       bIncrOk = 0;
136721     }
136722     if( pToken->pSegcsr ) bHaveIncr = 1;
136723   }
136724
136725   if( bIncrOk && bHaveIncr ){
136726     /* Use the incremental approach. */
136727     int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
136728     for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
136729       Fts3PhraseToken *pToken = &p->aToken[i];
136730       Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
136731       if( pSegcsr ){
136732         rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
136733       }
136734     }
136735     p->bIncr = 1;
136736   }else{
136737     /* Load the full doclist for the phrase into memory. */
136738     rc = fts3EvalPhraseLoad(pCsr, p);
136739     p->bIncr = 0;
136740   }
136741
136742   assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
136743   return rc;
136744 }
136745
136746 /*
136747 ** This function is used to iterate backwards (from the end to start) 
136748 ** through doclists. It is used by this module to iterate through phrase
136749 ** doclists in reverse and by the fts3_write.c module to iterate through
136750 ** pending-terms lists when writing to databases with "order=desc".
136751 **
136752 ** The doclist may be sorted in ascending (parameter bDescIdx==0) or 
136753 ** descending (parameter bDescIdx==1) order of docid. Regardless, this
136754 ** function iterates from the end of the doclist to the beginning.
136755 */
136756 SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
136757   int bDescIdx,                   /* True if the doclist is desc */
136758   char *aDoclist,                 /* Pointer to entire doclist */
136759   int nDoclist,                   /* Length of aDoclist in bytes */
136760   char **ppIter,                  /* IN/OUT: Iterator pointer */
136761   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
136762   int *pnList,                    /* OUT: List length pointer */
136763   u8 *pbEof                       /* OUT: End-of-file flag */
136764 ){
136765   char *p = *ppIter;
136766
136767   assert( nDoclist>0 );
136768   assert( *pbEof==0 );
136769   assert( p || *piDocid==0 );
136770   assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
136771
136772   if( p==0 ){
136773     sqlite3_int64 iDocid = 0;
136774     char *pNext = 0;
136775     char *pDocid = aDoclist;
136776     char *pEnd = &aDoclist[nDoclist];
136777     int iMul = 1;
136778
136779     while( pDocid<pEnd ){
136780       sqlite3_int64 iDelta;
136781       pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
136782       iDocid += (iMul * iDelta);
136783       pNext = pDocid;
136784       fts3PoslistCopy(0, &pDocid);
136785       while( pDocid<pEnd && *pDocid==0 ) pDocid++;
136786       iMul = (bDescIdx ? -1 : 1);
136787     }
136788
136789     *pnList = (int)(pEnd - pNext);
136790     *ppIter = pNext;
136791     *piDocid = iDocid;
136792   }else{
136793     int iMul = (bDescIdx ? -1 : 1);
136794     sqlite3_int64 iDelta;
136795     fts3GetReverseVarint(&p, aDoclist, &iDelta);
136796     *piDocid -= (iMul * iDelta);
136797
136798     if( p==aDoclist ){
136799       *pbEof = 1;
136800     }else{
136801       char *pSave = p;
136802       fts3ReversePoslist(aDoclist, &p);
136803       *pnList = (int)(pSave - p);
136804     }
136805     *ppIter = p;
136806   }
136807 }
136808
136809 /*
136810 ** Iterate forwards through a doclist.
136811 */
136812 SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
136813   int bDescIdx,                   /* True if the doclist is desc */
136814   char *aDoclist,                 /* Pointer to entire doclist */
136815   int nDoclist,                   /* Length of aDoclist in bytes */
136816   char **ppIter,                  /* IN/OUT: Iterator pointer */
136817   sqlite3_int64 *piDocid,         /* IN/OUT: Docid pointer */
136818   u8 *pbEof                       /* OUT: End-of-file flag */
136819 ){
136820   char *p = *ppIter;
136821
136822   assert( nDoclist>0 );
136823   assert( *pbEof==0 );
136824   assert( p || *piDocid==0 );
136825   assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
136826
136827   if( p==0 ){
136828     p = aDoclist;
136829     p += sqlite3Fts3GetVarint(p, piDocid);
136830   }else{
136831     fts3PoslistCopy(0, &p);
136832     if( p>=&aDoclist[nDoclist] ){
136833       *pbEof = 1;
136834     }else{
136835       sqlite3_int64 iVar;
136836       p += sqlite3Fts3GetVarint(p, &iVar);
136837       *piDocid += ((bDescIdx ? -1 : 1) * iVar);
136838     }
136839   }
136840
136841   *ppIter = p;
136842 }
136843
136844 /*
136845 ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
136846 ** to true if EOF is reached.
136847 */
136848 static void fts3EvalDlPhraseNext(
136849   Fts3Table *pTab,
136850   Fts3Doclist *pDL,
136851   u8 *pbEof
136852 ){
136853   char *pIter;                            /* Used to iterate through aAll */
136854   char *pEnd = &pDL->aAll[pDL->nAll];     /* 1 byte past end of aAll */
136855  
136856   if( pDL->pNextDocid ){
136857     pIter = pDL->pNextDocid;
136858   }else{
136859     pIter = pDL->aAll;
136860   }
136861
136862   if( pIter>=pEnd ){
136863     /* We have already reached the end of this doclist. EOF. */
136864     *pbEof = 1;
136865   }else{
136866     sqlite3_int64 iDelta;
136867     pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
136868     if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
136869       pDL->iDocid += iDelta;
136870     }else{
136871       pDL->iDocid -= iDelta;
136872     }
136873     pDL->pList = pIter;
136874     fts3PoslistCopy(0, &pIter);
136875     pDL->nList = (int)(pIter - pDL->pList);
136876
136877     /* pIter now points just past the 0x00 that terminates the position-
136878     ** list for document pDL->iDocid. However, if this position-list was
136879     ** edited in place by fts3EvalNearTrim(), then pIter may not actually
136880     ** point to the start of the next docid value. The following line deals
136881     ** with this case by advancing pIter past the zero-padding added by
136882     ** fts3EvalNearTrim().  */
136883     while( pIter<pEnd && *pIter==0 ) pIter++;
136884
136885     pDL->pNextDocid = pIter;
136886     assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
136887     *pbEof = 0;
136888   }
136889 }
136890
136891 /*
136892 ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
136893 */
136894 typedef struct TokenDoclist TokenDoclist;
136895 struct TokenDoclist {
136896   int bIgnore;
136897   sqlite3_int64 iDocid;
136898   char *pList;
136899   int nList;
136900 };
136901
136902 /*
136903 ** Token pToken is an incrementally loaded token that is part of a 
136904 ** multi-token phrase. Advance it to the next matching document in the
136905 ** database and populate output variable *p with the details of the new
136906 ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
136907 **
136908 ** If an error occurs, return an SQLite error code. Otherwise, return 
136909 ** SQLITE_OK.
136910 */
136911 static int incrPhraseTokenNext(
136912   Fts3Table *pTab,                /* Virtual table handle */
136913   Fts3Phrase *pPhrase,            /* Phrase to advance token of */
136914   int iToken,                     /* Specific token to advance */
136915   TokenDoclist *p,                /* OUT: Docid and doclist for new entry */
136916   u8 *pbEof                       /* OUT: True if iterator is at EOF */
136917 ){
136918   int rc = SQLITE_OK;
136919
136920   if( pPhrase->iDoclistToken==iToken ){
136921     assert( p->bIgnore==0 );
136922     assert( pPhrase->aToken[iToken].pSegcsr==0 );
136923     fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
136924     p->pList = pPhrase->doclist.pList;
136925     p->nList = pPhrase->doclist.nList;
136926     p->iDocid = pPhrase->doclist.iDocid;
136927   }else{
136928     Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
136929     assert( pToken->pDeferred==0 );
136930     assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
136931     if( pToken->pSegcsr ){
136932       assert( p->bIgnore==0 );
136933       rc = sqlite3Fts3MsrIncrNext(
136934           pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
136935       );
136936       if( p->pList==0 ) *pbEof = 1;
136937     }else{
136938       p->bIgnore = 1;
136939     }
136940   }
136941
136942   return rc;
136943 }
136944
136945
136946 /*
136947 ** The phrase iterator passed as the second argument:
136948 **
136949 **   * features at least one token that uses an incremental doclist, and 
136950 **
136951 **   * does not contain any deferred tokens.
136952 **
136953 ** Advance it to the next matching documnent in the database and populate
136954 ** the Fts3Doclist.pList and nList fields. 
136955 **
136956 ** If there is no "next" entry and no error occurs, then *pbEof is set to
136957 ** 1 before returning. Otherwise, if no error occurs and the iterator is
136958 ** successfully advanced, *pbEof is set to 0.
136959 **
136960 ** If an error occurs, return an SQLite error code. Otherwise, return 
136961 ** SQLITE_OK.
136962 */
136963 static int fts3EvalIncrPhraseNext(
136964   Fts3Cursor *pCsr,               /* FTS Cursor handle */
136965   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
136966   u8 *pbEof                       /* OUT: Set to 1 if EOF */
136967 ){
136968   int rc = SQLITE_OK;
136969   Fts3Doclist *pDL = &p->doclist;
136970   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
136971   u8 bEof = 0;
136972
136973   /* This is only called if it is guaranteed that the phrase has at least
136974   ** one incremental token. In which case the bIncr flag is set. */
136975   assert( p->bIncr==1 );
136976
136977   if( p->nToken==1 && p->bIncr ){
136978     rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr, 
136979         &pDL->iDocid, &pDL->pList, &pDL->nList
136980     );
136981     if( pDL->pList==0 ) bEof = 1;
136982   }else{
136983     int bDescDoclist = pCsr->bDesc;
136984     struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
136985
136986     memset(a, 0, sizeof(a));
136987     assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
136988     assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
136989
136990     while( bEof==0 ){
136991       int bMaxSet = 0;
136992       sqlite3_int64 iMax = 0;     /* Largest docid for all iterators */
136993       int i;                      /* Used to iterate through tokens */
136994
136995       /* Advance the iterator for each token in the phrase once. */
136996       for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
136997         rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
136998         if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
136999           iMax = a[i].iDocid;
137000           bMaxSet = 1;
137001         }
137002       }
137003       assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
137004       assert( rc!=SQLITE_OK || bMaxSet );
137005
137006       /* Keep advancing iterators until they all point to the same document */
137007       for(i=0; i<p->nToken; i++){
137008         while( rc==SQLITE_OK && bEof==0 
137009             && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0 
137010         ){
137011           rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
137012           if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
137013             iMax = a[i].iDocid;
137014             i = 0;
137015           }
137016         }
137017       }
137018
137019       /* Check if the current entries really are a phrase match */
137020       if( bEof==0 ){
137021         int nList = 0;
137022         int nByte = a[p->nToken-1].nList;
137023         char *aDoclist = sqlite3_malloc(nByte+1);
137024         if( !aDoclist ) return SQLITE_NOMEM;
137025         memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
137026
137027         for(i=0; i<(p->nToken-1); i++){
137028           if( a[i].bIgnore==0 ){
137029             char *pL = a[i].pList;
137030             char *pR = aDoclist;
137031             char *pOut = aDoclist;
137032             int nDist = p->nToken-1-i;
137033             int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
137034             if( res==0 ) break;
137035             nList = (int)(pOut - aDoclist);
137036           }
137037         }
137038         if( i==(p->nToken-1) ){
137039           pDL->iDocid = iMax;
137040           pDL->pList = aDoclist;
137041           pDL->nList = nList;
137042           pDL->bFreeList = 1;
137043           break;
137044         }
137045         sqlite3_free(aDoclist);
137046       }
137047     }
137048   }
137049
137050   *pbEof = bEof;
137051   return rc;
137052 }
137053
137054 /*
137055 ** Attempt to move the phrase iterator to point to the next matching docid. 
137056 ** If an error occurs, return an SQLite error code. Otherwise, return 
137057 ** SQLITE_OK.
137058 **
137059 ** If there is no "next" entry and no error occurs, then *pbEof is set to
137060 ** 1 before returning. Otherwise, if no error occurs and the iterator is
137061 ** successfully advanced, *pbEof is set to 0.
137062 */
137063 static int fts3EvalPhraseNext(
137064   Fts3Cursor *pCsr,               /* FTS Cursor handle */
137065   Fts3Phrase *p,                  /* Phrase object to advance to next docid */
137066   u8 *pbEof                       /* OUT: Set to 1 if EOF */
137067 ){
137068   int rc = SQLITE_OK;
137069   Fts3Doclist *pDL = &p->doclist;
137070   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
137071
137072   if( p->bIncr ){
137073     rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
137074   }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
137075     sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll, 
137076         &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
137077     );
137078     pDL->pList = pDL->pNextDocid;
137079   }else{
137080     fts3EvalDlPhraseNext(pTab, pDL, pbEof);
137081   }
137082
137083   return rc;
137084 }
137085
137086 /*
137087 **
137088 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
137089 ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
137090 ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
137091 ** expressions for which all descendent tokens are deferred.
137092 **
137093 ** If parameter bOptOk is zero, then it is guaranteed that the
137094 ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
137095 ** each phrase in the expression (subject to deferred token processing).
137096 ** Or, if bOptOk is non-zero, then one or more tokens within the expression
137097 ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
137098 **
137099 ** If an error occurs within this function, *pRc is set to an SQLite error
137100 ** code before returning.
137101 */
137102 static void fts3EvalStartReaders(
137103   Fts3Cursor *pCsr,               /* FTS Cursor handle */
137104   Fts3Expr *pExpr,                /* Expression to initialize phrases in */
137105   int *pRc                        /* IN/OUT: Error code */
137106 ){
137107   if( pExpr && SQLITE_OK==*pRc ){
137108     if( pExpr->eType==FTSQUERY_PHRASE ){
137109       int i;
137110       int nToken = pExpr->pPhrase->nToken;
137111       for(i=0; i<nToken; i++){
137112         if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
137113       }
137114       pExpr->bDeferred = (i==nToken);
137115       *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
137116     }else{
137117       fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
137118       fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
137119       pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
137120     }
137121   }
137122 }
137123
137124 /*
137125 ** An array of the following structures is assembled as part of the process
137126 ** of selecting tokens to defer before the query starts executing (as part
137127 ** of the xFilter() method). There is one element in the array for each
137128 ** token in the FTS expression.
137129 **
137130 ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
137131 ** to phrases that are connected only by AND and NEAR operators (not OR or
137132 ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
137133 ** separately. The root of a tokens AND/NEAR cluster is stored in 
137134 ** Fts3TokenAndCost.pRoot.
137135 */
137136 typedef struct Fts3TokenAndCost Fts3TokenAndCost;
137137 struct Fts3TokenAndCost {
137138   Fts3Phrase *pPhrase;            /* The phrase the token belongs to */
137139   int iToken;                     /* Position of token in phrase */
137140   Fts3PhraseToken *pToken;        /* The token itself */
137141   Fts3Expr *pRoot;                /* Root of NEAR/AND cluster */
137142   int nOvfl;                      /* Number of overflow pages to load doclist */
137143   int iCol;                       /* The column the token must match */
137144 };
137145
137146 /*
137147 ** This function is used to populate an allocated Fts3TokenAndCost array.
137148 **
137149 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
137150 ** Otherwise, if an error occurs during execution, *pRc is set to an
137151 ** SQLite error code.
137152 */
137153 static void fts3EvalTokenCosts(
137154   Fts3Cursor *pCsr,               /* FTS Cursor handle */
137155   Fts3Expr *pRoot,                /* Root of current AND/NEAR cluster */
137156   Fts3Expr *pExpr,                /* Expression to consider */
137157   Fts3TokenAndCost **ppTC,        /* Write new entries to *(*ppTC)++ */
137158   Fts3Expr ***ppOr,               /* Write new OR root to *(*ppOr)++ */
137159   int *pRc                        /* IN/OUT: Error code */
137160 ){
137161   if( *pRc==SQLITE_OK ){
137162     if( pExpr->eType==FTSQUERY_PHRASE ){
137163       Fts3Phrase *pPhrase = pExpr->pPhrase;
137164       int i;
137165       for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
137166         Fts3TokenAndCost *pTC = (*ppTC)++;
137167         pTC->pPhrase = pPhrase;
137168         pTC->iToken = i;
137169         pTC->pRoot = pRoot;
137170         pTC->pToken = &pPhrase->aToken[i];
137171         pTC->iCol = pPhrase->iColumn;
137172         *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
137173       }
137174     }else if( pExpr->eType!=FTSQUERY_NOT ){
137175       assert( pExpr->eType==FTSQUERY_OR
137176            || pExpr->eType==FTSQUERY_AND
137177            || pExpr->eType==FTSQUERY_NEAR
137178       );
137179       assert( pExpr->pLeft && pExpr->pRight );
137180       if( pExpr->eType==FTSQUERY_OR ){
137181         pRoot = pExpr->pLeft;
137182         **ppOr = pRoot;
137183         (*ppOr)++;
137184       }
137185       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
137186       if( pExpr->eType==FTSQUERY_OR ){
137187         pRoot = pExpr->pRight;
137188         **ppOr = pRoot;
137189         (*ppOr)++;
137190       }
137191       fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
137192     }
137193   }
137194 }
137195
137196 /*
137197 ** Determine the average document (row) size in pages. If successful,
137198 ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
137199 ** an SQLite error code.
137200 **
137201 ** The average document size in pages is calculated by first calculating 
137202 ** determining the average size in bytes, B. If B is less than the amount
137203 ** of data that will fit on a single leaf page of an intkey table in
137204 ** this database, then the average docsize is 1. Otherwise, it is 1 plus
137205 ** the number of overflow pages consumed by a record B bytes in size.
137206 */
137207 static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
137208   if( pCsr->nRowAvg==0 ){
137209     /* The average document size, which is required to calculate the cost
137210     ** of each doclist, has not yet been determined. Read the required 
137211     ** data from the %_stat table to calculate it.
137212     **
137213     ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3 
137214     ** varints, where nCol is the number of columns in the FTS3 table.
137215     ** The first varint is the number of documents currently stored in
137216     ** the table. The following nCol varints contain the total amount of
137217     ** data stored in all rows of each column of the table, from left
137218     ** to right.
137219     */
137220     int rc;
137221     Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
137222     sqlite3_stmt *pStmt;
137223     sqlite3_int64 nDoc = 0;
137224     sqlite3_int64 nByte = 0;
137225     const char *pEnd;
137226     const char *a;
137227
137228     rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
137229     if( rc!=SQLITE_OK ) return rc;
137230     a = sqlite3_column_blob(pStmt, 0);
137231     assert( a );
137232
137233     pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
137234     a += sqlite3Fts3GetVarint(a, &nDoc);
137235     while( a<pEnd ){
137236       a += sqlite3Fts3GetVarint(a, &nByte);
137237     }
137238     if( nDoc==0 || nByte==0 ){
137239       sqlite3_reset(pStmt);
137240       return FTS_CORRUPT_VTAB;
137241     }
137242
137243     pCsr->nDoc = nDoc;
137244     pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
137245     assert( pCsr->nRowAvg>0 ); 
137246     rc = sqlite3_reset(pStmt);
137247     if( rc!=SQLITE_OK ) return rc;
137248   }
137249
137250   *pnPage = pCsr->nRowAvg;
137251   return SQLITE_OK;
137252 }
137253
137254 /*
137255 ** This function is called to select the tokens (if any) that will be 
137256 ** deferred. The array aTC[] has already been populated when this is
137257 ** called.
137258 **
137259 ** This function is called once for each AND/NEAR cluster in the 
137260 ** expression. Each invocation determines which tokens to defer within
137261 ** the cluster with root node pRoot. See comments above the definition
137262 ** of struct Fts3TokenAndCost for more details.
137263 **
137264 ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
137265 ** called on each token to defer. Otherwise, an SQLite error code is
137266 ** returned.
137267 */
137268 static int fts3EvalSelectDeferred(
137269   Fts3Cursor *pCsr,               /* FTS Cursor handle */
137270   Fts3Expr *pRoot,                /* Consider tokens with this root node */
137271   Fts3TokenAndCost *aTC,          /* Array of expression tokens and costs */
137272   int nTC                         /* Number of entries in aTC[] */
137273 ){
137274   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
137275   int nDocSize = 0;               /* Number of pages per doc loaded */
137276   int rc = SQLITE_OK;             /* Return code */
137277   int ii;                         /* Iterator variable for various purposes */
137278   int nOvfl = 0;                  /* Total overflow pages used by doclists */
137279   int nToken = 0;                 /* Total number of tokens in cluster */
137280
137281   int nMinEst = 0;                /* The minimum count for any phrase so far. */
137282   int nLoad4 = 1;                 /* (Phrases that will be loaded)^4. */
137283
137284   /* Tokens are never deferred for FTS tables created using the content=xxx
137285   ** option. The reason being that it is not guaranteed that the content
137286   ** table actually contains the same data as the index. To prevent this from
137287   ** causing any problems, the deferred token optimization is completely
137288   ** disabled for content=xxx tables. */
137289   if( pTab->zContentTbl ){
137290     return SQLITE_OK;
137291   }
137292
137293   /* Count the tokens in this AND/NEAR cluster. If none of the doclists
137294   ** associated with the tokens spill onto overflow pages, or if there is
137295   ** only 1 token, exit early. No tokens to defer in this case. */
137296   for(ii=0; ii<nTC; ii++){
137297     if( aTC[ii].pRoot==pRoot ){
137298       nOvfl += aTC[ii].nOvfl;
137299       nToken++;
137300     }
137301   }
137302   if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
137303
137304   /* Obtain the average docsize (in pages). */
137305   rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
137306   assert( rc!=SQLITE_OK || nDocSize>0 );
137307
137308
137309   /* Iterate through all tokens in this AND/NEAR cluster, in ascending order 
137310   ** of the number of overflow pages that will be loaded by the pager layer 
137311   ** to retrieve the entire doclist for the token from the full-text index.
137312   ** Load the doclists for tokens that are either:
137313   **
137314   **   a. The cheapest token in the entire query (i.e. the one visited by the
137315   **      first iteration of this loop), or
137316   **
137317   **   b. Part of a multi-token phrase.
137318   **
137319   ** After each token doclist is loaded, merge it with the others from the
137320   ** same phrase and count the number of documents that the merged doclist
137321   ** contains. Set variable "nMinEst" to the smallest number of documents in 
137322   ** any phrase doclist for which 1 or more token doclists have been loaded.
137323   ** Let nOther be the number of other phrases for which it is certain that
137324   ** one or more tokens will not be deferred.
137325   **
137326   ** Then, for each token, defer it if loading the doclist would result in
137327   ** loading N or more overflow pages into memory, where N is computed as:
137328   **
137329   **    (nMinEst + 4^nOther - 1) / (4^nOther)
137330   */
137331   for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
137332     int iTC;                      /* Used to iterate through aTC[] array. */
137333     Fts3TokenAndCost *pTC = 0;    /* Set to cheapest remaining token. */
137334
137335     /* Set pTC to point to the cheapest remaining token. */
137336     for(iTC=0; iTC<nTC; iTC++){
137337       if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot 
137338        && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl) 
137339       ){
137340         pTC = &aTC[iTC];
137341       }
137342     }
137343     assert( pTC );
137344
137345     if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
137346       /* The number of overflow pages to load for this (and therefore all
137347       ** subsequent) tokens is greater than the estimated number of pages 
137348       ** that will be loaded if all subsequent tokens are deferred.
137349       */
137350       Fts3PhraseToken *pToken = pTC->pToken;
137351       rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
137352       fts3SegReaderCursorFree(pToken->pSegcsr);
137353       pToken->pSegcsr = 0;
137354     }else{
137355       /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
137356       ** for-loop. Except, limit the value to 2^24 to prevent it from 
137357       ** overflowing the 32-bit integer it is stored in. */
137358       if( ii<12 ) nLoad4 = nLoad4*4;
137359
137360       if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
137361         /* Either this is the cheapest token in the entire query, or it is
137362         ** part of a multi-token phrase. Either way, the entire doclist will
137363         ** (eventually) be loaded into memory. It may as well be now. */
137364         Fts3PhraseToken *pToken = pTC->pToken;
137365         int nList = 0;
137366         char *pList = 0;
137367         rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
137368         assert( rc==SQLITE_OK || pList==0 );
137369         if( rc==SQLITE_OK ){
137370           rc = fts3EvalPhraseMergeToken(
137371               pTab, pTC->pPhrase, pTC->iToken,pList,nList
137372           );
137373         }
137374         if( rc==SQLITE_OK ){
137375           int nCount;
137376           nCount = fts3DoclistCountDocids(
137377               pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
137378           );
137379           if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
137380         }
137381       }
137382     }
137383     pTC->pToken = 0;
137384   }
137385
137386   return rc;
137387 }
137388
137389 /*
137390 ** This function is called from within the xFilter method. It initializes
137391 ** the full-text query currently stored in pCsr->pExpr. To iterate through
137392 ** the results of a query, the caller does:
137393 **
137394 **    fts3EvalStart(pCsr);
137395 **    while( 1 ){
137396 **      fts3EvalNext(pCsr);
137397 **      if( pCsr->bEof ) break;
137398 **      ... return row pCsr->iPrevId to the caller ...
137399 **    }
137400 */
137401 static int fts3EvalStart(Fts3Cursor *pCsr){
137402   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
137403   int rc = SQLITE_OK;
137404   int nToken = 0;
137405   int nOr = 0;
137406
137407   /* Allocate a MultiSegReader for each token in the expression. */
137408   fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
137409
137410   /* Determine which, if any, tokens in the expression should be deferred. */
137411 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
137412   if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
137413     Fts3TokenAndCost *aTC;
137414     Fts3Expr **apOr;
137415     aTC = (Fts3TokenAndCost *)sqlite3_malloc(
137416         sizeof(Fts3TokenAndCost) * nToken
137417       + sizeof(Fts3Expr *) * nOr * 2
137418     );
137419     apOr = (Fts3Expr **)&aTC[nToken];
137420
137421     if( !aTC ){
137422       rc = SQLITE_NOMEM;
137423     }else{
137424       int ii;
137425       Fts3TokenAndCost *pTC = aTC;
137426       Fts3Expr **ppOr = apOr;
137427
137428       fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
137429       nToken = (int)(pTC-aTC);
137430       nOr = (int)(ppOr-apOr);
137431
137432       if( rc==SQLITE_OK ){
137433         rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
137434         for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
137435           rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
137436         }
137437       }
137438
137439       sqlite3_free(aTC);
137440     }
137441   }
137442 #endif
137443
137444   fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
137445   return rc;
137446 }
137447
137448 /*
137449 ** Invalidate the current position list for phrase pPhrase.
137450 */
137451 static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
137452   if( pPhrase->doclist.bFreeList ){
137453     sqlite3_free(pPhrase->doclist.pList);
137454   }
137455   pPhrase->doclist.pList = 0;
137456   pPhrase->doclist.nList = 0;
137457   pPhrase->doclist.bFreeList = 0;
137458 }
137459
137460 /*
137461 ** This function is called to edit the position list associated with
137462 ** the phrase object passed as the fifth argument according to a NEAR
137463 ** condition. For example:
137464 **
137465 **     abc NEAR/5 "def ghi"
137466 **
137467 ** Parameter nNear is passed the NEAR distance of the expression (5 in
137468 ** the example above). When this function is called, *paPoslist points to
137469 ** the position list, and *pnToken is the number of phrase tokens in, the
137470 ** phrase on the other side of the NEAR operator to pPhrase. For example,
137471 ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
137472 ** the position list associated with phrase "abc".
137473 **
137474 ** All positions in the pPhrase position list that are not sufficiently
137475 ** close to a position in the *paPoslist position list are removed. If this
137476 ** leaves 0 positions, zero is returned. Otherwise, non-zero.
137477 **
137478 ** Before returning, *paPoslist is set to point to the position lsit 
137479 ** associated with pPhrase. And *pnToken is set to the number of tokens in
137480 ** pPhrase.
137481 */
137482 static int fts3EvalNearTrim(
137483   int nNear,                      /* NEAR distance. As in "NEAR/nNear". */
137484   char *aTmp,                     /* Temporary space to use */
137485   char **paPoslist,               /* IN/OUT: Position list */
137486   int *pnToken,                   /* IN/OUT: Tokens in phrase of *paPoslist */
137487   Fts3Phrase *pPhrase             /* The phrase object to trim the doclist of */
137488 ){
137489   int nParam1 = nNear + pPhrase->nToken;
137490   int nParam2 = nNear + *pnToken;
137491   int nNew;
137492   char *p2; 
137493   char *pOut; 
137494   int res;
137495
137496   assert( pPhrase->doclist.pList );
137497
137498   p2 = pOut = pPhrase->doclist.pList;
137499   res = fts3PoslistNearMerge(
137500     &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
137501   );
137502   if( res ){
137503     nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
137504     assert( pPhrase->doclist.pList[nNew]=='\0' );
137505     assert( nNew<=pPhrase->doclist.nList && nNew>0 );
137506     memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
137507     pPhrase->doclist.nList = nNew;
137508     *paPoslist = pPhrase->doclist.pList;
137509     *pnToken = pPhrase->nToken;
137510   }
137511
137512   return res;
137513 }
137514
137515 /*
137516 ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
137517 ** Otherwise, it advances the expression passed as the second argument to
137518 ** point to the next matching row in the database. Expressions iterate through
137519 ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
137520 ** or descending if it is non-zero.
137521 **
137522 ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
137523 ** successful, the following variables in pExpr are set:
137524 **
137525 **   Fts3Expr.bEof                (non-zero if EOF - there is no next row)
137526 **   Fts3Expr.iDocid              (valid if bEof==0. The docid of the next row)
137527 **
137528 ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
137529 ** at EOF, then the following variables are populated with the position list
137530 ** for the phrase for the visited row:
137531 **
137532 **   FTs3Expr.pPhrase->doclist.nList        (length of pList in bytes)
137533 **   FTs3Expr.pPhrase->doclist.pList        (pointer to position list)
137534 **
137535 ** It says above that this function advances the expression to the next
137536 ** matching row. This is usually true, but there are the following exceptions:
137537 **
137538 **   1. Deferred tokens are not taken into account. If a phrase consists
137539 **      entirely of deferred tokens, it is assumed to match every row in
137540 **      the db. In this case the position-list is not populated at all. 
137541 **
137542 **      Or, if a phrase contains one or more deferred tokens and one or
137543 **      more non-deferred tokens, then the expression is advanced to the 
137544 **      next possible match, considering only non-deferred tokens. In other
137545 **      words, if the phrase is "A B C", and "B" is deferred, the expression
137546 **      is advanced to the next row that contains an instance of "A * C", 
137547 **      where "*" may match any single token. The position list in this case
137548 **      is populated as for "A * C" before returning.
137549 **
137550 **   2. NEAR is treated as AND. If the expression is "x NEAR y", it is 
137551 **      advanced to point to the next row that matches "x AND y".
137552 ** 
137553 ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
137554 ** really a match, taking into account deferred tokens and NEAR operators.
137555 */
137556 static void fts3EvalNextRow(
137557   Fts3Cursor *pCsr,               /* FTS Cursor handle */
137558   Fts3Expr *pExpr,                /* Expr. to advance to next matching row */
137559   int *pRc                        /* IN/OUT: Error code */
137560 ){
137561   if( *pRc==SQLITE_OK ){
137562     int bDescDoclist = pCsr->bDesc;         /* Used by DOCID_CMP() macro */
137563     assert( pExpr->bEof==0 );
137564     pExpr->bStart = 1;
137565
137566     switch( pExpr->eType ){
137567       case FTSQUERY_NEAR:
137568       case FTSQUERY_AND: {
137569         Fts3Expr *pLeft = pExpr->pLeft;
137570         Fts3Expr *pRight = pExpr->pRight;
137571         assert( !pLeft->bDeferred || !pRight->bDeferred );
137572
137573         if( pLeft->bDeferred ){
137574           /* LHS is entirely deferred. So we assume it matches every row.
137575           ** Advance the RHS iterator to find the next row visited. */
137576           fts3EvalNextRow(pCsr, pRight, pRc);
137577           pExpr->iDocid = pRight->iDocid;
137578           pExpr->bEof = pRight->bEof;
137579         }else if( pRight->bDeferred ){
137580           /* RHS is entirely deferred. So we assume it matches every row.
137581           ** Advance the LHS iterator to find the next row visited. */
137582           fts3EvalNextRow(pCsr, pLeft, pRc);
137583           pExpr->iDocid = pLeft->iDocid;
137584           pExpr->bEof = pLeft->bEof;
137585         }else{
137586           /* Neither the RHS or LHS are deferred. */
137587           fts3EvalNextRow(pCsr, pLeft, pRc);
137588           fts3EvalNextRow(pCsr, pRight, pRc);
137589           while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
137590             sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
137591             if( iDiff==0 ) break;
137592             if( iDiff<0 ){
137593               fts3EvalNextRow(pCsr, pLeft, pRc);
137594             }else{
137595               fts3EvalNextRow(pCsr, pRight, pRc);
137596             }
137597           }
137598           pExpr->iDocid = pLeft->iDocid;
137599           pExpr->bEof = (pLeft->bEof || pRight->bEof);
137600           if( pExpr->eType==FTSQUERY_NEAR && pExpr->bEof ){
137601             if( pRight->pPhrase && pRight->pPhrase->doclist.aAll ){
137602               Fts3Doclist *pDl = &pRight->pPhrase->doclist;
137603               while( *pRc==SQLITE_OK && pRight->bEof==0 ){
137604                 memset(pDl->pList, 0, pDl->nList);
137605                 fts3EvalNextRow(pCsr, pRight, pRc);
137606               }
137607             }
137608             if( pLeft->pPhrase && pLeft->pPhrase->doclist.aAll ){
137609               Fts3Doclist *pDl = &pLeft->pPhrase->doclist;
137610               while( *pRc==SQLITE_OK && pLeft->bEof==0 ){
137611                 memset(pDl->pList, 0, pDl->nList);
137612                 fts3EvalNextRow(pCsr, pLeft, pRc);
137613               }
137614             }
137615           }
137616         }
137617         break;
137618       }
137619   
137620       case FTSQUERY_OR: {
137621         Fts3Expr *pLeft = pExpr->pLeft;
137622         Fts3Expr *pRight = pExpr->pRight;
137623         sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
137624
137625         assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
137626         assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
137627
137628         if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
137629           fts3EvalNextRow(pCsr, pLeft, pRc);
137630         }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
137631           fts3EvalNextRow(pCsr, pRight, pRc);
137632         }else{
137633           fts3EvalNextRow(pCsr, pLeft, pRc);
137634           fts3EvalNextRow(pCsr, pRight, pRc);
137635         }
137636
137637         pExpr->bEof = (pLeft->bEof && pRight->bEof);
137638         iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
137639         if( pRight->bEof || (pLeft->bEof==0 &&  iCmp<0) ){
137640           pExpr->iDocid = pLeft->iDocid;
137641         }else{
137642           pExpr->iDocid = pRight->iDocid;
137643         }
137644
137645         break;
137646       }
137647
137648       case FTSQUERY_NOT: {
137649         Fts3Expr *pLeft = pExpr->pLeft;
137650         Fts3Expr *pRight = pExpr->pRight;
137651
137652         if( pRight->bStart==0 ){
137653           fts3EvalNextRow(pCsr, pRight, pRc);
137654           assert( *pRc!=SQLITE_OK || pRight->bStart );
137655         }
137656
137657         fts3EvalNextRow(pCsr, pLeft, pRc);
137658         if( pLeft->bEof==0 ){
137659           while( !*pRc 
137660               && !pRight->bEof 
137661               && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0 
137662           ){
137663             fts3EvalNextRow(pCsr, pRight, pRc);
137664           }
137665         }
137666         pExpr->iDocid = pLeft->iDocid;
137667         pExpr->bEof = pLeft->bEof;
137668         break;
137669       }
137670
137671       default: {
137672         Fts3Phrase *pPhrase = pExpr->pPhrase;
137673         fts3EvalInvalidatePoslist(pPhrase);
137674         *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
137675         pExpr->iDocid = pPhrase->doclist.iDocid;
137676         break;
137677       }
137678     }
137679   }
137680 }
137681
137682 /*
137683 ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
137684 ** cluster, then this function returns 1 immediately.
137685 **
137686 ** Otherwise, it checks if the current row really does match the NEAR 
137687 ** expression, using the data currently stored in the position lists 
137688 ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression. 
137689 **
137690 ** If the current row is a match, the position list associated with each
137691 ** phrase in the NEAR expression is edited in place to contain only those
137692 ** phrase instances sufficiently close to their peers to satisfy all NEAR
137693 ** constraints. In this case it returns 1. If the NEAR expression does not 
137694 ** match the current row, 0 is returned. The position lists may or may not
137695 ** be edited if 0 is returned.
137696 */
137697 static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
137698   int res = 1;
137699
137700   /* The following block runs if pExpr is the root of a NEAR query.
137701   ** For example, the query:
137702   **
137703   **         "w" NEAR "x" NEAR "y" NEAR "z"
137704   **
137705   ** which is represented in tree form as:
137706   **
137707   **                               |
137708   **                          +--NEAR--+      <-- root of NEAR query
137709   **                          |        |
137710   **                     +--NEAR--+   "z"
137711   **                     |        |
137712   **                +--NEAR--+   "y"
137713   **                |        |
137714   **               "w"      "x"
137715   **
137716   ** The right-hand child of a NEAR node is always a phrase. The 
137717   ** left-hand child may be either a phrase or a NEAR node. There are
137718   ** no exceptions to this - it's the way the parser in fts3_expr.c works.
137719   */
137720   if( *pRc==SQLITE_OK 
137721    && pExpr->eType==FTSQUERY_NEAR 
137722    && pExpr->bEof==0
137723    && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
137724   ){
137725     Fts3Expr *p; 
137726     int nTmp = 0;                 /* Bytes of temp space */
137727     char *aTmp;                   /* Temp space for PoslistNearMerge() */
137728
137729     /* Allocate temporary working space. */
137730     for(p=pExpr; p->pLeft; p=p->pLeft){
137731       nTmp += p->pRight->pPhrase->doclist.nList;
137732     }
137733     nTmp += p->pPhrase->doclist.nList;
137734     if( nTmp==0 ){
137735       res = 0;
137736     }else{
137737       aTmp = sqlite3_malloc(nTmp*2);
137738       if( !aTmp ){
137739         *pRc = SQLITE_NOMEM;
137740         res = 0;
137741       }else{
137742         char *aPoslist = p->pPhrase->doclist.pList;
137743         int nToken = p->pPhrase->nToken;
137744
137745         for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
137746           Fts3Phrase *pPhrase = p->pRight->pPhrase;
137747           int nNear = p->nNear;
137748           res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
137749         }
137750
137751         aPoslist = pExpr->pRight->pPhrase->doclist.pList;
137752         nToken = pExpr->pRight->pPhrase->nToken;
137753         for(p=pExpr->pLeft; p && res; p=p->pLeft){
137754           int nNear;
137755           Fts3Phrase *pPhrase;
137756           assert( p->pParent && p->pParent->pLeft==p );
137757           nNear = p->pParent->nNear;
137758           pPhrase = (
137759               p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
137760               );
137761           res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
137762         }
137763       }
137764
137765       sqlite3_free(aTmp);
137766     }
137767   }
137768
137769   return res;
137770 }
137771
137772 /*
137773 ** This function is a helper function for fts3EvalTestDeferredAndNear().
137774 ** Assuming no error occurs or has occurred, It returns non-zero if the
137775 ** expression passed as the second argument matches the row that pCsr 
137776 ** currently points to, or zero if it does not.
137777 **
137778 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
137779 ** If an error occurs during execution of this function, *pRc is set to 
137780 ** the appropriate SQLite error code. In this case the returned value is 
137781 ** undefined.
137782 */
137783 static int fts3EvalTestExpr(
137784   Fts3Cursor *pCsr,               /* FTS cursor handle */
137785   Fts3Expr *pExpr,                /* Expr to test. May or may not be root. */
137786   int *pRc                        /* IN/OUT: Error code */
137787 ){
137788   int bHit = 1;                   /* Return value */
137789   if( *pRc==SQLITE_OK ){
137790     switch( pExpr->eType ){
137791       case FTSQUERY_NEAR:
137792       case FTSQUERY_AND:
137793         bHit = (
137794             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
137795          && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
137796          && fts3EvalNearTest(pExpr, pRc)
137797         );
137798
137799         /* If the NEAR expression does not match any rows, zero the doclist for 
137800         ** all phrases involved in the NEAR. This is because the snippet(),
137801         ** offsets() and matchinfo() functions are not supposed to recognize 
137802         ** any instances of phrases that are part of unmatched NEAR queries. 
137803         ** For example if this expression:
137804         **
137805         **    ... MATCH 'a OR (b NEAR c)'
137806         **
137807         ** is matched against a row containing:
137808         **
137809         **        'a b d e'
137810         **
137811         ** then any snippet() should ony highlight the "a" term, not the "b"
137812         ** (as "b" is part of a non-matching NEAR clause).
137813         */
137814         if( bHit==0 
137815          && pExpr->eType==FTSQUERY_NEAR 
137816          && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
137817         ){
137818           Fts3Expr *p;
137819           for(p=pExpr; p->pPhrase==0; p=p->pLeft){
137820             if( p->pRight->iDocid==pCsr->iPrevId ){
137821               fts3EvalInvalidatePoslist(p->pRight->pPhrase);
137822             }
137823           }
137824           if( p->iDocid==pCsr->iPrevId ){
137825             fts3EvalInvalidatePoslist(p->pPhrase);
137826           }
137827         }
137828
137829         break;
137830
137831       case FTSQUERY_OR: {
137832         int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
137833         int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
137834         bHit = bHit1 || bHit2;
137835         break;
137836       }
137837
137838       case FTSQUERY_NOT:
137839         bHit = (
137840             fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
137841          && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
137842         );
137843         break;
137844
137845       default: {
137846 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
137847         if( pCsr->pDeferred 
137848          && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
137849         ){
137850           Fts3Phrase *pPhrase = pExpr->pPhrase;
137851           assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
137852           if( pExpr->bDeferred ){
137853             fts3EvalInvalidatePoslist(pPhrase);
137854           }
137855           *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
137856           bHit = (pPhrase->doclist.pList!=0);
137857           pExpr->iDocid = pCsr->iPrevId;
137858         }else
137859 #endif
137860         {
137861           bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
137862         }
137863         break;
137864       }
137865     }
137866   }
137867   return bHit;
137868 }
137869
137870 /*
137871 ** This function is called as the second part of each xNext operation when
137872 ** iterating through the results of a full-text query. At this point the
137873 ** cursor points to a row that matches the query expression, with the
137874 ** following caveats:
137875 **
137876 **   * Up until this point, "NEAR" operators in the expression have been
137877 **     treated as "AND".
137878 **
137879 **   * Deferred tokens have not yet been considered.
137880 **
137881 ** If *pRc is not SQLITE_OK when this function is called, it immediately
137882 ** returns 0. Otherwise, it tests whether or not after considering NEAR
137883 ** operators and deferred tokens the current row is still a match for the
137884 ** expression. It returns 1 if both of the following are true:
137885 **
137886 **   1. *pRc is SQLITE_OK when this function returns, and
137887 **
137888 **   2. After scanning the current FTS table row for the deferred tokens,
137889 **      it is determined that the row does *not* match the query.
137890 **
137891 ** Or, if no error occurs and it seems the current row does match the FTS
137892 ** query, return 0.
137893 */
137894 static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
137895   int rc = *pRc;
137896   int bMiss = 0;
137897   if( rc==SQLITE_OK ){
137898
137899     /* If there are one or more deferred tokens, load the current row into
137900     ** memory and scan it to determine the position list for each deferred
137901     ** token. Then, see if this row is really a match, considering deferred
137902     ** tokens and NEAR operators (neither of which were taken into account
137903     ** earlier, by fts3EvalNextRow()). 
137904     */
137905     if( pCsr->pDeferred ){
137906       rc = fts3CursorSeek(0, pCsr);
137907       if( rc==SQLITE_OK ){
137908         rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
137909       }
137910     }
137911     bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
137912
137913     /* Free the position-lists accumulated for each deferred token above. */
137914     sqlite3Fts3FreeDeferredDoclists(pCsr);
137915     *pRc = rc;
137916   }
137917   return (rc==SQLITE_OK && bMiss);
137918 }
137919
137920 /*
137921 ** Advance to the next document that matches the FTS expression in
137922 ** Fts3Cursor.pExpr.
137923 */
137924 static int fts3EvalNext(Fts3Cursor *pCsr){
137925   int rc = SQLITE_OK;             /* Return Code */
137926   Fts3Expr *pExpr = pCsr->pExpr;
137927   assert( pCsr->isEof==0 );
137928   if( pExpr==0 ){
137929     pCsr->isEof = 1;
137930   }else{
137931     do {
137932       if( pCsr->isRequireSeek==0 ){
137933         sqlite3_reset(pCsr->pStmt);
137934       }
137935       assert( sqlite3_data_count(pCsr->pStmt)==0 );
137936       fts3EvalNextRow(pCsr, pExpr, &rc);
137937       pCsr->isEof = pExpr->bEof;
137938       pCsr->isRequireSeek = 1;
137939       pCsr->isMatchinfoNeeded = 1;
137940       pCsr->iPrevId = pExpr->iDocid;
137941     }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
137942   }
137943
137944   /* Check if the cursor is past the end of the docid range specified
137945   ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag.  */
137946   if( rc==SQLITE_OK && (
137947         (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
137948      || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
137949   )){
137950     pCsr->isEof = 1;
137951   }
137952
137953   return rc;
137954 }
137955
137956 /*
137957 ** Restart interation for expression pExpr so that the next call to
137958 ** fts3EvalNext() visits the first row. Do not allow incremental 
137959 ** loading or merging of phrase doclists for this iteration.
137960 **
137961 ** If *pRc is other than SQLITE_OK when this function is called, it is
137962 ** a no-op. If an error occurs within this function, *pRc is set to an
137963 ** SQLite error code before returning.
137964 */
137965 static void fts3EvalRestart(
137966   Fts3Cursor *pCsr,
137967   Fts3Expr *pExpr,
137968   int *pRc
137969 ){
137970   if( pExpr && *pRc==SQLITE_OK ){
137971     Fts3Phrase *pPhrase = pExpr->pPhrase;
137972
137973     if( pPhrase ){
137974       fts3EvalInvalidatePoslist(pPhrase);
137975       if( pPhrase->bIncr ){
137976         int i;
137977         for(i=0; i<pPhrase->nToken; i++){
137978           Fts3PhraseToken *pToken = &pPhrase->aToken[i];
137979           assert( pToken->pDeferred==0 );
137980           if( pToken->pSegcsr ){
137981             sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
137982           }
137983         }
137984         *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
137985       }
137986       pPhrase->doclist.pNextDocid = 0;
137987       pPhrase->doclist.iDocid = 0;
137988       pPhrase->pOrPoslist = 0;
137989     }
137990
137991     pExpr->iDocid = 0;
137992     pExpr->bEof = 0;
137993     pExpr->bStart = 0;
137994
137995     fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
137996     fts3EvalRestart(pCsr, pExpr->pRight, pRc);
137997   }
137998 }
137999
138000 /*
138001 ** After allocating the Fts3Expr.aMI[] array for each phrase in the 
138002 ** expression rooted at pExpr, the cursor iterates through all rows matched
138003 ** by pExpr, calling this function for each row. This function increments
138004 ** the values in Fts3Expr.aMI[] according to the position-list currently
138005 ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase 
138006 ** expression nodes.
138007 */
138008 static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
138009   if( pExpr ){
138010     Fts3Phrase *pPhrase = pExpr->pPhrase;
138011     if( pPhrase && pPhrase->doclist.pList ){
138012       int iCol = 0;
138013       char *p = pPhrase->doclist.pList;
138014
138015       assert( *p );
138016       while( 1 ){
138017         u8 c = 0;
138018         int iCnt = 0;
138019         while( 0xFE & (*p | c) ){
138020           if( (c&0x80)==0 ) iCnt++;
138021           c = *p++ & 0x80;
138022         }
138023
138024         /* aMI[iCol*3 + 1] = Number of occurrences
138025         ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
138026         */
138027         pExpr->aMI[iCol*3 + 1] += iCnt;
138028         pExpr->aMI[iCol*3 + 2] += (iCnt>0);
138029         if( *p==0x00 ) break;
138030         p++;
138031         p += fts3GetVarint32(p, &iCol);
138032       }
138033     }
138034
138035     fts3EvalUpdateCounts(pExpr->pLeft);
138036     fts3EvalUpdateCounts(pExpr->pRight);
138037   }
138038 }
138039
138040 /*
138041 ** Expression pExpr must be of type FTSQUERY_PHRASE.
138042 **
138043 ** If it is not already allocated and populated, this function allocates and
138044 ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
138045 ** of a NEAR expression, then it also allocates and populates the same array
138046 ** for all other phrases that are part of the NEAR expression.
138047 **
138048 ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
138049 ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
138050 */
138051 static int fts3EvalGatherStats(
138052   Fts3Cursor *pCsr,               /* Cursor object */
138053   Fts3Expr *pExpr                 /* FTSQUERY_PHRASE expression */
138054 ){
138055   int rc = SQLITE_OK;             /* Return code */
138056
138057   assert( pExpr->eType==FTSQUERY_PHRASE );
138058   if( pExpr->aMI==0 ){
138059     Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
138060     Fts3Expr *pRoot;                /* Root of NEAR expression */
138061     Fts3Expr *p;                    /* Iterator used for several purposes */
138062
138063     sqlite3_int64 iPrevId = pCsr->iPrevId;
138064     sqlite3_int64 iDocid;
138065     u8 bEof;
138066
138067     /* Find the root of the NEAR expression */
138068     pRoot = pExpr;
138069     while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
138070       pRoot = pRoot->pParent;
138071     }
138072     iDocid = pRoot->iDocid;
138073     bEof = pRoot->bEof;
138074     assert( pRoot->bStart );
138075
138076     /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
138077     for(p=pRoot; p; p=p->pLeft){
138078       Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
138079       assert( pE->aMI==0 );
138080       pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
138081       if( !pE->aMI ) return SQLITE_NOMEM;
138082       memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
138083     }
138084
138085     fts3EvalRestart(pCsr, pRoot, &rc);
138086
138087     while( pCsr->isEof==0 && rc==SQLITE_OK ){
138088
138089       do {
138090         /* Ensure the %_content statement is reset. */
138091         if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
138092         assert( sqlite3_data_count(pCsr->pStmt)==0 );
138093
138094         /* Advance to the next document */
138095         fts3EvalNextRow(pCsr, pRoot, &rc);
138096         pCsr->isEof = pRoot->bEof;
138097         pCsr->isRequireSeek = 1;
138098         pCsr->isMatchinfoNeeded = 1;
138099         pCsr->iPrevId = pRoot->iDocid;
138100       }while( pCsr->isEof==0 
138101            && pRoot->eType==FTSQUERY_NEAR 
138102            && fts3EvalTestDeferredAndNear(pCsr, &rc) 
138103       );
138104
138105       if( rc==SQLITE_OK && pCsr->isEof==0 ){
138106         fts3EvalUpdateCounts(pRoot);
138107       }
138108     }
138109
138110     pCsr->isEof = 0;
138111     pCsr->iPrevId = iPrevId;
138112
138113     if( bEof ){
138114       pRoot->bEof = bEof;
138115     }else{
138116       /* Caution: pRoot may iterate through docids in ascending or descending
138117       ** order. For this reason, even though it seems more defensive, the 
138118       ** do loop can not be written:
138119       **
138120       **   do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
138121       */
138122       fts3EvalRestart(pCsr, pRoot, &rc);
138123       do {
138124         fts3EvalNextRow(pCsr, pRoot, &rc);
138125         assert( pRoot->bEof==0 );
138126       }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
138127       fts3EvalTestDeferredAndNear(pCsr, &rc);
138128     }
138129   }
138130   return rc;
138131 }
138132
138133 /*
138134 ** This function is used by the matchinfo() module to query a phrase 
138135 ** expression node for the following information:
138136 **
138137 **   1. The total number of occurrences of the phrase in each column of 
138138 **      the FTS table (considering all rows), and
138139 **
138140 **   2. For each column, the number of rows in the table for which the
138141 **      column contains at least one instance of the phrase.
138142 **
138143 ** If no error occurs, SQLITE_OK is returned and the values for each column
138144 ** written into the array aiOut as follows:
138145 **
138146 **   aiOut[iCol*3 + 1] = Number of occurrences
138147 **   aiOut[iCol*3 + 2] = Number of rows containing at least one instance
138148 **
138149 ** Caveats:
138150 **
138151 **   * If a phrase consists entirely of deferred tokens, then all output 
138152 **     values are set to the number of documents in the table. In other
138153 **     words we assume that very common tokens occur exactly once in each 
138154 **     column of each row of the table.
138155 **
138156 **   * If a phrase contains some deferred tokens (and some non-deferred 
138157 **     tokens), count the potential occurrence identified by considering
138158 **     the non-deferred tokens instead of actual phrase occurrences.
138159 **
138160 **   * If the phrase is part of a NEAR expression, then only phrase instances
138161 **     that meet the NEAR constraint are included in the counts.
138162 */
138163 SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
138164   Fts3Cursor *pCsr,               /* FTS cursor handle */
138165   Fts3Expr *pExpr,                /* Phrase expression */
138166   u32 *aiOut                      /* Array to write results into (see above) */
138167 ){
138168   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
138169   int rc = SQLITE_OK;
138170   int iCol;
138171
138172   if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
138173     assert( pCsr->nDoc>0 );
138174     for(iCol=0; iCol<pTab->nColumn; iCol++){
138175       aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
138176       aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
138177     }
138178   }else{
138179     rc = fts3EvalGatherStats(pCsr, pExpr);
138180     if( rc==SQLITE_OK ){
138181       assert( pExpr->aMI );
138182       for(iCol=0; iCol<pTab->nColumn; iCol++){
138183         aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
138184         aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
138185       }
138186     }
138187   }
138188
138189   return rc;
138190 }
138191
138192 /*
138193 ** The expression pExpr passed as the second argument to this function
138194 ** must be of type FTSQUERY_PHRASE. 
138195 **
138196 ** The returned value is either NULL or a pointer to a buffer containing
138197 ** a position-list indicating the occurrences of the phrase in column iCol
138198 ** of the current row. 
138199 **
138200 ** More specifically, the returned buffer contains 1 varint for each 
138201 ** occurrence of the phrase in the column, stored using the normal (delta+2) 
138202 ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
138203 ** if the requested column contains "a b X c d X X" and the position-list
138204 ** for 'X' is requested, the buffer returned may contain:
138205 **
138206 **     0x04 0x05 0x03 0x01   or   0x04 0x05 0x03 0x00
138207 **
138208 ** This function works regardless of whether or not the phrase is deferred,
138209 ** incremental, or neither.
138210 */
138211 SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
138212   Fts3Cursor *pCsr,               /* FTS3 cursor object */
138213   Fts3Expr *pExpr,                /* Phrase to return doclist for */
138214   int iCol,                       /* Column to return position list for */
138215   char **ppOut                    /* OUT: Pointer to position list */
138216 ){
138217   Fts3Phrase *pPhrase = pExpr->pPhrase;
138218   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
138219   char *pIter;
138220   int iThis;
138221   sqlite3_int64 iDocid;
138222
138223   /* If this phrase is applies specifically to some column other than 
138224   ** column iCol, return a NULL pointer.  */
138225   *ppOut = 0;
138226   assert( iCol>=0 && iCol<pTab->nColumn );
138227   if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
138228     return SQLITE_OK;
138229   }
138230
138231   iDocid = pExpr->iDocid;
138232   pIter = pPhrase->doclist.pList;
138233   if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
138234     int rc = SQLITE_OK;
138235     int bDescDoclist = pTab->bDescIdx;      /* For DOCID_CMP macro */
138236     int bOr = 0;
138237     u8 bEof = 0;
138238     u8 bTreeEof = 0;
138239     Fts3Expr *p;                  /* Used to iterate from pExpr to root */
138240     Fts3Expr *pNear;              /* Most senior NEAR ancestor (or pExpr) */
138241
138242     /* Check if this phrase descends from an OR expression node. If not, 
138243     ** return NULL. Otherwise, the entry that corresponds to docid 
138244     ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
138245     ** tree that the node is part of has been marked as EOF, but the node
138246     ** itself is not EOF, then it may point to an earlier entry. */
138247     pNear = pExpr;
138248     for(p=pExpr->pParent; p; p=p->pParent){
138249       if( p->eType==FTSQUERY_OR ) bOr = 1;
138250       if( p->eType==FTSQUERY_NEAR ) pNear = p;
138251       if( p->bEof ) bTreeEof = 1;
138252     }
138253     if( bOr==0 ) return SQLITE_OK;
138254
138255     /* This is the descendent of an OR node. In this case we cannot use
138256     ** an incremental phrase. Load the entire doclist for the phrase
138257     ** into memory in this case.  */
138258     if( pPhrase->bIncr ){
138259       int bEofSave = pNear->bEof;
138260       fts3EvalRestart(pCsr, pNear, &rc);
138261       while( rc==SQLITE_OK && !pNear->bEof ){
138262         fts3EvalNextRow(pCsr, pNear, &rc);
138263         if( bEofSave==0 && pNear->iDocid==iDocid ) break;
138264       }
138265       assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
138266     }
138267     if( bTreeEof ){
138268       while( rc==SQLITE_OK && !pNear->bEof ){
138269         fts3EvalNextRow(pCsr, pNear, &rc);
138270       }
138271     }
138272     if( rc!=SQLITE_OK ) return rc;
138273
138274     pIter = pPhrase->pOrPoslist;
138275     iDocid = pPhrase->iOrDocid;
138276     if( pCsr->bDesc==bDescDoclist ){
138277       bEof = (pIter >= (pPhrase->doclist.aAll + pPhrase->doclist.nAll));
138278       while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
138279         sqlite3Fts3DoclistNext(
138280             bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll, 
138281             &pIter, &iDocid, &bEof
138282         );
138283       }
138284     }else{
138285       bEof = !pPhrase->doclist.nAll || (pIter && pIter<=pPhrase->doclist.aAll);
138286       while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
138287         int dummy;
138288         sqlite3Fts3DoclistPrev(
138289             bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll, 
138290             &pIter, &iDocid, &dummy, &bEof
138291         );
138292       }
138293     }
138294     pPhrase->pOrPoslist = pIter;
138295     pPhrase->iOrDocid = iDocid;
138296
138297     if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
138298   }
138299   if( pIter==0 ) return SQLITE_OK;
138300
138301   if( *pIter==0x01 ){
138302     pIter++;
138303     pIter += fts3GetVarint32(pIter, &iThis);
138304   }else{
138305     iThis = 0;
138306   }
138307   while( iThis<iCol ){
138308     fts3ColumnlistCopy(0, &pIter);
138309     if( *pIter==0x00 ) return SQLITE_OK;
138310     pIter++;
138311     pIter += fts3GetVarint32(pIter, &iThis);
138312   }
138313   if( *pIter==0x00 ){
138314     pIter = 0;
138315   }
138316
138317   *ppOut = ((iCol==iThis)?pIter:0);
138318   return SQLITE_OK;
138319 }
138320
138321 /*
138322 ** Free all components of the Fts3Phrase structure that were allocated by
138323 ** the eval module. Specifically, this means to free:
138324 **
138325 **   * the contents of pPhrase->doclist, and
138326 **   * any Fts3MultiSegReader objects held by phrase tokens.
138327 */
138328 SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
138329   if( pPhrase ){
138330     int i;
138331     sqlite3_free(pPhrase->doclist.aAll);
138332     fts3EvalInvalidatePoslist(pPhrase);
138333     memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
138334     for(i=0; i<pPhrase->nToken; i++){
138335       fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
138336       pPhrase->aToken[i].pSegcsr = 0;
138337     }
138338   }
138339 }
138340
138341
138342 /*
138343 ** Return SQLITE_CORRUPT_VTAB.
138344 */
138345 #ifdef SQLITE_DEBUG
138346 SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
138347   return SQLITE_CORRUPT_VTAB;
138348 }
138349 #endif
138350
138351 #if !SQLITE_CORE
138352 /*
138353 ** Initialize API pointer table, if required.
138354 */
138355 #ifdef _WIN32
138356 __declspec(dllexport)
138357 #endif
138358 SQLITE_API int SQLITE_STDCALL sqlite3_fts3_init(
138359   sqlite3 *db, 
138360   char **pzErrMsg,
138361   const sqlite3_api_routines *pApi
138362 ){
138363   SQLITE_EXTENSION_INIT2(pApi)
138364   return sqlite3Fts3Init(db);
138365 }
138366 #endif
138367
138368 #endif
138369
138370 /************** End of fts3.c ************************************************/
138371 /************** Begin file fts3_aux.c ****************************************/
138372 /*
138373 ** 2011 Jan 27
138374 **
138375 ** The author disclaims copyright to this source code.  In place of
138376 ** a legal notice, here is a blessing:
138377 **
138378 **    May you do good and not evil.
138379 **    May you find forgiveness for yourself and forgive others.
138380 **    May you share freely, never taking more than you give.
138381 **
138382 ******************************************************************************
138383 **
138384 */
138385 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
138386
138387 /* #include <string.h> */
138388 /* #include <assert.h> */
138389
138390 typedef struct Fts3auxTable Fts3auxTable;
138391 typedef struct Fts3auxCursor Fts3auxCursor;
138392
138393 struct Fts3auxTable {
138394   sqlite3_vtab base;              /* Base class used by SQLite core */
138395   Fts3Table *pFts3Tab;
138396 };
138397
138398 struct Fts3auxCursor {
138399   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
138400   Fts3MultiSegReader csr;        /* Must be right after "base" */
138401   Fts3SegFilter filter;
138402   char *zStop;
138403   int nStop;                      /* Byte-length of string zStop */
138404   int iLangid;                    /* Language id to query */
138405   int isEof;                      /* True if cursor is at EOF */
138406   sqlite3_int64 iRowid;           /* Current rowid */
138407
138408   int iCol;                       /* Current value of 'col' column */
138409   int nStat;                      /* Size of aStat[] array */
138410   struct Fts3auxColstats {
138411     sqlite3_int64 nDoc;           /* 'documents' values for current csr row */
138412     sqlite3_int64 nOcc;           /* 'occurrences' values for current csr row */
138413   } *aStat;
138414 };
138415
138416 /*
138417 ** Schema of the terms table.
138418 */
138419 #define FTS3_AUX_SCHEMA \
138420   "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
138421
138422 /*
138423 ** This function does all the work for both the xConnect and xCreate methods.
138424 ** These tables have no persistent representation of their own, so xConnect
138425 ** and xCreate are identical operations.
138426 */
138427 static int fts3auxConnectMethod(
138428   sqlite3 *db,                    /* Database connection */
138429   void *pUnused,                  /* Unused */
138430   int argc,                       /* Number of elements in argv array */
138431   const char * const *argv,       /* xCreate/xConnect argument array */
138432   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
138433   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
138434 ){
138435   char const *zDb;                /* Name of database (e.g. "main") */
138436   char const *zFts3;              /* Name of fts3 table */
138437   int nDb;                        /* Result of strlen(zDb) */
138438   int nFts3;                      /* Result of strlen(zFts3) */
138439   int nByte;                      /* Bytes of space to allocate here */
138440   int rc;                         /* value returned by declare_vtab() */
138441   Fts3auxTable *p;                /* Virtual table object to return */
138442
138443   UNUSED_PARAMETER(pUnused);
138444
138445   /* The user should invoke this in one of two forms:
138446   **
138447   **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
138448   **     CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
138449   */
138450   if( argc!=4 && argc!=5 ) goto bad_args;
138451
138452   zDb = argv[1]; 
138453   nDb = (int)strlen(zDb);
138454   if( argc==5 ){
138455     if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
138456       zDb = argv[3]; 
138457       nDb = (int)strlen(zDb);
138458       zFts3 = argv[4];
138459     }else{
138460       goto bad_args;
138461     }
138462   }else{
138463     zFts3 = argv[3];
138464   }
138465   nFts3 = (int)strlen(zFts3);
138466
138467   rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
138468   if( rc!=SQLITE_OK ) return rc;
138469
138470   nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
138471   p = (Fts3auxTable *)sqlite3_malloc(nByte);
138472   if( !p ) return SQLITE_NOMEM;
138473   memset(p, 0, nByte);
138474
138475   p->pFts3Tab = (Fts3Table *)&p[1];
138476   p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
138477   p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
138478   p->pFts3Tab->db = db;
138479   p->pFts3Tab->nIndex = 1;
138480
138481   memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
138482   memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
138483   sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
138484
138485   *ppVtab = (sqlite3_vtab *)p;
138486   return SQLITE_OK;
138487
138488  bad_args:
138489   *pzErr = sqlite3_mprintf("invalid arguments to fts4aux constructor");
138490   return SQLITE_ERROR;
138491 }
138492
138493 /*
138494 ** This function does the work for both the xDisconnect and xDestroy methods.
138495 ** These tables have no persistent representation of their own, so xDisconnect
138496 ** and xDestroy are identical operations.
138497 */
138498 static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
138499   Fts3auxTable *p = (Fts3auxTable *)pVtab;
138500   Fts3Table *pFts3 = p->pFts3Tab;
138501   int i;
138502
138503   /* Free any prepared statements held */
138504   for(i=0; i<SizeofArray(pFts3->aStmt); i++){
138505     sqlite3_finalize(pFts3->aStmt[i]);
138506   }
138507   sqlite3_free(pFts3->zSegmentsTbl);
138508   sqlite3_free(p);
138509   return SQLITE_OK;
138510 }
138511
138512 #define FTS4AUX_EQ_CONSTRAINT 1
138513 #define FTS4AUX_GE_CONSTRAINT 2
138514 #define FTS4AUX_LE_CONSTRAINT 4
138515
138516 /*
138517 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
138518 */
138519 static int fts3auxBestIndexMethod(
138520   sqlite3_vtab *pVTab, 
138521   sqlite3_index_info *pInfo
138522 ){
138523   int i;
138524   int iEq = -1;
138525   int iGe = -1;
138526   int iLe = -1;
138527   int iLangid = -1;
138528   int iNext = 1;                  /* Next free argvIndex value */
138529
138530   UNUSED_PARAMETER(pVTab);
138531
138532   /* This vtab delivers always results in "ORDER BY term ASC" order. */
138533   if( pInfo->nOrderBy==1 
138534    && pInfo->aOrderBy[0].iColumn==0 
138535    && pInfo->aOrderBy[0].desc==0
138536   ){
138537     pInfo->orderByConsumed = 1;
138538   }
138539
138540   /* Search for equality and range constraints on the "term" column. 
138541   ** And equality constraints on the hidden "languageid" column. */
138542   for(i=0; i<pInfo->nConstraint; i++){
138543     if( pInfo->aConstraint[i].usable ){
138544       int op = pInfo->aConstraint[i].op;
138545       int iCol = pInfo->aConstraint[i].iColumn;
138546
138547       if( iCol==0 ){
138548         if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
138549         if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
138550         if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
138551         if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
138552         if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
138553       }
138554       if( iCol==4 ){
138555         if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
138556       }
138557     }
138558   }
138559
138560   if( iEq>=0 ){
138561     pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
138562     pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
138563     pInfo->estimatedCost = 5;
138564   }else{
138565     pInfo->idxNum = 0;
138566     pInfo->estimatedCost = 20000;
138567     if( iGe>=0 ){
138568       pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
138569       pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
138570       pInfo->estimatedCost /= 2;
138571     }
138572     if( iLe>=0 ){
138573       pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
138574       pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
138575       pInfo->estimatedCost /= 2;
138576     }
138577   }
138578   if( iLangid>=0 ){
138579     pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
138580     pInfo->estimatedCost--;
138581   }
138582
138583   return SQLITE_OK;
138584 }
138585
138586 /*
138587 ** xOpen - Open a cursor.
138588 */
138589 static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
138590   Fts3auxCursor *pCsr;            /* Pointer to cursor object to return */
138591
138592   UNUSED_PARAMETER(pVTab);
138593
138594   pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
138595   if( !pCsr ) return SQLITE_NOMEM;
138596   memset(pCsr, 0, sizeof(Fts3auxCursor));
138597
138598   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
138599   return SQLITE_OK;
138600 }
138601
138602 /*
138603 ** xClose - Close a cursor.
138604 */
138605 static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
138606   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
138607   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
138608
138609   sqlite3Fts3SegmentsClose(pFts3);
138610   sqlite3Fts3SegReaderFinish(&pCsr->csr);
138611   sqlite3_free((void *)pCsr->filter.zTerm);
138612   sqlite3_free(pCsr->zStop);
138613   sqlite3_free(pCsr->aStat);
138614   sqlite3_free(pCsr);
138615   return SQLITE_OK;
138616 }
138617
138618 static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
138619   if( nSize>pCsr->nStat ){
138620     struct Fts3auxColstats *aNew;
138621     aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat, 
138622         sizeof(struct Fts3auxColstats) * nSize
138623     );
138624     if( aNew==0 ) return SQLITE_NOMEM;
138625     memset(&aNew[pCsr->nStat], 0, 
138626         sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
138627     );
138628     pCsr->aStat = aNew;
138629     pCsr->nStat = nSize;
138630   }
138631   return SQLITE_OK;
138632 }
138633
138634 /*
138635 ** xNext - Advance the cursor to the next row, if any.
138636 */
138637 static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
138638   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
138639   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
138640   int rc;
138641
138642   /* Increment our pretend rowid value. */
138643   pCsr->iRowid++;
138644
138645   for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
138646     if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
138647   }
138648
138649   rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
138650   if( rc==SQLITE_ROW ){
138651     int i = 0;
138652     int nDoclist = pCsr->csr.nDoclist;
138653     char *aDoclist = pCsr->csr.aDoclist;
138654     int iCol;
138655
138656     int eState = 0;
138657
138658     if( pCsr->zStop ){
138659       int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
138660       int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
138661       if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
138662         pCsr->isEof = 1;
138663         return SQLITE_OK;
138664       }
138665     }
138666
138667     if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
138668     memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
138669     iCol = 0;
138670
138671     while( i<nDoclist ){
138672       sqlite3_int64 v = 0;
138673
138674       i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
138675       switch( eState ){
138676         /* State 0. In this state the integer just read was a docid. */
138677         case 0:
138678           pCsr->aStat[0].nDoc++;
138679           eState = 1;
138680           iCol = 0;
138681           break;
138682
138683         /* State 1. In this state we are expecting either a 1, indicating
138684         ** that the following integer will be a column number, or the
138685         ** start of a position list for column 0.  
138686         ** 
138687         ** The only difference between state 1 and state 2 is that if the
138688         ** integer encountered in state 1 is not 0 or 1, then we need to
138689         ** increment the column 0 "nDoc" count for this term.
138690         */
138691         case 1:
138692           assert( iCol==0 );
138693           if( v>1 ){
138694             pCsr->aStat[1].nDoc++;
138695           }
138696           eState = 2;
138697           /* fall through */
138698
138699         case 2:
138700           if( v==0 ){       /* 0x00. Next integer will be a docid. */
138701             eState = 0;
138702           }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
138703             eState = 3;
138704           }else{            /* 2 or greater. A position. */
138705             pCsr->aStat[iCol+1].nOcc++;
138706             pCsr->aStat[0].nOcc++;
138707           }
138708           break;
138709
138710         /* State 3. The integer just read is a column number. */
138711         default: assert( eState==3 );
138712           iCol = (int)v;
138713           if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
138714           pCsr->aStat[iCol+1].nDoc++;
138715           eState = 2;
138716           break;
138717       }
138718     }
138719
138720     pCsr->iCol = 0;
138721     rc = SQLITE_OK;
138722   }else{
138723     pCsr->isEof = 1;
138724   }
138725   return rc;
138726 }
138727
138728 /*
138729 ** xFilter - Initialize a cursor to point at the start of its data.
138730 */
138731 static int fts3auxFilterMethod(
138732   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
138733   int idxNum,                     /* Strategy index */
138734   const char *idxStr,             /* Unused */
138735   int nVal,                       /* Number of elements in apVal */
138736   sqlite3_value **apVal           /* Arguments for the indexing scheme */
138737 ){
138738   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
138739   Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
138740   int rc;
138741   int isScan = 0;
138742   int iLangVal = 0;               /* Language id to query */
138743
138744   int iEq = -1;                   /* Index of term=? value in apVal */
138745   int iGe = -1;                   /* Index of term>=? value in apVal */
138746   int iLe = -1;                   /* Index of term<=? value in apVal */
138747   int iLangid = -1;               /* Index of languageid=? value in apVal */
138748   int iNext = 0;
138749
138750   UNUSED_PARAMETER(nVal);
138751   UNUSED_PARAMETER(idxStr);
138752
138753   assert( idxStr==0 );
138754   assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
138755        || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
138756        || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
138757   );
138758
138759   if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
138760     iEq = iNext++;
138761   }else{
138762     isScan = 1;
138763     if( idxNum & FTS4AUX_GE_CONSTRAINT ){
138764       iGe = iNext++;
138765     }
138766     if( idxNum & FTS4AUX_LE_CONSTRAINT ){
138767       iLe = iNext++;
138768     }
138769   }
138770   if( iNext<nVal ){
138771     iLangid = iNext++;
138772   }
138773
138774   /* In case this cursor is being reused, close and zero it. */
138775   testcase(pCsr->filter.zTerm);
138776   sqlite3Fts3SegReaderFinish(&pCsr->csr);
138777   sqlite3_free((void *)pCsr->filter.zTerm);
138778   sqlite3_free(pCsr->aStat);
138779   memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
138780
138781   pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
138782   if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
138783
138784   if( iEq>=0 || iGe>=0 ){
138785     const unsigned char *zStr = sqlite3_value_text(apVal[0]);
138786     assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
138787     if( zStr ){
138788       pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
138789       pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
138790       if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
138791     }
138792   }
138793
138794   if( iLe>=0 ){
138795     pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
138796     pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
138797     if( pCsr->zStop==0 ) return SQLITE_NOMEM;
138798   }
138799   
138800   if( iLangid>=0 ){
138801     iLangVal = sqlite3_value_int(apVal[iLangid]);
138802
138803     /* If the user specified a negative value for the languageid, use zero
138804     ** instead. This works, as the "languageid=?" constraint will also
138805     ** be tested by the VDBE layer. The test will always be false (since
138806     ** this module will not return a row with a negative languageid), and
138807     ** so the overall query will return zero rows.  */
138808     if( iLangVal<0 ) iLangVal = 0;
138809   }
138810   pCsr->iLangid = iLangVal;
138811
138812   rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
138813       pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
138814   );
138815   if( rc==SQLITE_OK ){
138816     rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
138817   }
138818
138819   if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
138820   return rc;
138821 }
138822
138823 /*
138824 ** xEof - Return true if the cursor is at EOF, or false otherwise.
138825 */
138826 static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
138827   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
138828   return pCsr->isEof;
138829 }
138830
138831 /*
138832 ** xColumn - Return a column value.
138833 */
138834 static int fts3auxColumnMethod(
138835   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
138836   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
138837   int iCol                        /* Index of column to read value from */
138838 ){
138839   Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
138840
138841   assert( p->isEof==0 );
138842   switch( iCol ){
138843     case 0: /* term */
138844       sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
138845       break;
138846
138847     case 1: /* col */
138848       if( p->iCol ){
138849         sqlite3_result_int(pCtx, p->iCol-1);
138850       }else{
138851         sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
138852       }
138853       break;
138854
138855     case 2: /* documents */
138856       sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
138857       break;
138858
138859     case 3: /* occurrences */
138860       sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
138861       break;
138862
138863     default: /* languageid */
138864       assert( iCol==4 );
138865       sqlite3_result_int(pCtx, p->iLangid);
138866       break;
138867   }
138868
138869   return SQLITE_OK;
138870 }
138871
138872 /*
138873 ** xRowid - Return the current rowid for the cursor.
138874 */
138875 static int fts3auxRowidMethod(
138876   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
138877   sqlite_int64 *pRowid            /* OUT: Rowid value */
138878 ){
138879   Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
138880   *pRowid = pCsr->iRowid;
138881   return SQLITE_OK;
138882 }
138883
138884 /*
138885 ** Register the fts3aux module with database connection db. Return SQLITE_OK
138886 ** if successful or an error code if sqlite3_create_module() fails.
138887 */
138888 SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
138889   static const sqlite3_module fts3aux_module = {
138890      0,                           /* iVersion      */
138891      fts3auxConnectMethod,        /* xCreate       */
138892      fts3auxConnectMethod,        /* xConnect      */
138893      fts3auxBestIndexMethod,      /* xBestIndex    */
138894      fts3auxDisconnectMethod,     /* xDisconnect   */
138895      fts3auxDisconnectMethod,     /* xDestroy      */
138896      fts3auxOpenMethod,           /* xOpen         */
138897      fts3auxCloseMethod,          /* xClose        */
138898      fts3auxFilterMethod,         /* xFilter       */
138899      fts3auxNextMethod,           /* xNext         */
138900      fts3auxEofMethod,            /* xEof          */
138901      fts3auxColumnMethod,         /* xColumn       */
138902      fts3auxRowidMethod,          /* xRowid        */
138903      0,                           /* xUpdate       */
138904      0,                           /* xBegin        */
138905      0,                           /* xSync         */
138906      0,                           /* xCommit       */
138907      0,                           /* xRollback     */
138908      0,                           /* xFindFunction */
138909      0,                           /* xRename       */
138910      0,                           /* xSavepoint    */
138911      0,                           /* xRelease      */
138912      0                            /* xRollbackTo   */
138913   };
138914   int rc;                         /* Return code */
138915
138916   rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
138917   return rc;
138918 }
138919
138920 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
138921
138922 /************** End of fts3_aux.c ********************************************/
138923 /************** Begin file fts3_expr.c ***************************************/
138924 /*
138925 ** 2008 Nov 28
138926 **
138927 ** The author disclaims copyright to this source code.  In place of
138928 ** a legal notice, here is a blessing:
138929 **
138930 **    May you do good and not evil.
138931 **    May you find forgiveness for yourself and forgive others.
138932 **    May you share freely, never taking more than you give.
138933 **
138934 ******************************************************************************
138935 **
138936 ** This module contains code that implements a parser for fts3 query strings
138937 ** (the right-hand argument to the MATCH operator). Because the supported 
138938 ** syntax is relatively simple, the whole tokenizer/parser system is
138939 ** hand-coded. 
138940 */
138941 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
138942
138943 /*
138944 ** By default, this module parses the legacy syntax that has been 
138945 ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
138946 ** is defined, then it uses the new syntax. The differences between
138947 ** the new and the old syntaxes are:
138948 **
138949 **  a) The new syntax supports parenthesis. The old does not.
138950 **
138951 **  b) The new syntax supports the AND and NOT operators. The old does not.
138952 **
138953 **  c) The old syntax supports the "-" token qualifier. This is not 
138954 **     supported by the new syntax (it is replaced by the NOT operator).
138955 **
138956 **  d) When using the old syntax, the OR operator has a greater precedence
138957 **     than an implicit AND. When using the new, both implicity and explicit
138958 **     AND operators have a higher precedence than OR.
138959 **
138960 ** If compiled with SQLITE_TEST defined, then this module exports the
138961 ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
138962 ** to zero causes the module to use the old syntax. If it is set to 
138963 ** non-zero the new syntax is activated. This is so both syntaxes can
138964 ** be tested using a single build of testfixture.
138965 **
138966 ** The following describes the syntax supported by the fts3 MATCH
138967 ** operator in a similar format to that used by the lemon parser
138968 ** generator. This module does not use actually lemon, it uses a
138969 ** custom parser.
138970 **
138971 **   query ::= andexpr (OR andexpr)*.
138972 **
138973 **   andexpr ::= notexpr (AND? notexpr)*.
138974 **
138975 **   notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
138976 **   notexpr ::= LP query RP.
138977 **
138978 **   nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
138979 **
138980 **   distance_opt ::= .
138981 **   distance_opt ::= / INTEGER.
138982 **
138983 **   phrase ::= TOKEN.
138984 **   phrase ::= COLUMN:TOKEN.
138985 **   phrase ::= "TOKEN TOKEN TOKEN...".
138986 */
138987
138988 #ifdef SQLITE_TEST
138989 SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
138990 #else
138991 # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS 
138992 #  define sqlite3_fts3_enable_parentheses 1
138993 # else
138994 #  define sqlite3_fts3_enable_parentheses 0
138995 # endif
138996 #endif
138997
138998 /*
138999 ** Default span for NEAR operators.
139000 */
139001 #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
139002
139003 /* #include <string.h> */
139004 /* #include <assert.h> */
139005
139006 /*
139007 ** isNot:
139008 **   This variable is used by function getNextNode(). When getNextNode() is
139009 **   called, it sets ParseContext.isNot to true if the 'next node' is a 
139010 **   FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
139011 **   FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
139012 **   zero.
139013 */
139014 typedef struct ParseContext ParseContext;
139015 struct ParseContext {
139016   sqlite3_tokenizer *pTokenizer;      /* Tokenizer module */
139017   int iLangid;                        /* Language id used with tokenizer */
139018   const char **azCol;                 /* Array of column names for fts3 table */
139019   int bFts4;                          /* True to allow FTS4-only syntax */
139020   int nCol;                           /* Number of entries in azCol[] */
139021   int iDefaultCol;                    /* Default column to query */
139022   int isNot;                          /* True if getNextNode() sees a unary - */
139023   sqlite3_context *pCtx;              /* Write error message here */
139024   int nNest;                          /* Number of nested brackets */
139025 };
139026
139027 /*
139028 ** This function is equivalent to the standard isspace() function. 
139029 **
139030 ** The standard isspace() can be awkward to use safely, because although it
139031 ** is defined to accept an argument of type int, its behavior when passed
139032 ** an integer that falls outside of the range of the unsigned char type
139033 ** is undefined (and sometimes, "undefined" means segfault). This wrapper
139034 ** is defined to accept an argument of type char, and always returns 0 for
139035 ** any values that fall outside of the range of the unsigned char type (i.e.
139036 ** negative values).
139037 */
139038 static int fts3isspace(char c){
139039   return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
139040 }
139041
139042 /*
139043 ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
139044 ** zero the memory before returning a pointer to it. If unsuccessful, 
139045 ** return NULL.
139046 */
139047 static void *fts3MallocZero(int nByte){
139048   void *pRet = sqlite3_malloc(nByte);
139049   if( pRet ) memset(pRet, 0, nByte);
139050   return pRet;
139051 }
139052
139053 SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
139054   sqlite3_tokenizer *pTokenizer,
139055   int iLangid,
139056   const char *z,
139057   int n,
139058   sqlite3_tokenizer_cursor **ppCsr
139059 ){
139060   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
139061   sqlite3_tokenizer_cursor *pCsr = 0;
139062   int rc;
139063
139064   rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
139065   assert( rc==SQLITE_OK || pCsr==0 );
139066   if( rc==SQLITE_OK ){
139067     pCsr->pTokenizer = pTokenizer;
139068     if( pModule->iVersion>=1 ){
139069       rc = pModule->xLanguageid(pCsr, iLangid);
139070       if( rc!=SQLITE_OK ){
139071         pModule->xClose(pCsr);
139072         pCsr = 0;
139073       }
139074     }
139075   }
139076   *ppCsr = pCsr;
139077   return rc;
139078 }
139079
139080 /*
139081 ** Function getNextNode(), which is called by fts3ExprParse(), may itself
139082 ** call fts3ExprParse(). So this forward declaration is required.
139083 */
139084 static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
139085
139086 /*
139087 ** Extract the next token from buffer z (length n) using the tokenizer
139088 ** and other information (column names etc.) in pParse. Create an Fts3Expr
139089 ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
139090 ** single token and set *ppExpr to point to it. If the end of the buffer is
139091 ** reached before a token is found, set *ppExpr to zero. It is the
139092 ** responsibility of the caller to eventually deallocate the allocated 
139093 ** Fts3Expr structure (if any) by passing it to sqlite3_free().
139094 **
139095 ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
139096 ** fails.
139097 */
139098 static int getNextToken(
139099   ParseContext *pParse,                   /* fts3 query parse context */
139100   int iCol,                               /* Value for Fts3Phrase.iColumn */
139101   const char *z, int n,                   /* Input string */
139102   Fts3Expr **ppExpr,                      /* OUT: expression */
139103   int *pnConsumed                         /* OUT: Number of bytes consumed */
139104 ){
139105   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
139106   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
139107   int rc;
139108   sqlite3_tokenizer_cursor *pCursor;
139109   Fts3Expr *pRet = 0;
139110   int i = 0;
139111
139112   /* Set variable i to the maximum number of bytes of input to tokenize. */
139113   for(i=0; i<n; i++){
139114     if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
139115     if( z[i]=='"' ) break;
139116   }
139117
139118   *pnConsumed = i;
139119   rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
139120   if( rc==SQLITE_OK ){
139121     const char *zToken;
139122     int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
139123     int nByte;                               /* total space to allocate */
139124
139125     rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
139126     if( rc==SQLITE_OK ){
139127       nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
139128       pRet = (Fts3Expr *)fts3MallocZero(nByte);
139129       if( !pRet ){
139130         rc = SQLITE_NOMEM;
139131       }else{
139132         pRet->eType = FTSQUERY_PHRASE;
139133         pRet->pPhrase = (Fts3Phrase *)&pRet[1];
139134         pRet->pPhrase->nToken = 1;
139135         pRet->pPhrase->iColumn = iCol;
139136         pRet->pPhrase->aToken[0].n = nToken;
139137         pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
139138         memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
139139
139140         if( iEnd<n && z[iEnd]=='*' ){
139141           pRet->pPhrase->aToken[0].isPrefix = 1;
139142           iEnd++;
139143         }
139144
139145         while( 1 ){
139146           if( !sqlite3_fts3_enable_parentheses 
139147            && iStart>0 && z[iStart-1]=='-' 
139148           ){
139149             pParse->isNot = 1;
139150             iStart--;
139151           }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
139152             pRet->pPhrase->aToken[0].bFirst = 1;
139153             iStart--;
139154           }else{
139155             break;
139156           }
139157         }
139158
139159       }
139160       *pnConsumed = iEnd;
139161     }else if( i && rc==SQLITE_DONE ){
139162       rc = SQLITE_OK;
139163     }
139164
139165     pModule->xClose(pCursor);
139166   }
139167   
139168   *ppExpr = pRet;
139169   return rc;
139170 }
139171
139172
139173 /*
139174 ** Enlarge a memory allocation.  If an out-of-memory allocation occurs,
139175 ** then free the old allocation.
139176 */
139177 static void *fts3ReallocOrFree(void *pOrig, int nNew){
139178   void *pRet = sqlite3_realloc(pOrig, nNew);
139179   if( !pRet ){
139180     sqlite3_free(pOrig);
139181   }
139182   return pRet;
139183 }
139184
139185 /*
139186 ** Buffer zInput, length nInput, contains the contents of a quoted string
139187 ** that appeared as part of an fts3 query expression. Neither quote character
139188 ** is included in the buffer. This function attempts to tokenize the entire
139189 ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE 
139190 ** containing the results.
139191 **
139192 ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
139193 ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
139194 ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
139195 ** to 0.
139196 */
139197 static int getNextString(
139198   ParseContext *pParse,                   /* fts3 query parse context */
139199   const char *zInput, int nInput,         /* Input string */
139200   Fts3Expr **ppExpr                       /* OUT: expression */
139201 ){
139202   sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
139203   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
139204   int rc;
139205   Fts3Expr *p = 0;
139206   sqlite3_tokenizer_cursor *pCursor = 0;
139207   char *zTemp = 0;
139208   int nTemp = 0;
139209
139210   const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
139211   int nToken = 0;
139212
139213   /* The final Fts3Expr data structure, including the Fts3Phrase,
139214   ** Fts3PhraseToken structures token buffers are all stored as a single 
139215   ** allocation so that the expression can be freed with a single call to
139216   ** sqlite3_free(). Setting this up requires a two pass approach.
139217   **
139218   ** The first pass, in the block below, uses a tokenizer cursor to iterate
139219   ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
139220   ** to assemble data in two dynamic buffers:
139221   **
139222   **   Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
139223   **             structure, followed by the array of Fts3PhraseToken 
139224   **             structures. This pass only populates the Fts3PhraseToken array.
139225   **
139226   **   Buffer zTemp: Contains copies of all tokens.
139227   **
139228   ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
139229   ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
139230   ** structures.
139231   */
139232   rc = sqlite3Fts3OpenTokenizer(
139233       pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
139234   if( rc==SQLITE_OK ){
139235     int ii;
139236     for(ii=0; rc==SQLITE_OK; ii++){
139237       const char *zByte;
139238       int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
139239       rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
139240       if( rc==SQLITE_OK ){
139241         Fts3PhraseToken *pToken;
139242
139243         p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
139244         if( !p ) goto no_mem;
139245
139246         zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
139247         if( !zTemp ) goto no_mem;
139248
139249         assert( nToken==ii );
139250         pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
139251         memset(pToken, 0, sizeof(Fts3PhraseToken));
139252
139253         memcpy(&zTemp[nTemp], zByte, nByte);
139254         nTemp += nByte;
139255
139256         pToken->n = nByte;
139257         pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
139258         pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
139259         nToken = ii+1;
139260       }
139261     }
139262
139263     pModule->xClose(pCursor);
139264     pCursor = 0;
139265   }
139266
139267   if( rc==SQLITE_DONE ){
139268     int jj;
139269     char *zBuf = 0;
139270
139271     p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
139272     if( !p ) goto no_mem;
139273     memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
139274     p->eType = FTSQUERY_PHRASE;
139275     p->pPhrase = (Fts3Phrase *)&p[1];
139276     p->pPhrase->iColumn = pParse->iDefaultCol;
139277     p->pPhrase->nToken = nToken;
139278
139279     zBuf = (char *)&p->pPhrase->aToken[nToken];
139280     if( zTemp ){
139281       memcpy(zBuf, zTemp, nTemp);
139282       sqlite3_free(zTemp);
139283     }else{
139284       assert( nTemp==0 );
139285     }
139286
139287     for(jj=0; jj<p->pPhrase->nToken; jj++){
139288       p->pPhrase->aToken[jj].z = zBuf;
139289       zBuf += p->pPhrase->aToken[jj].n;
139290     }
139291     rc = SQLITE_OK;
139292   }
139293
139294   *ppExpr = p;
139295   return rc;
139296 no_mem:
139297
139298   if( pCursor ){
139299     pModule->xClose(pCursor);
139300   }
139301   sqlite3_free(zTemp);
139302   sqlite3_free(p);
139303   *ppExpr = 0;
139304   return SQLITE_NOMEM;
139305 }
139306
139307 /*
139308 ** The output variable *ppExpr is populated with an allocated Fts3Expr 
139309 ** structure, or set to 0 if the end of the input buffer is reached.
139310 **
139311 ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
139312 ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
139313 ** If SQLITE_ERROR is returned, pContext is populated with an error message.
139314 */
139315 static int getNextNode(
139316   ParseContext *pParse,                   /* fts3 query parse context */
139317   const char *z, int n,                   /* Input string */
139318   Fts3Expr **ppExpr,                      /* OUT: expression */
139319   int *pnConsumed                         /* OUT: Number of bytes consumed */
139320 ){
139321   static const struct Fts3Keyword {
139322     char *z;                              /* Keyword text */
139323     unsigned char n;                      /* Length of the keyword */
139324     unsigned char parenOnly;              /* Only valid in paren mode */
139325     unsigned char eType;                  /* Keyword code */
139326   } aKeyword[] = {
139327     { "OR" ,  2, 0, FTSQUERY_OR   },
139328     { "AND",  3, 1, FTSQUERY_AND  },
139329     { "NOT",  3, 1, FTSQUERY_NOT  },
139330     { "NEAR", 4, 0, FTSQUERY_NEAR }
139331   };
139332   int ii;
139333   int iCol;
139334   int iColLen;
139335   int rc;
139336   Fts3Expr *pRet = 0;
139337
139338   const char *zInput = z;
139339   int nInput = n;
139340
139341   pParse->isNot = 0;
139342
139343   /* Skip over any whitespace before checking for a keyword, an open or
139344   ** close bracket, or a quoted string. 
139345   */
139346   while( nInput>0 && fts3isspace(*zInput) ){
139347     nInput--;
139348     zInput++;
139349   }
139350   if( nInput==0 ){
139351     return SQLITE_DONE;
139352   }
139353
139354   /* See if we are dealing with a keyword. */
139355   for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
139356     const struct Fts3Keyword *pKey = &aKeyword[ii];
139357
139358     if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
139359       continue;
139360     }
139361
139362     if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
139363       int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
139364       int nKey = pKey->n;
139365       char cNext;
139366
139367       /* If this is a "NEAR" keyword, check for an explicit nearness. */
139368       if( pKey->eType==FTSQUERY_NEAR ){
139369         assert( nKey==4 );
139370         if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
139371           nNear = 0;
139372           for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
139373             nNear = nNear * 10 + (zInput[nKey] - '0');
139374           }
139375         }
139376       }
139377
139378       /* At this point this is probably a keyword. But for that to be true,
139379       ** the next byte must contain either whitespace, an open or close
139380       ** parenthesis, a quote character, or EOF. 
139381       */
139382       cNext = zInput[nKey];
139383       if( fts3isspace(cNext) 
139384        || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
139385       ){
139386         pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
139387         if( !pRet ){
139388           return SQLITE_NOMEM;
139389         }
139390         pRet->eType = pKey->eType;
139391         pRet->nNear = nNear;
139392         *ppExpr = pRet;
139393         *pnConsumed = (int)((zInput - z) + nKey);
139394         return SQLITE_OK;
139395       }
139396
139397       /* Turns out that wasn't a keyword after all. This happens if the
139398       ** user has supplied a token such as "ORacle". Continue.
139399       */
139400     }
139401   }
139402
139403   /* See if we are dealing with a quoted phrase. If this is the case, then
139404   ** search for the closing quote and pass the whole string to getNextString()
139405   ** for processing. This is easy to do, as fts3 has no syntax for escaping
139406   ** a quote character embedded in a string.
139407   */
139408   if( *zInput=='"' ){
139409     for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
139410     *pnConsumed = (int)((zInput - z) + ii + 1);
139411     if( ii==nInput ){
139412       return SQLITE_ERROR;
139413     }
139414     return getNextString(pParse, &zInput[1], ii-1, ppExpr);
139415   }
139416
139417   if( sqlite3_fts3_enable_parentheses ){
139418     if( *zInput=='(' ){
139419       int nConsumed = 0;
139420       pParse->nNest++;
139421       rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
139422       if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
139423       *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
139424       return rc;
139425     }else if( *zInput==')' ){
139426       pParse->nNest--;
139427       *pnConsumed = (int)((zInput - z) + 1);
139428       *ppExpr = 0;
139429       return SQLITE_DONE;
139430     }
139431   }
139432
139433   /* If control flows to this point, this must be a regular token, or 
139434   ** the end of the input. Read a regular token using the sqlite3_tokenizer
139435   ** interface. Before doing so, figure out if there is an explicit
139436   ** column specifier for the token. 
139437   **
139438   ** TODO: Strangely, it is not possible to associate a column specifier
139439   ** with a quoted phrase, only with a single token. Not sure if this was
139440   ** an implementation artifact or an intentional decision when fts3 was
139441   ** first implemented. Whichever it was, this module duplicates the 
139442   ** limitation.
139443   */
139444   iCol = pParse->iDefaultCol;
139445   iColLen = 0;
139446   for(ii=0; ii<pParse->nCol; ii++){
139447     const char *zStr = pParse->azCol[ii];
139448     int nStr = (int)strlen(zStr);
139449     if( nInput>nStr && zInput[nStr]==':' 
139450      && sqlite3_strnicmp(zStr, zInput, nStr)==0 
139451     ){
139452       iCol = ii;
139453       iColLen = (int)((zInput - z) + nStr + 1);
139454       break;
139455     }
139456   }
139457   rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
139458   *pnConsumed += iColLen;
139459   return rc;
139460 }
139461
139462 /*
139463 ** The argument is an Fts3Expr structure for a binary operator (any type
139464 ** except an FTSQUERY_PHRASE). Return an integer value representing the
139465 ** precedence of the operator. Lower values have a higher precedence (i.e.
139466 ** group more tightly). For example, in the C language, the == operator
139467 ** groups more tightly than ||, and would therefore have a higher precedence.
139468 **
139469 ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
139470 ** is defined), the order of the operators in precedence from highest to
139471 ** lowest is:
139472 **
139473 **   NEAR
139474 **   NOT
139475 **   AND (including implicit ANDs)
139476 **   OR
139477 **
139478 ** Note that when using the old query syntax, the OR operator has a higher
139479 ** precedence than the AND operator.
139480 */
139481 static int opPrecedence(Fts3Expr *p){
139482   assert( p->eType!=FTSQUERY_PHRASE );
139483   if( sqlite3_fts3_enable_parentheses ){
139484     return p->eType;
139485   }else if( p->eType==FTSQUERY_NEAR ){
139486     return 1;
139487   }else if( p->eType==FTSQUERY_OR ){
139488     return 2;
139489   }
139490   assert( p->eType==FTSQUERY_AND );
139491   return 3;
139492 }
139493
139494 /*
139495 ** Argument ppHead contains a pointer to the current head of a query 
139496 ** expression tree being parsed. pPrev is the expression node most recently
139497 ** inserted into the tree. This function adds pNew, which is always a binary
139498 ** operator node, into the expression tree based on the relative precedence
139499 ** of pNew and the existing nodes of the tree. This may result in the head
139500 ** of the tree changing, in which case *ppHead is set to the new root node.
139501 */
139502 static void insertBinaryOperator(
139503   Fts3Expr **ppHead,       /* Pointer to the root node of a tree */
139504   Fts3Expr *pPrev,         /* Node most recently inserted into the tree */
139505   Fts3Expr *pNew           /* New binary node to insert into expression tree */
139506 ){
139507   Fts3Expr *pSplit = pPrev;
139508   while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
139509     pSplit = pSplit->pParent;
139510   }
139511
139512   if( pSplit->pParent ){
139513     assert( pSplit->pParent->pRight==pSplit );
139514     pSplit->pParent->pRight = pNew;
139515     pNew->pParent = pSplit->pParent;
139516   }else{
139517     *ppHead = pNew;
139518   }
139519   pNew->pLeft = pSplit;
139520   pSplit->pParent = pNew;
139521 }
139522
139523 /*
139524 ** Parse the fts3 query expression found in buffer z, length n. This function
139525 ** returns either when the end of the buffer is reached or an unmatched 
139526 ** closing bracket - ')' - is encountered.
139527 **
139528 ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
139529 ** parsed form of the expression and *pnConsumed is set to the number of
139530 ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
139531 ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
139532 */
139533 static int fts3ExprParse(
139534   ParseContext *pParse,                   /* fts3 query parse context */
139535   const char *z, int n,                   /* Text of MATCH query */
139536   Fts3Expr **ppExpr,                      /* OUT: Parsed query structure */
139537   int *pnConsumed                         /* OUT: Number of bytes consumed */
139538 ){
139539   Fts3Expr *pRet = 0;
139540   Fts3Expr *pPrev = 0;
139541   Fts3Expr *pNotBranch = 0;               /* Only used in legacy parse mode */
139542   int nIn = n;
139543   const char *zIn = z;
139544   int rc = SQLITE_OK;
139545   int isRequirePhrase = 1;
139546
139547   while( rc==SQLITE_OK ){
139548     Fts3Expr *p = 0;
139549     int nByte = 0;
139550
139551     rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
139552     assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
139553     if( rc==SQLITE_OK ){
139554       if( p ){
139555         int isPhrase;
139556
139557         if( !sqlite3_fts3_enable_parentheses 
139558             && p->eType==FTSQUERY_PHRASE && pParse->isNot 
139559         ){
139560           /* Create an implicit NOT operator. */
139561           Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
139562           if( !pNot ){
139563             sqlite3Fts3ExprFree(p);
139564             rc = SQLITE_NOMEM;
139565             goto exprparse_out;
139566           }
139567           pNot->eType = FTSQUERY_NOT;
139568           pNot->pRight = p;
139569           p->pParent = pNot;
139570           if( pNotBranch ){
139571             pNot->pLeft = pNotBranch;
139572             pNotBranch->pParent = pNot;
139573           }
139574           pNotBranch = pNot;
139575           p = pPrev;
139576         }else{
139577           int eType = p->eType;
139578           isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
139579
139580           /* The isRequirePhrase variable is set to true if a phrase or
139581           ** an expression contained in parenthesis is required. If a
139582           ** binary operator (AND, OR, NOT or NEAR) is encounted when
139583           ** isRequirePhrase is set, this is a syntax error.
139584           */
139585           if( !isPhrase && isRequirePhrase ){
139586             sqlite3Fts3ExprFree(p);
139587             rc = SQLITE_ERROR;
139588             goto exprparse_out;
139589           }
139590
139591           if( isPhrase && !isRequirePhrase ){
139592             /* Insert an implicit AND operator. */
139593             Fts3Expr *pAnd;
139594             assert( pRet && pPrev );
139595             pAnd = fts3MallocZero(sizeof(Fts3Expr));
139596             if( !pAnd ){
139597               sqlite3Fts3ExprFree(p);
139598               rc = SQLITE_NOMEM;
139599               goto exprparse_out;
139600             }
139601             pAnd->eType = FTSQUERY_AND;
139602             insertBinaryOperator(&pRet, pPrev, pAnd);
139603             pPrev = pAnd;
139604           }
139605
139606           /* This test catches attempts to make either operand of a NEAR
139607            ** operator something other than a phrase. For example, either of
139608            ** the following:
139609            **
139610            **    (bracketed expression) NEAR phrase
139611            **    phrase NEAR (bracketed expression)
139612            **
139613            ** Return an error in either case.
139614            */
139615           if( pPrev && (
139616             (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
139617          || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
139618           )){
139619             sqlite3Fts3ExprFree(p);
139620             rc = SQLITE_ERROR;
139621             goto exprparse_out;
139622           }
139623
139624           if( isPhrase ){
139625             if( pRet ){
139626               assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
139627               pPrev->pRight = p;
139628               p->pParent = pPrev;
139629             }else{
139630               pRet = p;
139631             }
139632           }else{
139633             insertBinaryOperator(&pRet, pPrev, p);
139634           }
139635           isRequirePhrase = !isPhrase;
139636         }
139637         pPrev = p;
139638       }
139639       assert( nByte>0 );
139640     }
139641     assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
139642     nIn -= nByte;
139643     zIn += nByte;
139644   }
139645
139646   if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
139647     rc = SQLITE_ERROR;
139648   }
139649
139650   if( rc==SQLITE_DONE ){
139651     rc = SQLITE_OK;
139652     if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
139653       if( !pRet ){
139654         rc = SQLITE_ERROR;
139655       }else{
139656         Fts3Expr *pIter = pNotBranch;
139657         while( pIter->pLeft ){
139658           pIter = pIter->pLeft;
139659         }
139660         pIter->pLeft = pRet;
139661         pRet->pParent = pIter;
139662         pRet = pNotBranch;
139663       }
139664     }
139665   }
139666   *pnConsumed = n - nIn;
139667
139668 exprparse_out:
139669   if( rc!=SQLITE_OK ){
139670     sqlite3Fts3ExprFree(pRet);
139671     sqlite3Fts3ExprFree(pNotBranch);
139672     pRet = 0;
139673   }
139674   *ppExpr = pRet;
139675   return rc;
139676 }
139677
139678 /*
139679 ** Return SQLITE_ERROR if the maximum depth of the expression tree passed 
139680 ** as the only argument is more than nMaxDepth.
139681 */
139682 static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
139683   int rc = SQLITE_OK;
139684   if( p ){
139685     if( nMaxDepth<0 ){ 
139686       rc = SQLITE_TOOBIG;
139687     }else{
139688       rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
139689       if( rc==SQLITE_OK ){
139690         rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
139691       }
139692     }
139693   }
139694   return rc;
139695 }
139696
139697 /*
139698 ** This function attempts to transform the expression tree at (*pp) to
139699 ** an equivalent but more balanced form. The tree is modified in place.
139700 ** If successful, SQLITE_OK is returned and (*pp) set to point to the 
139701 ** new root expression node. 
139702 **
139703 ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
139704 **
139705 ** Otherwise, if an error occurs, an SQLite error code is returned and 
139706 ** expression (*pp) freed.
139707 */
139708 static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
139709   int rc = SQLITE_OK;             /* Return code */
139710   Fts3Expr *pRoot = *pp;          /* Initial root node */
139711   Fts3Expr *pFree = 0;            /* List of free nodes. Linked by pParent. */
139712   int eType = pRoot->eType;       /* Type of node in this tree */
139713
139714   if( nMaxDepth==0 ){
139715     rc = SQLITE_ERROR;
139716   }
139717
139718   if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
139719     Fts3Expr **apLeaf;
139720     apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
139721     if( 0==apLeaf ){
139722       rc = SQLITE_NOMEM;
139723     }else{
139724       memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
139725     }
139726
139727     if( rc==SQLITE_OK ){
139728       int i;
139729       Fts3Expr *p;
139730
139731       /* Set $p to point to the left-most leaf in the tree of eType nodes. */
139732       for(p=pRoot; p->eType==eType; p=p->pLeft){
139733         assert( p->pParent==0 || p->pParent->pLeft==p );
139734         assert( p->pLeft && p->pRight );
139735       }
139736
139737       /* This loop runs once for each leaf in the tree of eType nodes. */
139738       while( 1 ){
139739         int iLvl;
139740         Fts3Expr *pParent = p->pParent;     /* Current parent of p */
139741
139742         assert( pParent==0 || pParent->pLeft==p );
139743         p->pParent = 0;
139744         if( pParent ){
139745           pParent->pLeft = 0;
139746         }else{
139747           pRoot = 0;
139748         }
139749         rc = fts3ExprBalance(&p, nMaxDepth-1);
139750         if( rc!=SQLITE_OK ) break;
139751
139752         for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
139753           if( apLeaf[iLvl]==0 ){
139754             apLeaf[iLvl] = p;
139755             p = 0;
139756           }else{
139757             assert( pFree );
139758             pFree->pLeft = apLeaf[iLvl];
139759             pFree->pRight = p;
139760             pFree->pLeft->pParent = pFree;
139761             pFree->pRight->pParent = pFree;
139762
139763             p = pFree;
139764             pFree = pFree->pParent;
139765             p->pParent = 0;
139766             apLeaf[iLvl] = 0;
139767           }
139768         }
139769         if( p ){
139770           sqlite3Fts3ExprFree(p);
139771           rc = SQLITE_TOOBIG;
139772           break;
139773         }
139774
139775         /* If that was the last leaf node, break out of the loop */
139776         if( pParent==0 ) break;
139777
139778         /* Set $p to point to the next leaf in the tree of eType nodes */
139779         for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
139780
139781         /* Remove pParent from the original tree. */
139782         assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
139783         pParent->pRight->pParent = pParent->pParent;
139784         if( pParent->pParent ){
139785           pParent->pParent->pLeft = pParent->pRight;
139786         }else{
139787           assert( pParent==pRoot );
139788           pRoot = pParent->pRight;
139789         }
139790
139791         /* Link pParent into the free node list. It will be used as an
139792         ** internal node of the new tree.  */
139793         pParent->pParent = pFree;
139794         pFree = pParent;
139795       }
139796
139797       if( rc==SQLITE_OK ){
139798         p = 0;
139799         for(i=0; i<nMaxDepth; i++){
139800           if( apLeaf[i] ){
139801             if( p==0 ){
139802               p = apLeaf[i];
139803               p->pParent = 0;
139804             }else{
139805               assert( pFree!=0 );
139806               pFree->pRight = p;
139807               pFree->pLeft = apLeaf[i];
139808               pFree->pLeft->pParent = pFree;
139809               pFree->pRight->pParent = pFree;
139810
139811               p = pFree;
139812               pFree = pFree->pParent;
139813               p->pParent = 0;
139814             }
139815           }
139816         }
139817         pRoot = p;
139818       }else{
139819         /* An error occurred. Delete the contents of the apLeaf[] array 
139820         ** and pFree list. Everything else is cleaned up by the call to
139821         ** sqlite3Fts3ExprFree(pRoot) below.  */
139822         Fts3Expr *pDel;
139823         for(i=0; i<nMaxDepth; i++){
139824           sqlite3Fts3ExprFree(apLeaf[i]);
139825         }
139826         while( (pDel=pFree)!=0 ){
139827           pFree = pDel->pParent;
139828           sqlite3_free(pDel);
139829         }
139830       }
139831
139832       assert( pFree==0 );
139833       sqlite3_free( apLeaf );
139834     }
139835   }
139836
139837   if( rc!=SQLITE_OK ){
139838     sqlite3Fts3ExprFree(pRoot);
139839     pRoot = 0;
139840   }
139841   *pp = pRoot;
139842   return rc;
139843 }
139844
139845 /*
139846 ** This function is similar to sqlite3Fts3ExprParse(), with the following
139847 ** differences:
139848 **
139849 **   1. It does not do expression rebalancing.
139850 **   2. It does not check that the expression does not exceed the 
139851 **      maximum allowable depth.
139852 **   3. Even if it fails, *ppExpr may still be set to point to an 
139853 **      expression tree. It should be deleted using sqlite3Fts3ExprFree()
139854 **      in this case.
139855 */
139856 static int fts3ExprParseUnbalanced(
139857   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
139858   int iLangid,                        /* Language id for tokenizer */
139859   char **azCol,                       /* Array of column names for fts3 table */
139860   int bFts4,                          /* True to allow FTS4-only syntax */
139861   int nCol,                           /* Number of entries in azCol[] */
139862   int iDefaultCol,                    /* Default column to query */
139863   const char *z, int n,               /* Text of MATCH query */
139864   Fts3Expr **ppExpr                   /* OUT: Parsed query structure */
139865 ){
139866   int nParsed;
139867   int rc;
139868   ParseContext sParse;
139869
139870   memset(&sParse, 0, sizeof(ParseContext));
139871   sParse.pTokenizer = pTokenizer;
139872   sParse.iLangid = iLangid;
139873   sParse.azCol = (const char **)azCol;
139874   sParse.nCol = nCol;
139875   sParse.iDefaultCol = iDefaultCol;
139876   sParse.bFts4 = bFts4;
139877   if( z==0 ){
139878     *ppExpr = 0;
139879     return SQLITE_OK;
139880   }
139881   if( n<0 ){
139882     n = (int)strlen(z);
139883   }
139884   rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
139885   assert( rc==SQLITE_OK || *ppExpr==0 );
139886
139887   /* Check for mismatched parenthesis */
139888   if( rc==SQLITE_OK && sParse.nNest ){
139889     rc = SQLITE_ERROR;
139890   }
139891   
139892   return rc;
139893 }
139894
139895 /*
139896 ** Parameters z and n contain a pointer to and length of a buffer containing
139897 ** an fts3 query expression, respectively. This function attempts to parse the
139898 ** query expression and create a tree of Fts3Expr structures representing the
139899 ** parsed expression. If successful, *ppExpr is set to point to the head
139900 ** of the parsed expression tree and SQLITE_OK is returned. If an error
139901 ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
139902 ** error) is returned and *ppExpr is set to 0.
139903 **
139904 ** If parameter n is a negative number, then z is assumed to point to a
139905 ** nul-terminated string and the length is determined using strlen().
139906 **
139907 ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
139908 ** use to normalize query tokens while parsing the expression. The azCol[]
139909 ** array, which is assumed to contain nCol entries, should contain the names
139910 ** of each column in the target fts3 table, in order from left to right. 
139911 ** Column names must be nul-terminated strings.
139912 **
139913 ** The iDefaultCol parameter should be passed the index of the table column
139914 ** that appears on the left-hand-side of the MATCH operator (the default
139915 ** column to match against for tokens for which a column name is not explicitly
139916 ** specified as part of the query string), or -1 if tokens may by default
139917 ** match any table column.
139918 */
139919 SQLITE_PRIVATE int sqlite3Fts3ExprParse(
139920   sqlite3_tokenizer *pTokenizer,      /* Tokenizer module */
139921   int iLangid,                        /* Language id for tokenizer */
139922   char **azCol,                       /* Array of column names for fts3 table */
139923   int bFts4,                          /* True to allow FTS4-only syntax */
139924   int nCol,                           /* Number of entries in azCol[] */
139925   int iDefaultCol,                    /* Default column to query */
139926   const char *z, int n,               /* Text of MATCH query */
139927   Fts3Expr **ppExpr,                  /* OUT: Parsed query structure */
139928   char **pzErr                        /* OUT: Error message (sqlite3_malloc) */
139929 ){
139930   int rc = fts3ExprParseUnbalanced(
139931       pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
139932   );
139933   
139934   /* Rebalance the expression. And check that its depth does not exceed
139935   ** SQLITE_FTS3_MAX_EXPR_DEPTH.  */
139936   if( rc==SQLITE_OK && *ppExpr ){
139937     rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
139938     if( rc==SQLITE_OK ){
139939       rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
139940     }
139941   }
139942
139943   if( rc!=SQLITE_OK ){
139944     sqlite3Fts3ExprFree(*ppExpr);
139945     *ppExpr = 0;
139946     if( rc==SQLITE_TOOBIG ){
139947       *pzErr = sqlite3_mprintf(
139948           "FTS expression tree is too large (maximum depth %d)", 
139949           SQLITE_FTS3_MAX_EXPR_DEPTH
139950       );
139951       rc = SQLITE_ERROR;
139952     }else if( rc==SQLITE_ERROR ){
139953       *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
139954     }
139955   }
139956
139957   return rc;
139958 }
139959
139960 /*
139961 ** Free a single node of an expression tree.
139962 */
139963 static void fts3FreeExprNode(Fts3Expr *p){
139964   assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
139965   sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
139966   sqlite3_free(p->aMI);
139967   sqlite3_free(p);
139968 }
139969
139970 /*
139971 ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
139972 **
139973 ** This function would be simpler if it recursively called itself. But
139974 ** that would mean passing a sufficiently large expression to ExprParse()
139975 ** could cause a stack overflow.
139976 */
139977 SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
139978   Fts3Expr *p;
139979   assert( pDel==0 || pDel->pParent==0 );
139980   for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
139981     assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
139982   }
139983   while( p ){
139984     Fts3Expr *pParent = p->pParent;
139985     fts3FreeExprNode(p);
139986     if( pParent && p==pParent->pLeft && pParent->pRight ){
139987       p = pParent->pRight;
139988       while( p && (p->pLeft || p->pRight) ){
139989         assert( p==p->pParent->pRight || p==p->pParent->pLeft );
139990         p = (p->pLeft ? p->pLeft : p->pRight);
139991       }
139992     }else{
139993       p = pParent;
139994     }
139995   }
139996 }
139997
139998 /****************************************************************************
139999 *****************************************************************************
140000 ** Everything after this point is just test code.
140001 */
140002
140003 #ifdef SQLITE_TEST
140004
140005 /* #include <stdio.h> */
140006
140007 /*
140008 ** Function to query the hash-table of tokenizers (see README.tokenizers).
140009 */
140010 static int queryTestTokenizer(
140011   sqlite3 *db, 
140012   const char *zName,  
140013   const sqlite3_tokenizer_module **pp
140014 ){
140015   int rc;
140016   sqlite3_stmt *pStmt;
140017   const char zSql[] = "SELECT fts3_tokenizer(?)";
140018
140019   *pp = 0;
140020   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
140021   if( rc!=SQLITE_OK ){
140022     return rc;
140023   }
140024
140025   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
140026   if( SQLITE_ROW==sqlite3_step(pStmt) ){
140027     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
140028       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
140029     }
140030   }
140031
140032   return sqlite3_finalize(pStmt);
140033 }
140034
140035 /*
140036 ** Return a pointer to a buffer containing a text representation of the
140037 ** expression passed as the first argument. The buffer is obtained from
140038 ** sqlite3_malloc(). It is the responsibility of the caller to use 
140039 ** sqlite3_free() to release the memory. If an OOM condition is encountered,
140040 ** NULL is returned.
140041 **
140042 ** If the second argument is not NULL, then its contents are prepended to 
140043 ** the returned expression text and then freed using sqlite3_free().
140044 */
140045 static char *exprToString(Fts3Expr *pExpr, char *zBuf){
140046   if( pExpr==0 ){
140047     return sqlite3_mprintf("");
140048   }
140049   switch( pExpr->eType ){
140050     case FTSQUERY_PHRASE: {
140051       Fts3Phrase *pPhrase = pExpr->pPhrase;
140052       int i;
140053       zBuf = sqlite3_mprintf(
140054           "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
140055       for(i=0; zBuf && i<pPhrase->nToken; i++){
140056         zBuf = sqlite3_mprintf("%z %.*s%s", zBuf, 
140057             pPhrase->aToken[i].n, pPhrase->aToken[i].z,
140058             (pPhrase->aToken[i].isPrefix?"+":"")
140059         );
140060       }
140061       return zBuf;
140062     }
140063
140064     case FTSQUERY_NEAR:
140065       zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
140066       break;
140067     case FTSQUERY_NOT:
140068       zBuf = sqlite3_mprintf("%zNOT ", zBuf);
140069       break;
140070     case FTSQUERY_AND:
140071       zBuf = sqlite3_mprintf("%zAND ", zBuf);
140072       break;
140073     case FTSQUERY_OR:
140074       zBuf = sqlite3_mprintf("%zOR ", zBuf);
140075       break;
140076   }
140077
140078   if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
140079   if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
140080   if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
140081
140082   if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
140083   if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
140084
140085   return zBuf;
140086 }
140087
140088 /*
140089 ** This is the implementation of a scalar SQL function used to test the 
140090 ** expression parser. It should be called as follows:
140091 **
140092 **   fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
140093 **
140094 ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
140095 ** to parse the query expression (see README.tokenizers). The second argument
140096 ** is the query expression to parse. Each subsequent argument is the name
140097 ** of a column of the fts3 table that the query expression may refer to.
140098 ** For example:
140099 **
140100 **   SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
140101 */
140102 static void fts3ExprTest(
140103   sqlite3_context *context,
140104   int argc,
140105   sqlite3_value **argv
140106 ){
140107   sqlite3_tokenizer_module const *pModule = 0;
140108   sqlite3_tokenizer *pTokenizer = 0;
140109   int rc;
140110   char **azCol = 0;
140111   const char *zExpr;
140112   int nExpr;
140113   int nCol;
140114   int ii;
140115   Fts3Expr *pExpr;
140116   char *zBuf = 0;
140117   sqlite3 *db = sqlite3_context_db_handle(context);
140118
140119   if( argc<3 ){
140120     sqlite3_result_error(context, 
140121         "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
140122     );
140123     return;
140124   }
140125
140126   rc = queryTestTokenizer(db,
140127                           (const char *)sqlite3_value_text(argv[0]), &pModule);
140128   if( rc==SQLITE_NOMEM ){
140129     sqlite3_result_error_nomem(context);
140130     goto exprtest_out;
140131   }else if( !pModule ){
140132     sqlite3_result_error(context, "No such tokenizer module", -1);
140133     goto exprtest_out;
140134   }
140135
140136   rc = pModule->xCreate(0, 0, &pTokenizer);
140137   assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
140138   if( rc==SQLITE_NOMEM ){
140139     sqlite3_result_error_nomem(context);
140140     goto exprtest_out;
140141   }
140142   pTokenizer->pModule = pModule;
140143
140144   zExpr = (const char *)sqlite3_value_text(argv[1]);
140145   nExpr = sqlite3_value_bytes(argv[1]);
140146   nCol = argc-2;
140147   azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
140148   if( !azCol ){
140149     sqlite3_result_error_nomem(context);
140150     goto exprtest_out;
140151   }
140152   for(ii=0; ii<nCol; ii++){
140153     azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
140154   }
140155
140156   if( sqlite3_user_data(context) ){
140157     char *zDummy = 0;
140158     rc = sqlite3Fts3ExprParse(
140159         pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
140160     );
140161     assert( rc==SQLITE_OK || pExpr==0 );
140162     sqlite3_free(zDummy);
140163   }else{
140164     rc = fts3ExprParseUnbalanced(
140165         pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
140166     );
140167   }
140168
140169   if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
140170     sqlite3Fts3ExprFree(pExpr);
140171     sqlite3_result_error(context, "Error parsing expression", -1);
140172   }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
140173     sqlite3_result_error_nomem(context);
140174   }else{
140175     sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
140176     sqlite3_free(zBuf);
140177   }
140178
140179   sqlite3Fts3ExprFree(pExpr);
140180
140181 exprtest_out:
140182   if( pModule && pTokenizer ){
140183     rc = pModule->xDestroy(pTokenizer);
140184   }
140185   sqlite3_free(azCol);
140186 }
140187
140188 /*
140189 ** Register the query expression parser test function fts3_exprtest() 
140190 ** with database connection db. 
140191 */
140192 SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
140193   int rc = sqlite3_create_function(
140194       db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
140195   );
140196   if( rc==SQLITE_OK ){
140197     rc = sqlite3_create_function(db, "fts3_exprtest_rebalance", 
140198         -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
140199     );
140200   }
140201   return rc;
140202 }
140203
140204 #endif
140205 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
140206
140207 /************** End of fts3_expr.c *******************************************/
140208 /************** Begin file fts3_hash.c ***************************************/
140209 /*
140210 ** 2001 September 22
140211 **
140212 ** The author disclaims copyright to this source code.  In place of
140213 ** a legal notice, here is a blessing:
140214 **
140215 **    May you do good and not evil.
140216 **    May you find forgiveness for yourself and forgive others.
140217 **    May you share freely, never taking more than you give.
140218 **
140219 *************************************************************************
140220 ** This is the implementation of generic hash-tables used in SQLite.
140221 ** We've modified it slightly to serve as a standalone hash table
140222 ** implementation for the full-text indexing module.
140223 */
140224
140225 /*
140226 ** The code in this file is only compiled if:
140227 **
140228 **     * The FTS3 module is being built as an extension
140229 **       (in which case SQLITE_CORE is not defined), or
140230 **
140231 **     * The FTS3 module is being built into the core of
140232 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
140233 */
140234 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
140235
140236 /* #include <assert.h> */
140237 /* #include <stdlib.h> */
140238 /* #include <string.h> */
140239
140240
140241 /*
140242 ** Malloc and Free functions
140243 */
140244 static void *fts3HashMalloc(int n){
140245   void *p = sqlite3_malloc(n);
140246   if( p ){
140247     memset(p, 0, n);
140248   }
140249   return p;
140250 }
140251 static void fts3HashFree(void *p){
140252   sqlite3_free(p);
140253 }
140254
140255 /* Turn bulk memory into a hash table object by initializing the
140256 ** fields of the Hash structure.
140257 **
140258 ** "pNew" is a pointer to the hash table that is to be initialized.
140259 ** keyClass is one of the constants 
140260 ** FTS3_HASH_BINARY or FTS3_HASH_STRING.  The value of keyClass 
140261 ** determines what kind of key the hash table will use.  "copyKey" is
140262 ** true if the hash table should make its own private copy of keys and
140263 ** false if it should just use the supplied pointer.
140264 */
140265 SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
140266   assert( pNew!=0 );
140267   assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
140268   pNew->keyClass = keyClass;
140269   pNew->copyKey = copyKey;
140270   pNew->first = 0;
140271   pNew->count = 0;
140272   pNew->htsize = 0;
140273   pNew->ht = 0;
140274 }
140275
140276 /* Remove all entries from a hash table.  Reclaim all memory.
140277 ** Call this routine to delete a hash table or to reset a hash table
140278 ** to the empty state.
140279 */
140280 SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
140281   Fts3HashElem *elem;         /* For looping over all elements of the table */
140282
140283   assert( pH!=0 );
140284   elem = pH->first;
140285   pH->first = 0;
140286   fts3HashFree(pH->ht);
140287   pH->ht = 0;
140288   pH->htsize = 0;
140289   while( elem ){
140290     Fts3HashElem *next_elem = elem->next;
140291     if( pH->copyKey && elem->pKey ){
140292       fts3HashFree(elem->pKey);
140293     }
140294     fts3HashFree(elem);
140295     elem = next_elem;
140296   }
140297   pH->count = 0;
140298 }
140299
140300 /*
140301 ** Hash and comparison functions when the mode is FTS3_HASH_STRING
140302 */
140303 static int fts3StrHash(const void *pKey, int nKey){
140304   const char *z = (const char *)pKey;
140305   unsigned h = 0;
140306   if( nKey<=0 ) nKey = (int) strlen(z);
140307   while( nKey > 0  ){
140308     h = (h<<3) ^ h ^ *z++;
140309     nKey--;
140310   }
140311   return (int)(h & 0x7fffffff);
140312 }
140313 static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
140314   if( n1!=n2 ) return 1;
140315   return strncmp((const char*)pKey1,(const char*)pKey2,n1);
140316 }
140317
140318 /*
140319 ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
140320 */
140321 static int fts3BinHash(const void *pKey, int nKey){
140322   int h = 0;
140323   const char *z = (const char *)pKey;
140324   while( nKey-- > 0 ){
140325     h = (h<<3) ^ h ^ *(z++);
140326   }
140327   return h & 0x7fffffff;
140328 }
140329 static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
140330   if( n1!=n2 ) return 1;
140331   return memcmp(pKey1,pKey2,n1);
140332 }
140333
140334 /*
140335 ** Return a pointer to the appropriate hash function given the key class.
140336 **
140337 ** The C syntax in this function definition may be unfamilar to some 
140338 ** programmers, so we provide the following additional explanation:
140339 **
140340 ** The name of the function is "ftsHashFunction".  The function takes a
140341 ** single parameter "keyClass".  The return value of ftsHashFunction()
140342 ** is a pointer to another function.  Specifically, the return value
140343 ** of ftsHashFunction() is a pointer to a function that takes two parameters
140344 ** with types "const void*" and "int" and returns an "int".
140345 */
140346 static int (*ftsHashFunction(int keyClass))(const void*,int){
140347   if( keyClass==FTS3_HASH_STRING ){
140348     return &fts3StrHash;
140349   }else{
140350     assert( keyClass==FTS3_HASH_BINARY );
140351     return &fts3BinHash;
140352   }
140353 }
140354
140355 /*
140356 ** Return a pointer to the appropriate hash function given the key class.
140357 **
140358 ** For help in interpreted the obscure C code in the function definition,
140359 ** see the header comment on the previous function.
140360 */
140361 static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
140362   if( keyClass==FTS3_HASH_STRING ){
140363     return &fts3StrCompare;
140364   }else{
140365     assert( keyClass==FTS3_HASH_BINARY );
140366     return &fts3BinCompare;
140367   }
140368 }
140369
140370 /* Link an element into the hash table
140371 */
140372 static void fts3HashInsertElement(
140373   Fts3Hash *pH,            /* The complete hash table */
140374   struct _fts3ht *pEntry,  /* The entry into which pNew is inserted */
140375   Fts3HashElem *pNew       /* The element to be inserted */
140376 ){
140377   Fts3HashElem *pHead;     /* First element already in pEntry */
140378   pHead = pEntry->chain;
140379   if( pHead ){
140380     pNew->next = pHead;
140381     pNew->prev = pHead->prev;
140382     if( pHead->prev ){ pHead->prev->next = pNew; }
140383     else             { pH->first = pNew; }
140384     pHead->prev = pNew;
140385   }else{
140386     pNew->next = pH->first;
140387     if( pH->first ){ pH->first->prev = pNew; }
140388     pNew->prev = 0;
140389     pH->first = pNew;
140390   }
140391   pEntry->count++;
140392   pEntry->chain = pNew;
140393 }
140394
140395
140396 /* Resize the hash table so that it cantains "new_size" buckets.
140397 ** "new_size" must be a power of 2.  The hash table might fail 
140398 ** to resize if sqliteMalloc() fails.
140399 **
140400 ** Return non-zero if a memory allocation error occurs.
140401 */
140402 static int fts3Rehash(Fts3Hash *pH, int new_size){
140403   struct _fts3ht *new_ht;          /* The new hash table */
140404   Fts3HashElem *elem, *next_elem;  /* For looping over existing elements */
140405   int (*xHash)(const void*,int);   /* The hash function */
140406
140407   assert( (new_size & (new_size-1))==0 );
140408   new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
140409   if( new_ht==0 ) return 1;
140410   fts3HashFree(pH->ht);
140411   pH->ht = new_ht;
140412   pH->htsize = new_size;
140413   xHash = ftsHashFunction(pH->keyClass);
140414   for(elem=pH->first, pH->first=0; elem; elem = next_elem){
140415     int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
140416     next_elem = elem->next;
140417     fts3HashInsertElement(pH, &new_ht[h], elem);
140418   }
140419   return 0;
140420 }
140421
140422 /* This function (for internal use only) locates an element in an
140423 ** hash table that matches the given key.  The hash for this key has
140424 ** already been computed and is passed as the 4th parameter.
140425 */
140426 static Fts3HashElem *fts3FindElementByHash(
140427   const Fts3Hash *pH, /* The pH to be searched */
140428   const void *pKey,   /* The key we are searching for */
140429   int nKey,
140430   int h               /* The hash for this key. */
140431 ){
140432   Fts3HashElem *elem;            /* Used to loop thru the element list */
140433   int count;                     /* Number of elements left to test */
140434   int (*xCompare)(const void*,int,const void*,int);  /* comparison function */
140435
140436   if( pH->ht ){
140437     struct _fts3ht *pEntry = &pH->ht[h];
140438     elem = pEntry->chain;
140439     count = pEntry->count;
140440     xCompare = ftsCompareFunction(pH->keyClass);
140441     while( count-- && elem ){
140442       if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){ 
140443         return elem;
140444       }
140445       elem = elem->next;
140446     }
140447   }
140448   return 0;
140449 }
140450
140451 /* Remove a single entry from the hash table given a pointer to that
140452 ** element and a hash on the element's key.
140453 */
140454 static void fts3RemoveElementByHash(
140455   Fts3Hash *pH,         /* The pH containing "elem" */
140456   Fts3HashElem* elem,   /* The element to be removed from the pH */
140457   int h                 /* Hash value for the element */
140458 ){
140459   struct _fts3ht *pEntry;
140460   if( elem->prev ){
140461     elem->prev->next = elem->next; 
140462   }else{
140463     pH->first = elem->next;
140464   }
140465   if( elem->next ){
140466     elem->next->prev = elem->prev;
140467   }
140468   pEntry = &pH->ht[h];
140469   if( pEntry->chain==elem ){
140470     pEntry->chain = elem->next;
140471   }
140472   pEntry->count--;
140473   if( pEntry->count<=0 ){
140474     pEntry->chain = 0;
140475   }
140476   if( pH->copyKey && elem->pKey ){
140477     fts3HashFree(elem->pKey);
140478   }
140479   fts3HashFree( elem );
140480   pH->count--;
140481   if( pH->count<=0 ){
140482     assert( pH->first==0 );
140483     assert( pH->count==0 );
140484     fts3HashClear(pH);
140485   }
140486 }
140487
140488 SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
140489   const Fts3Hash *pH, 
140490   const void *pKey, 
140491   int nKey
140492 ){
140493   int h;                          /* A hash on key */
140494   int (*xHash)(const void*,int);  /* The hash function */
140495
140496   if( pH==0 || pH->ht==0 ) return 0;
140497   xHash = ftsHashFunction(pH->keyClass);
140498   assert( xHash!=0 );
140499   h = (*xHash)(pKey,nKey);
140500   assert( (pH->htsize & (pH->htsize-1))==0 );
140501   return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
140502 }
140503
140504 /* 
140505 ** Attempt to locate an element of the hash table pH with a key
140506 ** that matches pKey,nKey.  Return the data for this element if it is
140507 ** found, or NULL if there is no match.
140508 */
140509 SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
140510   Fts3HashElem *pElem;            /* The element that matches key (if any) */
140511
140512   pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
140513   return pElem ? pElem->data : 0;
140514 }
140515
140516 /* Insert an element into the hash table pH.  The key is pKey,nKey
140517 ** and the data is "data".
140518 **
140519 ** If no element exists with a matching key, then a new
140520 ** element is created.  A copy of the key is made if the copyKey
140521 ** flag is set.  NULL is returned.
140522 **
140523 ** If another element already exists with the same key, then the
140524 ** new data replaces the old data and the old data is returned.
140525 ** The key is not copied in this instance.  If a malloc fails, then
140526 ** the new data is returned and the hash table is unchanged.
140527 **
140528 ** If the "data" parameter to this function is NULL, then the
140529 ** element corresponding to "key" is removed from the hash table.
140530 */
140531 SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
140532   Fts3Hash *pH,        /* The hash table to insert into */
140533   const void *pKey,    /* The key */
140534   int nKey,            /* Number of bytes in the key */
140535   void *data           /* The data */
140536 ){
140537   int hraw;                 /* Raw hash value of the key */
140538   int h;                    /* the hash of the key modulo hash table size */
140539   Fts3HashElem *elem;       /* Used to loop thru the element list */
140540   Fts3HashElem *new_elem;   /* New element added to the pH */
140541   int (*xHash)(const void*,int);  /* The hash function */
140542
140543   assert( pH!=0 );
140544   xHash = ftsHashFunction(pH->keyClass);
140545   assert( xHash!=0 );
140546   hraw = (*xHash)(pKey, nKey);
140547   assert( (pH->htsize & (pH->htsize-1))==0 );
140548   h = hraw & (pH->htsize-1);
140549   elem = fts3FindElementByHash(pH,pKey,nKey,h);
140550   if( elem ){
140551     void *old_data = elem->data;
140552     if( data==0 ){
140553       fts3RemoveElementByHash(pH,elem,h);
140554     }else{
140555       elem->data = data;
140556     }
140557     return old_data;
140558   }
140559   if( data==0 ) return 0;
140560   if( (pH->htsize==0 && fts3Rehash(pH,8))
140561    || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
140562   ){
140563     pH->count = 0;
140564     return data;
140565   }
140566   assert( pH->htsize>0 );
140567   new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
140568   if( new_elem==0 ) return data;
140569   if( pH->copyKey && pKey!=0 ){
140570     new_elem->pKey = fts3HashMalloc( nKey );
140571     if( new_elem->pKey==0 ){
140572       fts3HashFree(new_elem);
140573       return data;
140574     }
140575     memcpy((void*)new_elem->pKey, pKey, nKey);
140576   }else{
140577     new_elem->pKey = (void*)pKey;
140578   }
140579   new_elem->nKey = nKey;
140580   pH->count++;
140581   assert( pH->htsize>0 );
140582   assert( (pH->htsize & (pH->htsize-1))==0 );
140583   h = hraw & (pH->htsize-1);
140584   fts3HashInsertElement(pH, &pH->ht[h], new_elem);
140585   new_elem->data = data;
140586   return 0;
140587 }
140588
140589 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
140590
140591 /************** End of fts3_hash.c *******************************************/
140592 /************** Begin file fts3_porter.c *************************************/
140593 /*
140594 ** 2006 September 30
140595 **
140596 ** The author disclaims copyright to this source code.  In place of
140597 ** a legal notice, here is a blessing:
140598 **
140599 **    May you do good and not evil.
140600 **    May you find forgiveness for yourself and forgive others.
140601 **    May you share freely, never taking more than you give.
140602 **
140603 *************************************************************************
140604 ** Implementation of the full-text-search tokenizer that implements
140605 ** a Porter stemmer.
140606 */
140607
140608 /*
140609 ** The code in this file is only compiled if:
140610 **
140611 **     * The FTS3 module is being built as an extension
140612 **       (in which case SQLITE_CORE is not defined), or
140613 **
140614 **     * The FTS3 module is being built into the core of
140615 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
140616 */
140617 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
140618
140619 /* #include <assert.h> */
140620 /* #include <stdlib.h> */
140621 /* #include <stdio.h> */
140622 /* #include <string.h> */
140623
140624
140625 /*
140626 ** Class derived from sqlite3_tokenizer
140627 */
140628 typedef struct porter_tokenizer {
140629   sqlite3_tokenizer base;      /* Base class */
140630 } porter_tokenizer;
140631
140632 /*
140633 ** Class derived from sqlite3_tokenizer_cursor
140634 */
140635 typedef struct porter_tokenizer_cursor {
140636   sqlite3_tokenizer_cursor base;
140637   const char *zInput;          /* input we are tokenizing */
140638   int nInput;                  /* size of the input */
140639   int iOffset;                 /* current position in zInput */
140640   int iToken;                  /* index of next token to be returned */
140641   char *zToken;                /* storage for current token */
140642   int nAllocated;              /* space allocated to zToken buffer */
140643 } porter_tokenizer_cursor;
140644
140645
140646 /*
140647 ** Create a new tokenizer instance.
140648 */
140649 static int porterCreate(
140650   int argc, const char * const *argv,
140651   sqlite3_tokenizer **ppTokenizer
140652 ){
140653   porter_tokenizer *t;
140654
140655   UNUSED_PARAMETER(argc);
140656   UNUSED_PARAMETER(argv);
140657
140658   t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
140659   if( t==NULL ) return SQLITE_NOMEM;
140660   memset(t, 0, sizeof(*t));
140661   *ppTokenizer = &t->base;
140662   return SQLITE_OK;
140663 }
140664
140665 /*
140666 ** Destroy a tokenizer
140667 */
140668 static int porterDestroy(sqlite3_tokenizer *pTokenizer){
140669   sqlite3_free(pTokenizer);
140670   return SQLITE_OK;
140671 }
140672
140673 /*
140674 ** Prepare to begin tokenizing a particular string.  The input
140675 ** string to be tokenized is zInput[0..nInput-1].  A cursor
140676 ** used to incrementally tokenize this string is returned in 
140677 ** *ppCursor.
140678 */
140679 static int porterOpen(
140680   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
140681   const char *zInput, int nInput,        /* String to be tokenized */
140682   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
140683 ){
140684   porter_tokenizer_cursor *c;
140685
140686   UNUSED_PARAMETER(pTokenizer);
140687
140688   c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
140689   if( c==NULL ) return SQLITE_NOMEM;
140690
140691   c->zInput = zInput;
140692   if( zInput==0 ){
140693     c->nInput = 0;
140694   }else if( nInput<0 ){
140695     c->nInput = (int)strlen(zInput);
140696   }else{
140697     c->nInput = nInput;
140698   }
140699   c->iOffset = 0;                 /* start tokenizing at the beginning */
140700   c->iToken = 0;
140701   c->zToken = NULL;               /* no space allocated, yet. */
140702   c->nAllocated = 0;
140703
140704   *ppCursor = &c->base;
140705   return SQLITE_OK;
140706 }
140707
140708 /*
140709 ** Close a tokenization cursor previously opened by a call to
140710 ** porterOpen() above.
140711 */
140712 static int porterClose(sqlite3_tokenizer_cursor *pCursor){
140713   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
140714   sqlite3_free(c->zToken);
140715   sqlite3_free(c);
140716   return SQLITE_OK;
140717 }
140718 /*
140719 ** Vowel or consonant
140720 */
140721 static const char cType[] = {
140722    0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
140723    1, 1, 1, 2, 1
140724 };
140725
140726 /*
140727 ** isConsonant() and isVowel() determine if their first character in
140728 ** the string they point to is a consonant or a vowel, according
140729 ** to Porter ruls.  
140730 **
140731 ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
140732 ** 'Y' is a consonant unless it follows another consonant,
140733 ** in which case it is a vowel.
140734 **
140735 ** In these routine, the letters are in reverse order.  So the 'y' rule
140736 ** is that 'y' is a consonant unless it is followed by another
140737 ** consonent.
140738 */
140739 static int isVowel(const char*);
140740 static int isConsonant(const char *z){
140741   int j;
140742   char x = *z;
140743   if( x==0 ) return 0;
140744   assert( x>='a' && x<='z' );
140745   j = cType[x-'a'];
140746   if( j<2 ) return j;
140747   return z[1]==0 || isVowel(z + 1);
140748 }
140749 static int isVowel(const char *z){
140750   int j;
140751   char x = *z;
140752   if( x==0 ) return 0;
140753   assert( x>='a' && x<='z' );
140754   j = cType[x-'a'];
140755   if( j<2 ) return 1-j;
140756   return isConsonant(z + 1);
140757 }
140758
140759 /*
140760 ** Let any sequence of one or more vowels be represented by V and let
140761 ** C be sequence of one or more consonants.  Then every word can be
140762 ** represented as:
140763 **
140764 **           [C] (VC){m} [V]
140765 **
140766 ** In prose:  A word is an optional consonant followed by zero or
140767 ** vowel-consonant pairs followed by an optional vowel.  "m" is the
140768 ** number of vowel consonant pairs.  This routine computes the value
140769 ** of m for the first i bytes of a word.
140770 **
140771 ** Return true if the m-value for z is 1 or more.  In other words,
140772 ** return true if z contains at least one vowel that is followed
140773 ** by a consonant.
140774 **
140775 ** In this routine z[] is in reverse order.  So we are really looking
140776 ** for an instance of a consonant followed by a vowel.
140777 */
140778 static int m_gt_0(const char *z){
140779   while( isVowel(z) ){ z++; }
140780   if( *z==0 ) return 0;
140781   while( isConsonant(z) ){ z++; }
140782   return *z!=0;
140783 }
140784
140785 /* Like mgt0 above except we are looking for a value of m which is
140786 ** exactly 1
140787 */
140788 static int m_eq_1(const char *z){
140789   while( isVowel(z) ){ z++; }
140790   if( *z==0 ) return 0;
140791   while( isConsonant(z) ){ z++; }
140792   if( *z==0 ) return 0;
140793   while( isVowel(z) ){ z++; }
140794   if( *z==0 ) return 1;
140795   while( isConsonant(z) ){ z++; }
140796   return *z==0;
140797 }
140798
140799 /* Like mgt0 above except we are looking for a value of m>1 instead
140800 ** or m>0
140801 */
140802 static int m_gt_1(const char *z){
140803   while( isVowel(z) ){ z++; }
140804   if( *z==0 ) return 0;
140805   while( isConsonant(z) ){ z++; }
140806   if( *z==0 ) return 0;
140807   while( isVowel(z) ){ z++; }
140808   if( *z==0 ) return 0;
140809   while( isConsonant(z) ){ z++; }
140810   return *z!=0;
140811 }
140812
140813 /*
140814 ** Return TRUE if there is a vowel anywhere within z[0..n-1]
140815 */
140816 static int hasVowel(const char *z){
140817   while( isConsonant(z) ){ z++; }
140818   return *z!=0;
140819 }
140820
140821 /*
140822 ** Return TRUE if the word ends in a double consonant.
140823 **
140824 ** The text is reversed here. So we are really looking at
140825 ** the first two characters of z[].
140826 */
140827 static int doubleConsonant(const char *z){
140828   return isConsonant(z) && z[0]==z[1];
140829 }
140830
140831 /*
140832 ** Return TRUE if the word ends with three letters which
140833 ** are consonant-vowel-consonent and where the final consonant
140834 ** is not 'w', 'x', or 'y'.
140835 **
140836 ** The word is reversed here.  So we are really checking the
140837 ** first three letters and the first one cannot be in [wxy].
140838 */
140839 static int star_oh(const char *z){
140840   return
140841     isConsonant(z) &&
140842     z[0]!='w' && z[0]!='x' && z[0]!='y' &&
140843     isVowel(z+1) &&
140844     isConsonant(z+2);
140845 }
140846
140847 /*
140848 ** If the word ends with zFrom and xCond() is true for the stem
140849 ** of the word that preceeds the zFrom ending, then change the 
140850 ** ending to zTo.
140851 **
140852 ** The input word *pz and zFrom are both in reverse order.  zTo
140853 ** is in normal order. 
140854 **
140855 ** Return TRUE if zFrom matches.  Return FALSE if zFrom does not
140856 ** match.  Not that TRUE is returned even if xCond() fails and
140857 ** no substitution occurs.
140858 */
140859 static int stem(
140860   char **pz,             /* The word being stemmed (Reversed) */
140861   const char *zFrom,     /* If the ending matches this... (Reversed) */
140862   const char *zTo,       /* ... change the ending to this (not reversed) */
140863   int (*xCond)(const char*)   /* Condition that must be true */
140864 ){
140865   char *z = *pz;
140866   while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
140867   if( *zFrom!=0 ) return 0;
140868   if( xCond && !xCond(z) ) return 1;
140869   while( *zTo ){
140870     *(--z) = *(zTo++);
140871   }
140872   *pz = z;
140873   return 1;
140874 }
140875
140876 /*
140877 ** This is the fallback stemmer used when the porter stemmer is
140878 ** inappropriate.  The input word is copied into the output with
140879 ** US-ASCII case folding.  If the input word is too long (more
140880 ** than 20 bytes if it contains no digits or more than 6 bytes if
140881 ** it contains digits) then word is truncated to 20 or 6 bytes
140882 ** by taking 10 or 3 bytes from the beginning and end.
140883 */
140884 static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
140885   int i, mx, j;
140886   int hasDigit = 0;
140887   for(i=0; i<nIn; i++){
140888     char c = zIn[i];
140889     if( c>='A' && c<='Z' ){
140890       zOut[i] = c - 'A' + 'a';
140891     }else{
140892       if( c>='0' && c<='9' ) hasDigit = 1;
140893       zOut[i] = c;
140894     }
140895   }
140896   mx = hasDigit ? 3 : 10;
140897   if( nIn>mx*2 ){
140898     for(j=mx, i=nIn-mx; i<nIn; i++, j++){
140899       zOut[j] = zOut[i];
140900     }
140901     i = j;
140902   }
140903   zOut[i] = 0;
140904   *pnOut = i;
140905 }
140906
140907
140908 /*
140909 ** Stem the input word zIn[0..nIn-1].  Store the output in zOut.
140910 ** zOut is at least big enough to hold nIn bytes.  Write the actual
140911 ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
140912 **
140913 ** Any upper-case characters in the US-ASCII character set ([A-Z])
140914 ** are converted to lower case.  Upper-case UTF characters are
140915 ** unchanged.
140916 **
140917 ** Words that are longer than about 20 bytes are stemmed by retaining
140918 ** a few bytes from the beginning and the end of the word.  If the
140919 ** word contains digits, 3 bytes are taken from the beginning and
140920 ** 3 bytes from the end.  For long words without digits, 10 bytes
140921 ** are taken from each end.  US-ASCII case folding still applies.
140922 ** 
140923 ** If the input word contains not digits but does characters not 
140924 ** in [a-zA-Z] then no stemming is attempted and this routine just 
140925 ** copies the input into the input into the output with US-ASCII
140926 ** case folding.
140927 **
140928 ** Stemming never increases the length of the word.  So there is
140929 ** no chance of overflowing the zOut buffer.
140930 */
140931 static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
140932   int i, j;
140933   char zReverse[28];
140934   char *z, *z2;
140935   if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
140936     /* The word is too big or too small for the porter stemmer.
140937     ** Fallback to the copy stemmer */
140938     copy_stemmer(zIn, nIn, zOut, pnOut);
140939     return;
140940   }
140941   for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
140942     char c = zIn[i];
140943     if( c>='A' && c<='Z' ){
140944       zReverse[j] = c + 'a' - 'A';
140945     }else if( c>='a' && c<='z' ){
140946       zReverse[j] = c;
140947     }else{
140948       /* The use of a character not in [a-zA-Z] means that we fallback
140949       ** to the copy stemmer */
140950       copy_stemmer(zIn, nIn, zOut, pnOut);
140951       return;
140952     }
140953   }
140954   memset(&zReverse[sizeof(zReverse)-5], 0, 5);
140955   z = &zReverse[j+1];
140956
140957
140958   /* Step 1a */
140959   if( z[0]=='s' ){
140960     if(
140961      !stem(&z, "sess", "ss", 0) &&
140962      !stem(&z, "sei", "i", 0)  &&
140963      !stem(&z, "ss", "ss", 0)
140964     ){
140965       z++;
140966     }
140967   }
140968
140969   /* Step 1b */  
140970   z2 = z;
140971   if( stem(&z, "dee", "ee", m_gt_0) ){
140972     /* Do nothing.  The work was all in the test */
140973   }else if( 
140974      (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
140975       && z!=z2
140976   ){
140977      if( stem(&z, "ta", "ate", 0) ||
140978          stem(&z, "lb", "ble", 0) ||
140979          stem(&z, "zi", "ize", 0) ){
140980        /* Do nothing.  The work was all in the test */
140981      }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
140982        z++;
140983      }else if( m_eq_1(z) && star_oh(z) ){
140984        *(--z) = 'e';
140985      }
140986   }
140987
140988   /* Step 1c */
140989   if( z[0]=='y' && hasVowel(z+1) ){
140990     z[0] = 'i';
140991   }
140992
140993   /* Step 2 */
140994   switch( z[1] ){
140995    case 'a':
140996      if( !stem(&z, "lanoita", "ate", m_gt_0) ){
140997        stem(&z, "lanoit", "tion", m_gt_0);
140998      }
140999      break;
141000    case 'c':
141001      if( !stem(&z, "icne", "ence", m_gt_0) ){
141002        stem(&z, "icna", "ance", m_gt_0);
141003      }
141004      break;
141005    case 'e':
141006      stem(&z, "rezi", "ize", m_gt_0);
141007      break;
141008    case 'g':
141009      stem(&z, "igol", "log", m_gt_0);
141010      break;
141011    case 'l':
141012      if( !stem(&z, "ilb", "ble", m_gt_0) 
141013       && !stem(&z, "illa", "al", m_gt_0)
141014       && !stem(&z, "iltne", "ent", m_gt_0)
141015       && !stem(&z, "ile", "e", m_gt_0)
141016      ){
141017        stem(&z, "ilsuo", "ous", m_gt_0);
141018      }
141019      break;
141020    case 'o':
141021      if( !stem(&z, "noitazi", "ize", m_gt_0)
141022       && !stem(&z, "noita", "ate", m_gt_0)
141023      ){
141024        stem(&z, "rota", "ate", m_gt_0);
141025      }
141026      break;
141027    case 's':
141028      if( !stem(&z, "msila", "al", m_gt_0)
141029       && !stem(&z, "ssenevi", "ive", m_gt_0)
141030       && !stem(&z, "ssenluf", "ful", m_gt_0)
141031      ){
141032        stem(&z, "ssensuo", "ous", m_gt_0);
141033      }
141034      break;
141035    case 't':
141036      if( !stem(&z, "itila", "al", m_gt_0)
141037       && !stem(&z, "itivi", "ive", m_gt_0)
141038      ){
141039        stem(&z, "itilib", "ble", m_gt_0);
141040      }
141041      break;
141042   }
141043
141044   /* Step 3 */
141045   switch( z[0] ){
141046    case 'e':
141047      if( !stem(&z, "etaci", "ic", m_gt_0)
141048       && !stem(&z, "evita", "", m_gt_0)
141049      ){
141050        stem(&z, "ezila", "al", m_gt_0);
141051      }
141052      break;
141053    case 'i':
141054      stem(&z, "itici", "ic", m_gt_0);
141055      break;
141056    case 'l':
141057      if( !stem(&z, "laci", "ic", m_gt_0) ){
141058        stem(&z, "luf", "", m_gt_0);
141059      }
141060      break;
141061    case 's':
141062      stem(&z, "ssen", "", m_gt_0);
141063      break;
141064   }
141065
141066   /* Step 4 */
141067   switch( z[1] ){
141068    case 'a':
141069      if( z[0]=='l' && m_gt_1(z+2) ){
141070        z += 2;
141071      }
141072      break;
141073    case 'c':
141074      if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e')  && m_gt_1(z+4)  ){
141075        z += 4;
141076      }
141077      break;
141078    case 'e':
141079      if( z[0]=='r' && m_gt_1(z+2) ){
141080        z += 2;
141081      }
141082      break;
141083    case 'i':
141084      if( z[0]=='c' && m_gt_1(z+2) ){
141085        z += 2;
141086      }
141087      break;
141088    case 'l':
141089      if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
141090        z += 4;
141091      }
141092      break;
141093    case 'n':
141094      if( z[0]=='t' ){
141095        if( z[2]=='a' ){
141096          if( m_gt_1(z+3) ){
141097            z += 3;
141098          }
141099        }else if( z[2]=='e' ){
141100          if( !stem(&z, "tneme", "", m_gt_1)
141101           && !stem(&z, "tnem", "", m_gt_1)
141102          ){
141103            stem(&z, "tne", "", m_gt_1);
141104          }
141105        }
141106      }
141107      break;
141108    case 'o':
141109      if( z[0]=='u' ){
141110        if( m_gt_1(z+2) ){
141111          z += 2;
141112        }
141113      }else if( z[3]=='s' || z[3]=='t' ){
141114        stem(&z, "noi", "", m_gt_1);
141115      }
141116      break;
141117    case 's':
141118      if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
141119        z += 3;
141120      }
141121      break;
141122    case 't':
141123      if( !stem(&z, "eta", "", m_gt_1) ){
141124        stem(&z, "iti", "", m_gt_1);
141125      }
141126      break;
141127    case 'u':
141128      if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
141129        z += 3;
141130      }
141131      break;
141132    case 'v':
141133    case 'z':
141134      if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
141135        z += 3;
141136      }
141137      break;
141138   }
141139
141140   /* Step 5a */
141141   if( z[0]=='e' ){
141142     if( m_gt_1(z+1) ){
141143       z++;
141144     }else if( m_eq_1(z+1) && !star_oh(z+1) ){
141145       z++;
141146     }
141147   }
141148
141149   /* Step 5b */
141150   if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
141151     z++;
141152   }
141153
141154   /* z[] is now the stemmed word in reverse order.  Flip it back
141155   ** around into forward order and return.
141156   */
141157   *pnOut = i = (int)strlen(z);
141158   zOut[i] = 0;
141159   while( *z ){
141160     zOut[--i] = *(z++);
141161   }
141162 }
141163
141164 /*
141165 ** Characters that can be part of a token.  We assume any character
141166 ** whose value is greater than 0x80 (any UTF character) can be
141167 ** part of a token.  In other words, delimiters all must have
141168 ** values of 0x7f or lower.
141169 */
141170 static const char porterIdChar[] = {
141171 /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
141172     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
141173     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
141174     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
141175     0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
141176     1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
141177 };
141178 #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
141179
141180 /*
141181 ** Extract the next token from a tokenization cursor.  The cursor must
141182 ** have been opened by a prior call to porterOpen().
141183 */
141184 static int porterNext(
141185   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by porterOpen */
141186   const char **pzToken,               /* OUT: *pzToken is the token text */
141187   int *pnBytes,                       /* OUT: Number of bytes in token */
141188   int *piStartOffset,                 /* OUT: Starting offset of token */
141189   int *piEndOffset,                   /* OUT: Ending offset of token */
141190   int *piPosition                     /* OUT: Position integer of token */
141191 ){
141192   porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
141193   const char *z = c->zInput;
141194
141195   while( c->iOffset<c->nInput ){
141196     int iStartOffset, ch;
141197
141198     /* Scan past delimiter characters */
141199     while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
141200       c->iOffset++;
141201     }
141202
141203     /* Count non-delimiter characters. */
141204     iStartOffset = c->iOffset;
141205     while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
141206       c->iOffset++;
141207     }
141208
141209     if( c->iOffset>iStartOffset ){
141210       int n = c->iOffset-iStartOffset;
141211       if( n>c->nAllocated ){
141212         char *pNew;
141213         c->nAllocated = n+20;
141214         pNew = sqlite3_realloc(c->zToken, c->nAllocated);
141215         if( !pNew ) return SQLITE_NOMEM;
141216         c->zToken = pNew;
141217       }
141218       porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
141219       *pzToken = c->zToken;
141220       *piStartOffset = iStartOffset;
141221       *piEndOffset = c->iOffset;
141222       *piPosition = c->iToken++;
141223       return SQLITE_OK;
141224     }
141225   }
141226   return SQLITE_DONE;
141227 }
141228
141229 /*
141230 ** The set of routines that implement the porter-stemmer tokenizer
141231 */
141232 static const sqlite3_tokenizer_module porterTokenizerModule = {
141233   0,
141234   porterCreate,
141235   porterDestroy,
141236   porterOpen,
141237   porterClose,
141238   porterNext,
141239   0
141240 };
141241
141242 /*
141243 ** Allocate a new porter tokenizer.  Return a pointer to the new
141244 ** tokenizer in *ppModule
141245 */
141246 SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
141247   sqlite3_tokenizer_module const**ppModule
141248 ){
141249   *ppModule = &porterTokenizerModule;
141250 }
141251
141252 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
141253
141254 /************** End of fts3_porter.c *****************************************/
141255 /************** Begin file fts3_tokenizer.c **********************************/
141256 /*
141257 ** 2007 June 22
141258 **
141259 ** The author disclaims copyright to this source code.  In place of
141260 ** a legal notice, here is a blessing:
141261 **
141262 **    May you do good and not evil.
141263 **    May you find forgiveness for yourself and forgive others.
141264 **    May you share freely, never taking more than you give.
141265 **
141266 ******************************************************************************
141267 **
141268 ** This is part of an SQLite module implementing full-text search.
141269 ** This particular file implements the generic tokenizer interface.
141270 */
141271
141272 /*
141273 ** The code in this file is only compiled if:
141274 **
141275 **     * The FTS3 module is being built as an extension
141276 **       (in which case SQLITE_CORE is not defined), or
141277 **
141278 **     * The FTS3 module is being built into the core of
141279 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
141280 */
141281 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
141282
141283 /* #include <assert.h> */
141284 /* #include <string.h> */
141285
141286 /*
141287 ** Implementation of the SQL scalar function for accessing the underlying 
141288 ** hash table. This function may be called as follows:
141289 **
141290 **   SELECT <function-name>(<key-name>);
141291 **   SELECT <function-name>(<key-name>, <pointer>);
141292 **
141293 ** where <function-name> is the name passed as the second argument
141294 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
141295 **
141296 ** If the <pointer> argument is specified, it must be a blob value
141297 ** containing a pointer to be stored as the hash data corresponding
141298 ** to the string <key-name>. If <pointer> is not specified, then
141299 ** the string <key-name> must already exist in the has table. Otherwise,
141300 ** an error is returned.
141301 **
141302 ** Whether or not the <pointer> argument is specified, the value returned
141303 ** is a blob containing the pointer stored as the hash data corresponding
141304 ** to string <key-name> (after the hash-table is updated, if applicable).
141305 */
141306 static void scalarFunc(
141307   sqlite3_context *context,
141308   int argc,
141309   sqlite3_value **argv
141310 ){
141311   Fts3Hash *pHash;
141312   void *pPtr = 0;
141313   const unsigned char *zName;
141314   int nName;
141315
141316   assert( argc==1 || argc==2 );
141317
141318   pHash = (Fts3Hash *)sqlite3_user_data(context);
141319
141320   zName = sqlite3_value_text(argv[0]);
141321   nName = sqlite3_value_bytes(argv[0])+1;
141322
141323   if( argc==2 ){
141324     void *pOld;
141325     int n = sqlite3_value_bytes(argv[1]);
141326     if( zName==0 || n!=sizeof(pPtr) ){
141327       sqlite3_result_error(context, "argument type mismatch", -1);
141328       return;
141329     }
141330     pPtr = *(void **)sqlite3_value_blob(argv[1]);
141331     pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
141332     if( pOld==pPtr ){
141333       sqlite3_result_error(context, "out of memory", -1);
141334       return;
141335     }
141336   }else{
141337     if( zName ){
141338       pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
141339     }
141340     if( !pPtr ){
141341       char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
141342       sqlite3_result_error(context, zErr, -1);
141343       sqlite3_free(zErr);
141344       return;
141345     }
141346   }
141347
141348   sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
141349 }
141350
141351 SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
141352   static const char isFtsIdChar[] = {
141353       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 0x */
141354       0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 1x */
141355       0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,  /* 2x */
141356       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,  /* 3x */
141357       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 4x */
141358       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1,  /* 5x */
141359       0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,  /* 6x */
141360       1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,  /* 7x */
141361   };
141362   return (c&0x80 || isFtsIdChar[(int)(c)]);
141363 }
141364
141365 SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
141366   const char *z1;
141367   const char *z2 = 0;
141368
141369   /* Find the start of the next token. */
141370   z1 = zStr;
141371   while( z2==0 ){
141372     char c = *z1;
141373     switch( c ){
141374       case '\0': return 0;        /* No more tokens here */
141375       case '\'':
141376       case '"':
141377       case '`': {
141378         z2 = z1;
141379         while( *++z2 && (*z2!=c || *++z2==c) );
141380         break;
141381       }
141382       case '[':
141383         z2 = &z1[1];
141384         while( *z2 && z2[0]!=']' ) z2++;
141385         if( *z2 ) z2++;
141386         break;
141387
141388       default:
141389         if( sqlite3Fts3IsIdChar(*z1) ){
141390           z2 = &z1[1];
141391           while( sqlite3Fts3IsIdChar(*z2) ) z2++;
141392         }else{
141393           z1++;
141394         }
141395     }
141396   }
141397
141398   *pn = (int)(z2-z1);
141399   return z1;
141400 }
141401
141402 SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
141403   Fts3Hash *pHash,                /* Tokenizer hash table */
141404   const char *zArg,               /* Tokenizer name */
141405   sqlite3_tokenizer **ppTok,      /* OUT: Tokenizer (if applicable) */
141406   char **pzErr                    /* OUT: Set to malloced error message */
141407 ){
141408   int rc;
141409   char *z = (char *)zArg;
141410   int n = 0;
141411   char *zCopy;
141412   char *zEnd;                     /* Pointer to nul-term of zCopy */
141413   sqlite3_tokenizer_module *m;
141414
141415   zCopy = sqlite3_mprintf("%s", zArg);
141416   if( !zCopy ) return SQLITE_NOMEM;
141417   zEnd = &zCopy[strlen(zCopy)];
141418
141419   z = (char *)sqlite3Fts3NextToken(zCopy, &n);
141420   if( z==0 ){
141421     assert( n==0 );
141422     z = zCopy;
141423   }
141424   z[n] = '\0';
141425   sqlite3Fts3Dequote(z);
141426
141427   m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
141428   if( !m ){
141429     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
141430     rc = SQLITE_ERROR;
141431   }else{
141432     char const **aArg = 0;
141433     int iArg = 0;
141434     z = &z[n+1];
141435     while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
141436       int nNew = sizeof(char *)*(iArg+1);
141437       char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
141438       if( !aNew ){
141439         sqlite3_free(zCopy);
141440         sqlite3_free((void *)aArg);
141441         return SQLITE_NOMEM;
141442       }
141443       aArg = aNew;
141444       aArg[iArg++] = z;
141445       z[n] = '\0';
141446       sqlite3Fts3Dequote(z);
141447       z = &z[n+1];
141448     }
141449     rc = m->xCreate(iArg, aArg, ppTok);
141450     assert( rc!=SQLITE_OK || *ppTok );
141451     if( rc!=SQLITE_OK ){
141452       *pzErr = sqlite3_mprintf("unknown tokenizer");
141453     }else{
141454       (*ppTok)->pModule = m; 
141455     }
141456     sqlite3_free((void *)aArg);
141457   }
141458
141459   sqlite3_free(zCopy);
141460   return rc;
141461 }
141462
141463
141464 #ifdef SQLITE_TEST
141465
141466 #include <tcl.h>
141467 /* #include <string.h> */
141468
141469 /*
141470 ** Implementation of a special SQL scalar function for testing tokenizers 
141471 ** designed to be used in concert with the Tcl testing framework. This
141472 ** function must be called with two or more arguments:
141473 **
141474 **   SELECT <function-name>(<key-name>, ..., <input-string>);
141475 **
141476 ** where <function-name> is the name passed as the second argument
141477 ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
141478 ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
141479 **
141480 ** The return value is a string that may be interpreted as a Tcl
141481 ** list. For each token in the <input-string>, three elements are
141482 ** added to the returned list. The first is the token position, the 
141483 ** second is the token text (folded, stemmed, etc.) and the third is the
141484 ** substring of <input-string> associated with the token. For example, 
141485 ** using the built-in "simple" tokenizer:
141486 **
141487 **   SELECT fts_tokenizer_test('simple', 'I don't see how');
141488 **
141489 ** will return the string:
141490 **
141491 **   "{0 i I 1 dont don't 2 see see 3 how how}"
141492 **   
141493 */
141494 static void testFunc(
141495   sqlite3_context *context,
141496   int argc,
141497   sqlite3_value **argv
141498 ){
141499   Fts3Hash *pHash;
141500   sqlite3_tokenizer_module *p;
141501   sqlite3_tokenizer *pTokenizer = 0;
141502   sqlite3_tokenizer_cursor *pCsr = 0;
141503
141504   const char *zErr = 0;
141505
141506   const char *zName;
141507   int nName;
141508   const char *zInput;
141509   int nInput;
141510
141511   const char *azArg[64];
141512
141513   const char *zToken;
141514   int nToken = 0;
141515   int iStart = 0;
141516   int iEnd = 0;
141517   int iPos = 0;
141518   int i;
141519
141520   Tcl_Obj *pRet;
141521
141522   if( argc<2 ){
141523     sqlite3_result_error(context, "insufficient arguments", -1);
141524     return;
141525   }
141526
141527   nName = sqlite3_value_bytes(argv[0]);
141528   zName = (const char *)sqlite3_value_text(argv[0]);
141529   nInput = sqlite3_value_bytes(argv[argc-1]);
141530   zInput = (const char *)sqlite3_value_text(argv[argc-1]);
141531
141532   pHash = (Fts3Hash *)sqlite3_user_data(context);
141533   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
141534
141535   if( !p ){
141536     char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
141537     sqlite3_result_error(context, zErr, -1);
141538     sqlite3_free(zErr);
141539     return;
141540   }
141541
141542   pRet = Tcl_NewObj();
141543   Tcl_IncrRefCount(pRet);
141544
141545   for(i=1; i<argc-1; i++){
141546     azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
141547   }
141548
141549   if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
141550     zErr = "error in xCreate()";
141551     goto finish;
141552   }
141553   pTokenizer->pModule = p;
141554   if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
141555     zErr = "error in xOpen()";
141556     goto finish;
141557   }
141558
141559   while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
141560     Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
141561     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
141562     zToken = &zInput[iStart];
141563     nToken = iEnd-iStart;
141564     Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
141565   }
141566
141567   if( SQLITE_OK!=p->xClose(pCsr) ){
141568     zErr = "error in xClose()";
141569     goto finish;
141570   }
141571   if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
141572     zErr = "error in xDestroy()";
141573     goto finish;
141574   }
141575
141576 finish:
141577   if( zErr ){
141578     sqlite3_result_error(context, zErr, -1);
141579   }else{
141580     sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
141581   }
141582   Tcl_DecrRefCount(pRet);
141583 }
141584
141585 static
141586 int registerTokenizer(
141587   sqlite3 *db, 
141588   char *zName, 
141589   const sqlite3_tokenizer_module *p
141590 ){
141591   int rc;
141592   sqlite3_stmt *pStmt;
141593   const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
141594
141595   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
141596   if( rc!=SQLITE_OK ){
141597     return rc;
141598   }
141599
141600   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
141601   sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
141602   sqlite3_step(pStmt);
141603
141604   return sqlite3_finalize(pStmt);
141605 }
141606
141607 static
141608 int queryTokenizer(
141609   sqlite3 *db, 
141610   char *zName,  
141611   const sqlite3_tokenizer_module **pp
141612 ){
141613   int rc;
141614   sqlite3_stmt *pStmt;
141615   const char zSql[] = "SELECT fts3_tokenizer(?)";
141616
141617   *pp = 0;
141618   rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
141619   if( rc!=SQLITE_OK ){
141620     return rc;
141621   }
141622
141623   sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
141624   if( SQLITE_ROW==sqlite3_step(pStmt) ){
141625     if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
141626       memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
141627     }
141628   }
141629
141630   return sqlite3_finalize(pStmt);
141631 }
141632
141633 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
141634
141635 /*
141636 ** Implementation of the scalar function fts3_tokenizer_internal_test().
141637 ** This function is used for testing only, it is not included in the
141638 ** build unless SQLITE_TEST is defined.
141639 **
141640 ** The purpose of this is to test that the fts3_tokenizer() function
141641 ** can be used as designed by the C-code in the queryTokenizer and
141642 ** registerTokenizer() functions above. These two functions are repeated
141643 ** in the README.tokenizer file as an example, so it is important to
141644 ** test them.
141645 **
141646 ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
141647 ** function with no arguments. An assert() will fail if a problem is
141648 ** detected. i.e.:
141649 **
141650 **     SELECT fts3_tokenizer_internal_test();
141651 **
141652 */
141653 static void intTestFunc(
141654   sqlite3_context *context,
141655   int argc,
141656   sqlite3_value **argv
141657 ){
141658   int rc;
141659   const sqlite3_tokenizer_module *p1;
141660   const sqlite3_tokenizer_module *p2;
141661   sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
141662
141663   UNUSED_PARAMETER(argc);
141664   UNUSED_PARAMETER(argv);
141665
141666   /* Test the query function */
141667   sqlite3Fts3SimpleTokenizerModule(&p1);
141668   rc = queryTokenizer(db, "simple", &p2);
141669   assert( rc==SQLITE_OK );
141670   assert( p1==p2 );
141671   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
141672   assert( rc==SQLITE_ERROR );
141673   assert( p2==0 );
141674   assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
141675
141676   /* Test the storage function */
141677   rc = registerTokenizer(db, "nosuchtokenizer", p1);
141678   assert( rc==SQLITE_OK );
141679   rc = queryTokenizer(db, "nosuchtokenizer", &p2);
141680   assert( rc==SQLITE_OK );
141681   assert( p2==p1 );
141682
141683   sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
141684 }
141685
141686 #endif
141687
141688 /*
141689 ** Set up SQL objects in database db used to access the contents of
141690 ** the hash table pointed to by argument pHash. The hash table must
141691 ** been initialized to use string keys, and to take a private copy 
141692 ** of the key when a value is inserted. i.e. by a call similar to:
141693 **
141694 **    sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
141695 **
141696 ** This function adds a scalar function (see header comment above
141697 ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
141698 ** defined at compilation time, a temporary virtual table (see header 
141699 ** comment above struct HashTableVtab) to the database schema. Both 
141700 ** provide read/write access to the contents of *pHash.
141701 **
141702 ** The third argument to this function, zName, is used as the name
141703 ** of both the scalar and, if created, the virtual table.
141704 */
141705 SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
141706   sqlite3 *db, 
141707   Fts3Hash *pHash, 
141708   const char *zName
141709 ){
141710   int rc = SQLITE_OK;
141711   void *p = (void *)pHash;
141712   const int any = SQLITE_ANY;
141713
141714 #ifdef SQLITE_TEST
141715   char *zTest = 0;
141716   char *zTest2 = 0;
141717   void *pdb = (void *)db;
141718   zTest = sqlite3_mprintf("%s_test", zName);
141719   zTest2 = sqlite3_mprintf("%s_internal_test", zName);
141720   if( !zTest || !zTest2 ){
141721     rc = SQLITE_NOMEM;
141722   }
141723 #endif
141724
141725   if( SQLITE_OK==rc ){
141726     rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
141727   }
141728   if( SQLITE_OK==rc ){
141729     rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
141730   }
141731 #ifdef SQLITE_TEST
141732   if( SQLITE_OK==rc ){
141733     rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
141734   }
141735   if( SQLITE_OK==rc ){
141736     rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
141737   }
141738 #endif
141739
141740 #ifdef SQLITE_TEST
141741   sqlite3_free(zTest);
141742   sqlite3_free(zTest2);
141743 #endif
141744
141745   return rc;
141746 }
141747
141748 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
141749
141750 /************** End of fts3_tokenizer.c **************************************/
141751 /************** Begin file fts3_tokenizer1.c *********************************/
141752 /*
141753 ** 2006 Oct 10
141754 **
141755 ** The author disclaims copyright to this source code.  In place of
141756 ** a legal notice, here is a blessing:
141757 **
141758 **    May you do good and not evil.
141759 **    May you find forgiveness for yourself and forgive others.
141760 **    May you share freely, never taking more than you give.
141761 **
141762 ******************************************************************************
141763 **
141764 ** Implementation of the "simple" full-text-search tokenizer.
141765 */
141766
141767 /*
141768 ** The code in this file is only compiled if:
141769 **
141770 **     * The FTS3 module is being built as an extension
141771 **       (in which case SQLITE_CORE is not defined), or
141772 **
141773 **     * The FTS3 module is being built into the core of
141774 **       SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
141775 */
141776 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
141777
141778 /* #include <assert.h> */
141779 /* #include <stdlib.h> */
141780 /* #include <stdio.h> */
141781 /* #include <string.h> */
141782
141783
141784 typedef struct simple_tokenizer {
141785   sqlite3_tokenizer base;
141786   char delim[128];             /* flag ASCII delimiters */
141787 } simple_tokenizer;
141788
141789 typedef struct simple_tokenizer_cursor {
141790   sqlite3_tokenizer_cursor base;
141791   const char *pInput;          /* input we are tokenizing */
141792   int nBytes;                  /* size of the input */
141793   int iOffset;                 /* current position in pInput */
141794   int iToken;                  /* index of next token to be returned */
141795   char *pToken;                /* storage for current token */
141796   int nTokenAllocated;         /* space allocated to zToken buffer */
141797 } simple_tokenizer_cursor;
141798
141799
141800 static int simpleDelim(simple_tokenizer *t, unsigned char c){
141801   return c<0x80 && t->delim[c];
141802 }
141803 static int fts3_isalnum(int x){
141804   return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
141805 }
141806
141807 /*
141808 ** Create a new tokenizer instance.
141809 */
141810 static int simpleCreate(
141811   int argc, const char * const *argv,
141812   sqlite3_tokenizer **ppTokenizer
141813 ){
141814   simple_tokenizer *t;
141815
141816   t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
141817   if( t==NULL ) return SQLITE_NOMEM;
141818   memset(t, 0, sizeof(*t));
141819
141820   /* TODO(shess) Delimiters need to remain the same from run to run,
141821   ** else we need to reindex.  One solution would be a meta-table to
141822   ** track such information in the database, then we'd only want this
141823   ** information on the initial create.
141824   */
141825   if( argc>1 ){
141826     int i, n = (int)strlen(argv[1]);
141827     for(i=0; i<n; i++){
141828       unsigned char ch = argv[1][i];
141829       /* We explicitly don't support UTF-8 delimiters for now. */
141830       if( ch>=0x80 ){
141831         sqlite3_free(t);
141832         return SQLITE_ERROR;
141833       }
141834       t->delim[ch] = 1;
141835     }
141836   } else {
141837     /* Mark non-alphanumeric ASCII characters as delimiters */
141838     int i;
141839     for(i=1; i<0x80; i++){
141840       t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
141841     }
141842   }
141843
141844   *ppTokenizer = &t->base;
141845   return SQLITE_OK;
141846 }
141847
141848 /*
141849 ** Destroy a tokenizer
141850 */
141851 static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
141852   sqlite3_free(pTokenizer);
141853   return SQLITE_OK;
141854 }
141855
141856 /*
141857 ** Prepare to begin tokenizing a particular string.  The input
141858 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
141859 ** used to incrementally tokenize this string is returned in 
141860 ** *ppCursor.
141861 */
141862 static int simpleOpen(
141863   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
141864   const char *pInput, int nBytes,        /* String to be tokenized */
141865   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
141866 ){
141867   simple_tokenizer_cursor *c;
141868
141869   UNUSED_PARAMETER(pTokenizer);
141870
141871   c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
141872   if( c==NULL ) return SQLITE_NOMEM;
141873
141874   c->pInput = pInput;
141875   if( pInput==0 ){
141876     c->nBytes = 0;
141877   }else if( nBytes<0 ){
141878     c->nBytes = (int)strlen(pInput);
141879   }else{
141880     c->nBytes = nBytes;
141881   }
141882   c->iOffset = 0;                 /* start tokenizing at the beginning */
141883   c->iToken = 0;
141884   c->pToken = NULL;               /* no space allocated, yet. */
141885   c->nTokenAllocated = 0;
141886
141887   *ppCursor = &c->base;
141888   return SQLITE_OK;
141889 }
141890
141891 /*
141892 ** Close a tokenization cursor previously opened by a call to
141893 ** simpleOpen() above.
141894 */
141895 static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
141896   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
141897   sqlite3_free(c->pToken);
141898   sqlite3_free(c);
141899   return SQLITE_OK;
141900 }
141901
141902 /*
141903 ** Extract the next token from a tokenization cursor.  The cursor must
141904 ** have been opened by a prior call to simpleOpen().
141905 */
141906 static int simpleNext(
141907   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
141908   const char **ppToken,               /* OUT: *ppToken is the token text */
141909   int *pnBytes,                       /* OUT: Number of bytes in token */
141910   int *piStartOffset,                 /* OUT: Starting offset of token */
141911   int *piEndOffset,                   /* OUT: Ending offset of token */
141912   int *piPosition                     /* OUT: Position integer of token */
141913 ){
141914   simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
141915   simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
141916   unsigned char *p = (unsigned char *)c->pInput;
141917
141918   while( c->iOffset<c->nBytes ){
141919     int iStartOffset;
141920
141921     /* Scan past delimiter characters */
141922     while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
141923       c->iOffset++;
141924     }
141925
141926     /* Count non-delimiter characters. */
141927     iStartOffset = c->iOffset;
141928     while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
141929       c->iOffset++;
141930     }
141931
141932     if( c->iOffset>iStartOffset ){
141933       int i, n = c->iOffset-iStartOffset;
141934       if( n>c->nTokenAllocated ){
141935         char *pNew;
141936         c->nTokenAllocated = n+20;
141937         pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
141938         if( !pNew ) return SQLITE_NOMEM;
141939         c->pToken = pNew;
141940       }
141941       for(i=0; i<n; i++){
141942         /* TODO(shess) This needs expansion to handle UTF-8
141943         ** case-insensitivity.
141944         */
141945         unsigned char ch = p[iStartOffset+i];
141946         c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
141947       }
141948       *ppToken = c->pToken;
141949       *pnBytes = n;
141950       *piStartOffset = iStartOffset;
141951       *piEndOffset = c->iOffset;
141952       *piPosition = c->iToken++;
141953
141954       return SQLITE_OK;
141955     }
141956   }
141957   return SQLITE_DONE;
141958 }
141959
141960 /*
141961 ** The set of routines that implement the simple tokenizer
141962 */
141963 static const sqlite3_tokenizer_module simpleTokenizerModule = {
141964   0,
141965   simpleCreate,
141966   simpleDestroy,
141967   simpleOpen,
141968   simpleClose,
141969   simpleNext,
141970   0,
141971 };
141972
141973 /*
141974 ** Allocate a new simple tokenizer.  Return a pointer to the new
141975 ** tokenizer in *ppModule
141976 */
141977 SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
141978   sqlite3_tokenizer_module const**ppModule
141979 ){
141980   *ppModule = &simpleTokenizerModule;
141981 }
141982
141983 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
141984
141985 /************** End of fts3_tokenizer1.c *************************************/
141986 /************** Begin file fts3_tokenize_vtab.c ******************************/
141987 /*
141988 ** 2013 Apr 22
141989 **
141990 ** The author disclaims copyright to this source code.  In place of
141991 ** a legal notice, here is a blessing:
141992 **
141993 **    May you do good and not evil.
141994 **    May you find forgiveness for yourself and forgive others.
141995 **    May you share freely, never taking more than you give.
141996 **
141997 ******************************************************************************
141998 **
141999 ** This file contains code for the "fts3tokenize" virtual table module.
142000 ** An fts3tokenize virtual table is created as follows:
142001 **
142002 **   CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
142003 **       <tokenizer-name>, <arg-1>, ...
142004 **   );
142005 **
142006 ** The table created has the following schema:
142007 **
142008 **   CREATE TABLE <tbl>(input, token, start, end, position)
142009 **
142010 ** When queried, the query must include a WHERE clause of type:
142011 **
142012 **   input = <string>
142013 **
142014 ** The virtual table module tokenizes this <string>, using the FTS3 
142015 ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE 
142016 ** statement and returns one row for each token in the result. With
142017 ** fields set as follows:
142018 **
142019 **   input:   Always set to a copy of <string>
142020 **   token:   A token from the input.
142021 **   start:   Byte offset of the token within the input <string>.
142022 **   end:     Byte offset of the byte immediately following the end of the
142023 **            token within the input string.
142024 **   pos:     Token offset of token within input.
142025 **
142026 */
142027 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
142028
142029 /* #include <string.h> */
142030 /* #include <assert.h> */
142031
142032 typedef struct Fts3tokTable Fts3tokTable;
142033 typedef struct Fts3tokCursor Fts3tokCursor;
142034
142035 /*
142036 ** Virtual table structure.
142037 */
142038 struct Fts3tokTable {
142039   sqlite3_vtab base;              /* Base class used by SQLite core */
142040   const sqlite3_tokenizer_module *pMod;
142041   sqlite3_tokenizer *pTok;
142042 };
142043
142044 /*
142045 ** Virtual table cursor structure.
142046 */
142047 struct Fts3tokCursor {
142048   sqlite3_vtab_cursor base;       /* Base class used by SQLite core */
142049   char *zInput;                   /* Input string */
142050   sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
142051   int iRowid;                     /* Current 'rowid' value */
142052   const char *zToken;             /* Current 'token' value */
142053   int nToken;                     /* Size of zToken in bytes */
142054   int iStart;                     /* Current 'start' value */
142055   int iEnd;                       /* Current 'end' value */
142056   int iPos;                       /* Current 'pos' value */
142057 };
142058
142059 /*
142060 ** Query FTS for the tokenizer implementation named zName.
142061 */
142062 static int fts3tokQueryTokenizer(
142063   Fts3Hash *pHash,
142064   const char *zName,
142065   const sqlite3_tokenizer_module **pp,
142066   char **pzErr
142067 ){
142068   sqlite3_tokenizer_module *p;
142069   int nName = (int)strlen(zName);
142070
142071   p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
142072   if( !p ){
142073     *pzErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
142074     return SQLITE_ERROR;
142075   }
142076
142077   *pp = p;
142078   return SQLITE_OK;
142079 }
142080
142081 /*
142082 ** The second argument, argv[], is an array of pointers to nul-terminated
142083 ** strings. This function makes a copy of the array and strings into a 
142084 ** single block of memory. It then dequotes any of the strings that appear
142085 ** to be quoted.
142086 **
142087 ** If successful, output parameter *pazDequote is set to point at the
142088 ** array of dequoted strings and SQLITE_OK is returned. The caller is
142089 ** responsible for eventually calling sqlite3_free() to free the array
142090 ** in this case. Or, if an error occurs, an SQLite error code is returned.
142091 ** The final value of *pazDequote is undefined in this case.
142092 */
142093 static int fts3tokDequoteArray(
142094   int argc,                       /* Number of elements in argv[] */
142095   const char * const *argv,       /* Input array */
142096   char ***pazDequote              /* Output array */
142097 ){
142098   int rc = SQLITE_OK;             /* Return code */
142099   if( argc==0 ){
142100     *pazDequote = 0;
142101   }else{
142102     int i;
142103     int nByte = 0;
142104     char **azDequote;
142105
142106     for(i=0; i<argc; i++){
142107       nByte += (int)(strlen(argv[i]) + 1);
142108     }
142109
142110     *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
142111     if( azDequote==0 ){
142112       rc = SQLITE_NOMEM;
142113     }else{
142114       char *pSpace = (char *)&azDequote[argc];
142115       for(i=0; i<argc; i++){
142116         int n = (int)strlen(argv[i]);
142117         azDequote[i] = pSpace;
142118         memcpy(pSpace, argv[i], n+1);
142119         sqlite3Fts3Dequote(pSpace);
142120         pSpace += (n+1);
142121       }
142122     }
142123   }
142124
142125   return rc;
142126 }
142127
142128 /*
142129 ** Schema of the tokenizer table.
142130 */
142131 #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
142132
142133 /*
142134 ** This function does all the work for both the xConnect and xCreate methods.
142135 ** These tables have no persistent representation of their own, so xConnect
142136 ** and xCreate are identical operations.
142137 **
142138 **   argv[0]: module name
142139 **   argv[1]: database name 
142140 **   argv[2]: table name
142141 **   argv[3]: first argument (tokenizer name)
142142 */
142143 static int fts3tokConnectMethod(
142144   sqlite3 *db,                    /* Database connection */
142145   void *pHash,                    /* Hash table of tokenizers */
142146   int argc,                       /* Number of elements in argv array */
142147   const char * const *argv,       /* xCreate/xConnect argument array */
142148   sqlite3_vtab **ppVtab,          /* OUT: New sqlite3_vtab object */
142149   char **pzErr                    /* OUT: sqlite3_malloc'd error message */
142150 ){
142151   Fts3tokTable *pTab = 0;
142152   const sqlite3_tokenizer_module *pMod = 0;
142153   sqlite3_tokenizer *pTok = 0;
142154   int rc;
142155   char **azDequote = 0;
142156   int nDequote;
142157
142158   rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
142159   if( rc!=SQLITE_OK ) return rc;
142160
142161   nDequote = argc-3;
142162   rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
142163
142164   if( rc==SQLITE_OK ){
142165     const char *zModule;
142166     if( nDequote<1 ){
142167       zModule = "simple";
142168     }else{
142169       zModule = azDequote[0];
142170     }
142171     rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
142172   }
142173
142174   assert( (rc==SQLITE_OK)==(pMod!=0) );
142175   if( rc==SQLITE_OK ){
142176     const char * const *azArg = (const char * const *)&azDequote[1];
142177     rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
142178   }
142179
142180   if( rc==SQLITE_OK ){
142181     pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
142182     if( pTab==0 ){
142183       rc = SQLITE_NOMEM;
142184     }
142185   }
142186
142187   if( rc==SQLITE_OK ){
142188     memset(pTab, 0, sizeof(Fts3tokTable));
142189     pTab->pMod = pMod;
142190     pTab->pTok = pTok;
142191     *ppVtab = &pTab->base;
142192   }else{
142193     if( pTok ){
142194       pMod->xDestroy(pTok);
142195     }
142196   }
142197
142198   sqlite3_free(azDequote);
142199   return rc;
142200 }
142201
142202 /*
142203 ** This function does the work for both the xDisconnect and xDestroy methods.
142204 ** These tables have no persistent representation of their own, so xDisconnect
142205 ** and xDestroy are identical operations.
142206 */
142207 static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
142208   Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
142209
142210   pTab->pMod->xDestroy(pTab->pTok);
142211   sqlite3_free(pTab);
142212   return SQLITE_OK;
142213 }
142214
142215 /*
142216 ** xBestIndex - Analyze a WHERE and ORDER BY clause.
142217 */
142218 static int fts3tokBestIndexMethod(
142219   sqlite3_vtab *pVTab, 
142220   sqlite3_index_info *pInfo
142221 ){
142222   int i;
142223   UNUSED_PARAMETER(pVTab);
142224
142225   for(i=0; i<pInfo->nConstraint; i++){
142226     if( pInfo->aConstraint[i].usable 
142227      && pInfo->aConstraint[i].iColumn==0 
142228      && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ 
142229     ){
142230       pInfo->idxNum = 1;
142231       pInfo->aConstraintUsage[i].argvIndex = 1;
142232       pInfo->aConstraintUsage[i].omit = 1;
142233       pInfo->estimatedCost = 1;
142234       return SQLITE_OK;
142235     }
142236   }
142237
142238   pInfo->idxNum = 0;
142239   assert( pInfo->estimatedCost>1000000.0 );
142240
142241   return SQLITE_OK;
142242 }
142243
142244 /*
142245 ** xOpen - Open a cursor.
142246 */
142247 static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
142248   Fts3tokCursor *pCsr;
142249   UNUSED_PARAMETER(pVTab);
142250
142251   pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
142252   if( pCsr==0 ){
142253     return SQLITE_NOMEM;
142254   }
142255   memset(pCsr, 0, sizeof(Fts3tokCursor));
142256
142257   *ppCsr = (sqlite3_vtab_cursor *)pCsr;
142258   return SQLITE_OK;
142259 }
142260
142261 /*
142262 ** Reset the tokenizer cursor passed as the only argument. As if it had
142263 ** just been returned by fts3tokOpenMethod().
142264 */
142265 static void fts3tokResetCursor(Fts3tokCursor *pCsr){
142266   if( pCsr->pCsr ){
142267     Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
142268     pTab->pMod->xClose(pCsr->pCsr);
142269     pCsr->pCsr = 0;
142270   }
142271   sqlite3_free(pCsr->zInput);
142272   pCsr->zInput = 0;
142273   pCsr->zToken = 0;
142274   pCsr->nToken = 0;
142275   pCsr->iStart = 0;
142276   pCsr->iEnd = 0;
142277   pCsr->iPos = 0;
142278   pCsr->iRowid = 0;
142279 }
142280
142281 /*
142282 ** xClose - Close a cursor.
142283 */
142284 static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
142285   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
142286
142287   fts3tokResetCursor(pCsr);
142288   sqlite3_free(pCsr);
142289   return SQLITE_OK;
142290 }
142291
142292 /*
142293 ** xNext - Advance the cursor to the next row, if any.
142294 */
142295 static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
142296   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
142297   Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
142298   int rc;                         /* Return code */
142299
142300   pCsr->iRowid++;
142301   rc = pTab->pMod->xNext(pCsr->pCsr,
142302       &pCsr->zToken, &pCsr->nToken,
142303       &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
142304   );
142305
142306   if( rc!=SQLITE_OK ){
142307     fts3tokResetCursor(pCsr);
142308     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
142309   }
142310
142311   return rc;
142312 }
142313
142314 /*
142315 ** xFilter - Initialize a cursor to point at the start of its data.
142316 */
142317 static int fts3tokFilterMethod(
142318   sqlite3_vtab_cursor *pCursor,   /* The cursor used for this query */
142319   int idxNum,                     /* Strategy index */
142320   const char *idxStr,             /* Unused */
142321   int nVal,                       /* Number of elements in apVal */
142322   sqlite3_value **apVal           /* Arguments for the indexing scheme */
142323 ){
142324   int rc = SQLITE_ERROR;
142325   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
142326   Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
142327   UNUSED_PARAMETER(idxStr);
142328   UNUSED_PARAMETER(nVal);
142329
142330   fts3tokResetCursor(pCsr);
142331   if( idxNum==1 ){
142332     const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
142333     int nByte = sqlite3_value_bytes(apVal[0]);
142334     pCsr->zInput = sqlite3_malloc(nByte+1);
142335     if( pCsr->zInput==0 ){
142336       rc = SQLITE_NOMEM;
142337     }else{
142338       memcpy(pCsr->zInput, zByte, nByte);
142339       pCsr->zInput[nByte] = 0;
142340       rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
142341       if( rc==SQLITE_OK ){
142342         pCsr->pCsr->pTokenizer = pTab->pTok;
142343       }
142344     }
142345   }
142346
142347   if( rc!=SQLITE_OK ) return rc;
142348   return fts3tokNextMethod(pCursor);
142349 }
142350
142351 /*
142352 ** xEof - Return true if the cursor is at EOF, or false otherwise.
142353 */
142354 static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
142355   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
142356   return (pCsr->zToken==0);
142357 }
142358
142359 /*
142360 ** xColumn - Return a column value.
142361 */
142362 static int fts3tokColumnMethod(
142363   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
142364   sqlite3_context *pCtx,          /* Context for sqlite3_result_xxx() calls */
142365   int iCol                        /* Index of column to read value from */
142366 ){
142367   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
142368
142369   /* CREATE TABLE x(input, token, start, end, position) */
142370   switch( iCol ){
142371     case 0:
142372       sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
142373       break;
142374     case 1:
142375       sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
142376       break;
142377     case 2:
142378       sqlite3_result_int(pCtx, pCsr->iStart);
142379       break;
142380     case 3:
142381       sqlite3_result_int(pCtx, pCsr->iEnd);
142382       break;
142383     default:
142384       assert( iCol==4 );
142385       sqlite3_result_int(pCtx, pCsr->iPos);
142386       break;
142387   }
142388   return SQLITE_OK;
142389 }
142390
142391 /*
142392 ** xRowid - Return the current rowid for the cursor.
142393 */
142394 static int fts3tokRowidMethod(
142395   sqlite3_vtab_cursor *pCursor,   /* Cursor to retrieve value from */
142396   sqlite_int64 *pRowid            /* OUT: Rowid value */
142397 ){
142398   Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
142399   *pRowid = (sqlite3_int64)pCsr->iRowid;
142400   return SQLITE_OK;
142401 }
142402
142403 /*
142404 ** Register the fts3tok module with database connection db. Return SQLITE_OK
142405 ** if successful or an error code if sqlite3_create_module() fails.
142406 */
142407 SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
142408   static const sqlite3_module fts3tok_module = {
142409      0,                           /* iVersion      */
142410      fts3tokConnectMethod,        /* xCreate       */
142411      fts3tokConnectMethod,        /* xConnect      */
142412      fts3tokBestIndexMethod,      /* xBestIndex    */
142413      fts3tokDisconnectMethod,     /* xDisconnect   */
142414      fts3tokDisconnectMethod,     /* xDestroy      */
142415      fts3tokOpenMethod,           /* xOpen         */
142416      fts3tokCloseMethod,          /* xClose        */
142417      fts3tokFilterMethod,         /* xFilter       */
142418      fts3tokNextMethod,           /* xNext         */
142419      fts3tokEofMethod,            /* xEof          */
142420      fts3tokColumnMethod,         /* xColumn       */
142421      fts3tokRowidMethod,          /* xRowid        */
142422      0,                           /* xUpdate       */
142423      0,                           /* xBegin        */
142424      0,                           /* xSync         */
142425      0,                           /* xCommit       */
142426      0,                           /* xRollback     */
142427      0,                           /* xFindFunction */
142428      0,                           /* xRename       */
142429      0,                           /* xSavepoint    */
142430      0,                           /* xRelease      */
142431      0                            /* xRollbackTo   */
142432   };
142433   int rc;                         /* Return code */
142434
142435   rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
142436   return rc;
142437 }
142438
142439 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
142440
142441 /************** End of fts3_tokenize_vtab.c **********************************/
142442 /************** Begin file fts3_write.c **************************************/
142443 /*
142444 ** 2009 Oct 23
142445 **
142446 ** The author disclaims copyright to this source code.  In place of
142447 ** a legal notice, here is a blessing:
142448 **
142449 **    May you do good and not evil.
142450 **    May you find forgiveness for yourself and forgive others.
142451 **    May you share freely, never taking more than you give.
142452 **
142453 ******************************************************************************
142454 **
142455 ** This file is part of the SQLite FTS3 extension module. Specifically,
142456 ** this file contains code to insert, update and delete rows from FTS3
142457 ** tables. It also contains code to merge FTS3 b-tree segments. Some
142458 ** of the sub-routines used to merge segments are also used by the query 
142459 ** code in fts3.c.
142460 */
142461
142462 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
142463
142464 /* #include <string.h> */
142465 /* #include <assert.h> */
142466 /* #include <stdlib.h> */
142467
142468
142469 #define FTS_MAX_APPENDABLE_HEIGHT 16
142470
142471 /*
142472 ** When full-text index nodes are loaded from disk, the buffer that they
142473 ** are loaded into has the following number of bytes of padding at the end 
142474 ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
142475 ** of 920 bytes is allocated for it.
142476 **
142477 ** This means that if we have a pointer into a buffer containing node data,
142478 ** it is always safe to read up to two varints from it without risking an
142479 ** overread, even if the node data is corrupted.
142480 */
142481 #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
142482
142483 /*
142484 ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
142485 ** memory incrementally instead of all at once. This can be a big performance
142486 ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
142487 ** method before retrieving all query results (as may happen, for example,
142488 ** if a query has a LIMIT clause).
142489 **
142490 ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD 
142491 ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
142492 ** The code is written so that the hard lower-limit for each of these values 
142493 ** is 1. Clearly such small values would be inefficient, but can be useful 
142494 ** for testing purposes.
142495 **
142496 ** If this module is built with SQLITE_TEST defined, these constants may
142497 ** be overridden at runtime for testing purposes. File fts3_test.c contains
142498 ** a Tcl interface to read and write the values.
142499 */
142500 #ifdef SQLITE_TEST
142501 int test_fts3_node_chunksize = (4*1024);
142502 int test_fts3_node_chunk_threshold = (4*1024)*4;
142503 # define FTS3_NODE_CHUNKSIZE       test_fts3_node_chunksize
142504 # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
142505 #else
142506 # define FTS3_NODE_CHUNKSIZE (4*1024) 
142507 # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
142508 #endif
142509
142510 /*
142511 ** The two values that may be meaningfully bound to the :1 parameter in
142512 ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
142513 */
142514 #define FTS_STAT_DOCTOTAL      0
142515 #define FTS_STAT_INCRMERGEHINT 1
142516 #define FTS_STAT_AUTOINCRMERGE 2
142517
142518 /*
142519 ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
142520 ** and incremental merge operation that takes place. This is used for 
142521 ** debugging FTS only, it should not usually be turned on in production
142522 ** systems.
142523 */
142524 #ifdef FTS3_LOG_MERGES
142525 static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
142526   sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
142527 }
142528 #else
142529 #define fts3LogMerge(x, y)
142530 #endif
142531
142532
142533 typedef struct PendingList PendingList;
142534 typedef struct SegmentNode SegmentNode;
142535 typedef struct SegmentWriter SegmentWriter;
142536
142537 /*
142538 ** An instance of the following data structure is used to build doclists
142539 ** incrementally. See function fts3PendingListAppend() for details.
142540 */
142541 struct PendingList {
142542   int nData;
142543   char *aData;
142544   int nSpace;
142545   sqlite3_int64 iLastDocid;
142546   sqlite3_int64 iLastCol;
142547   sqlite3_int64 iLastPos;
142548 };
142549
142550
142551 /*
142552 ** Each cursor has a (possibly empty) linked list of the following objects.
142553 */
142554 struct Fts3DeferredToken {
142555   Fts3PhraseToken *pToken;        /* Pointer to corresponding expr token */
142556   int iCol;                       /* Column token must occur in */
142557   Fts3DeferredToken *pNext;       /* Next in list of deferred tokens */
142558   PendingList *pList;             /* Doclist is assembled here */
142559 };
142560
142561 /*
142562 ** An instance of this structure is used to iterate through the terms on
142563 ** a contiguous set of segment b-tree leaf nodes. Although the details of
142564 ** this structure are only manipulated by code in this file, opaque handles
142565 ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
142566 ** terms when querying the full-text index. See functions:
142567 **
142568 **   sqlite3Fts3SegReaderNew()
142569 **   sqlite3Fts3SegReaderFree()
142570 **   sqlite3Fts3SegReaderIterate()
142571 **
142572 ** Methods used to manipulate Fts3SegReader structures:
142573 **
142574 **   fts3SegReaderNext()
142575 **   fts3SegReaderFirstDocid()
142576 **   fts3SegReaderNextDocid()
142577 */
142578 struct Fts3SegReader {
142579   int iIdx;                       /* Index within level, or 0x7FFFFFFF for PT */
142580   u8 bLookup;                     /* True for a lookup only */
142581   u8 rootOnly;                    /* True for a root-only reader */
142582
142583   sqlite3_int64 iStartBlock;      /* Rowid of first leaf block to traverse */
142584   sqlite3_int64 iLeafEndBlock;    /* Rowid of final leaf block to traverse */
142585   sqlite3_int64 iEndBlock;        /* Rowid of final block in segment (or 0) */
142586   sqlite3_int64 iCurrentBlock;    /* Current leaf block (or 0) */
142587
142588   char *aNode;                    /* Pointer to node data (or NULL) */
142589   int nNode;                      /* Size of buffer at aNode (or 0) */
142590   int nPopulate;                  /* If >0, bytes of buffer aNode[] loaded */
142591   sqlite3_blob *pBlob;            /* If not NULL, blob handle to read node */
142592
142593   Fts3HashElem **ppNextElem;
142594
142595   /* Variables set by fts3SegReaderNext(). These may be read directly
142596   ** by the caller. They are valid from the time SegmentReaderNew() returns
142597   ** until SegmentReaderNext() returns something other than SQLITE_OK
142598   ** (i.e. SQLITE_DONE).
142599   */
142600   int nTerm;                      /* Number of bytes in current term */
142601   char *zTerm;                    /* Pointer to current term */
142602   int nTermAlloc;                 /* Allocated size of zTerm buffer */
142603   char *aDoclist;                 /* Pointer to doclist of current entry */
142604   int nDoclist;                   /* Size of doclist in current entry */
142605
142606   /* The following variables are used by fts3SegReaderNextDocid() to iterate 
142607   ** through the current doclist (aDoclist/nDoclist).
142608   */
142609   char *pOffsetList;
142610   int nOffsetList;                /* For descending pending seg-readers only */
142611   sqlite3_int64 iDocid;
142612 };
142613
142614 #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
142615 #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
142616
142617 /*
142618 ** An instance of this structure is used to create a segment b-tree in the
142619 ** database. The internal details of this type are only accessed by the
142620 ** following functions:
142621 **
142622 **   fts3SegWriterAdd()
142623 **   fts3SegWriterFlush()
142624 **   fts3SegWriterFree()
142625 */
142626 struct SegmentWriter {
142627   SegmentNode *pTree;             /* Pointer to interior tree structure */
142628   sqlite3_int64 iFirst;           /* First slot in %_segments written */
142629   sqlite3_int64 iFree;            /* Next free slot in %_segments */
142630   char *zTerm;                    /* Pointer to previous term buffer */
142631   int nTerm;                      /* Number of bytes in zTerm */
142632   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
142633   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
142634   int nSize;                      /* Size of allocation at aData */
142635   int nData;                      /* Bytes of data in aData */
142636   char *aData;                    /* Pointer to block from malloc() */
142637   i64 nLeafData;                  /* Number of bytes of leaf data written */
142638 };
142639
142640 /*
142641 ** Type SegmentNode is used by the following three functions to create
142642 ** the interior part of the segment b+-tree structures (everything except
142643 ** the leaf nodes). These functions and type are only ever used by code
142644 ** within the fts3SegWriterXXX() family of functions described above.
142645 **
142646 **   fts3NodeAddTerm()
142647 **   fts3NodeWrite()
142648 **   fts3NodeFree()
142649 **
142650 ** When a b+tree is written to the database (either as a result of a merge
142651 ** or the pending-terms table being flushed), leaves are written into the 
142652 ** database file as soon as they are completely populated. The interior of
142653 ** the tree is assembled in memory and written out only once all leaves have
142654 ** been populated and stored. This is Ok, as the b+-tree fanout is usually
142655 ** very large, meaning that the interior of the tree consumes relatively 
142656 ** little memory.
142657 */
142658 struct SegmentNode {
142659   SegmentNode *pParent;           /* Parent node (or NULL for root node) */
142660   SegmentNode *pRight;            /* Pointer to right-sibling */
142661   SegmentNode *pLeftmost;         /* Pointer to left-most node of this depth */
142662   int nEntry;                     /* Number of terms written to node so far */
142663   char *zTerm;                    /* Pointer to previous term buffer */
142664   int nTerm;                      /* Number of bytes in zTerm */
142665   int nMalloc;                    /* Size of malloc'd buffer at zMalloc */
142666   char *zMalloc;                  /* Malloc'd space (possibly) used for zTerm */
142667   int nData;                      /* Bytes of valid data so far */
142668   char *aData;                    /* Node data */
142669 };
142670
142671 /*
142672 ** Valid values for the second argument to fts3SqlStmt().
142673 */
142674 #define SQL_DELETE_CONTENT             0
142675 #define SQL_IS_EMPTY                   1
142676 #define SQL_DELETE_ALL_CONTENT         2 
142677 #define SQL_DELETE_ALL_SEGMENTS        3
142678 #define SQL_DELETE_ALL_SEGDIR          4
142679 #define SQL_DELETE_ALL_DOCSIZE         5
142680 #define SQL_DELETE_ALL_STAT            6
142681 #define SQL_SELECT_CONTENT_BY_ROWID    7
142682 #define SQL_NEXT_SEGMENT_INDEX         8
142683 #define SQL_INSERT_SEGMENTS            9
142684 #define SQL_NEXT_SEGMENTS_ID          10
142685 #define SQL_INSERT_SEGDIR             11
142686 #define SQL_SELECT_LEVEL              12
142687 #define SQL_SELECT_LEVEL_RANGE        13
142688 #define SQL_SELECT_LEVEL_COUNT        14
142689 #define SQL_SELECT_SEGDIR_MAX_LEVEL   15
142690 #define SQL_DELETE_SEGDIR_LEVEL       16
142691 #define SQL_DELETE_SEGMENTS_RANGE     17
142692 #define SQL_CONTENT_INSERT            18
142693 #define SQL_DELETE_DOCSIZE            19
142694 #define SQL_REPLACE_DOCSIZE           20
142695 #define SQL_SELECT_DOCSIZE            21
142696 #define SQL_SELECT_STAT               22
142697 #define SQL_REPLACE_STAT              23
142698
142699 #define SQL_SELECT_ALL_PREFIX_LEVEL   24
142700 #define SQL_DELETE_ALL_TERMS_SEGDIR   25
142701 #define SQL_DELETE_SEGDIR_RANGE       26
142702 #define SQL_SELECT_ALL_LANGID         27
142703 #define SQL_FIND_MERGE_LEVEL          28
142704 #define SQL_MAX_LEAF_NODE_ESTIMATE    29
142705 #define SQL_DELETE_SEGDIR_ENTRY       30
142706 #define SQL_SHIFT_SEGDIR_ENTRY        31
142707 #define SQL_SELECT_SEGDIR             32
142708 #define SQL_CHOMP_SEGDIR              33
142709 #define SQL_SEGMENT_IS_APPENDABLE     34
142710 #define SQL_SELECT_INDEXES            35
142711 #define SQL_SELECT_MXLEVEL            36
142712
142713 #define SQL_SELECT_LEVEL_RANGE2       37
142714 #define SQL_UPDATE_LEVEL_IDX          38
142715 #define SQL_UPDATE_LEVEL              39
142716
142717 /*
142718 ** This function is used to obtain an SQLite prepared statement handle
142719 ** for the statement identified by the second argument. If successful,
142720 ** *pp is set to the requested statement handle and SQLITE_OK returned.
142721 ** Otherwise, an SQLite error code is returned and *pp is set to 0.
142722 **
142723 ** If argument apVal is not NULL, then it must point to an array with
142724 ** at least as many entries as the requested statement has bound 
142725 ** parameters. The values are bound to the statements parameters before
142726 ** returning.
142727 */
142728 static int fts3SqlStmt(
142729   Fts3Table *p,                   /* Virtual table handle */
142730   int eStmt,                      /* One of the SQL_XXX constants above */
142731   sqlite3_stmt **pp,              /* OUT: Statement handle */
142732   sqlite3_value **apVal           /* Values to bind to statement */
142733 ){
142734   const char *azSql[] = {
142735 /* 0  */  "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
142736 /* 1  */  "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
142737 /* 2  */  "DELETE FROM %Q.'%q_content'",
142738 /* 3  */  "DELETE FROM %Q.'%q_segments'",
142739 /* 4  */  "DELETE FROM %Q.'%q_segdir'",
142740 /* 5  */  "DELETE FROM %Q.'%q_docsize'",
142741 /* 6  */  "DELETE FROM %Q.'%q_stat'",
142742 /* 7  */  "SELECT %s WHERE rowid=?",
142743 /* 8  */  "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
142744 /* 9  */  "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
142745 /* 10 */  "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
142746 /* 11 */  "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
142747
142748           /* Return segments in order from oldest to newest.*/ 
142749 /* 12 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
142750             "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
142751 /* 13 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
142752             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
142753             "ORDER BY level DESC, idx ASC",
142754
142755 /* 14 */  "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
142756 /* 15 */  "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
142757
142758 /* 16 */  "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
142759 /* 17 */  "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
142760 /* 18 */  "INSERT INTO %Q.'%q_content' VALUES(%s)",
142761 /* 19 */  "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
142762 /* 20 */  "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
142763 /* 21 */  "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
142764 /* 22 */  "SELECT value FROM %Q.'%q_stat' WHERE id=?",
142765 /* 23 */  "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
142766 /* 24 */  "",
142767 /* 25 */  "",
142768
142769 /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
142770 /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
142771
142772 /* This statement is used to determine which level to read the input from
142773 ** when performing an incremental merge. It returns the absolute level number
142774 ** of the oldest level in the db that contains at least ? segments. Or,
142775 ** if no level in the FTS index contains more than ? segments, the statement
142776 ** returns zero rows.  */
142777 /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
142778          "  ORDER BY (level %% 1024) ASC LIMIT 1",
142779
142780 /* Estimate the upper limit on the number of leaf nodes in a new segment
142781 ** created by merging the oldest :2 segments from absolute level :1. See 
142782 ** function sqlite3Fts3Incrmerge() for details.  */
142783 /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
142784          "  FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
142785
142786 /* SQL_DELETE_SEGDIR_ENTRY
142787 **   Delete the %_segdir entry on absolute level :1 with index :2.  */
142788 /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
142789
142790 /* SQL_SHIFT_SEGDIR_ENTRY
142791 **   Modify the idx value for the segment with idx=:3 on absolute level :2
142792 **   to :1.  */
142793 /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
142794
142795 /* SQL_SELECT_SEGDIR
142796 **   Read a single entry from the %_segdir table. The entry from absolute 
142797 **   level :1 with index value :2.  */
142798 /* 32 */  "SELECT idx, start_block, leaves_end_block, end_block, root "
142799             "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
142800
142801 /* SQL_CHOMP_SEGDIR
142802 **   Update the start_block (:1) and root (:2) fields of the %_segdir
142803 **   entry located on absolute level :3 with index :4.  */
142804 /* 33 */  "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
142805             "WHERE level = ? AND idx = ?",
142806
142807 /* SQL_SEGMENT_IS_APPENDABLE
142808 **   Return a single row if the segment with end_block=? is appendable. Or
142809 **   no rows otherwise.  */
142810 /* 34 */  "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
142811
142812 /* SQL_SELECT_INDEXES
142813 **   Return the list of valid segment indexes for absolute level ?  */
142814 /* 35 */  "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
142815
142816 /* SQL_SELECT_MXLEVEL
142817 **   Return the largest relative level in the FTS index or indexes.  */
142818 /* 36 */  "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
142819
142820           /* Return segments in order from oldest to newest.*/ 
142821 /* 37 */  "SELECT level, idx, end_block "
142822             "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
142823             "ORDER BY level DESC, idx ASC",
142824
142825           /* Update statements used while promoting segments */
142826 /* 38 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
142827             "WHERE level=? AND idx=?",
142828 /* 39 */  "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
142829
142830   };
142831   int rc = SQLITE_OK;
142832   sqlite3_stmt *pStmt;
142833
142834   assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
142835   assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
142836   
142837   pStmt = p->aStmt[eStmt];
142838   if( !pStmt ){
142839     char *zSql;
142840     if( eStmt==SQL_CONTENT_INSERT ){
142841       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
142842     }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
142843       zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
142844     }else{
142845       zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
142846     }
142847     if( !zSql ){
142848       rc = SQLITE_NOMEM;
142849     }else{
142850       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
142851       sqlite3_free(zSql);
142852       assert( rc==SQLITE_OK || pStmt==0 );
142853       p->aStmt[eStmt] = pStmt;
142854     }
142855   }
142856   if( apVal ){
142857     int i;
142858     int nParam = sqlite3_bind_parameter_count(pStmt);
142859     for(i=0; rc==SQLITE_OK && i<nParam; i++){
142860       rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
142861     }
142862   }
142863   *pp = pStmt;
142864   return rc;
142865 }
142866
142867
142868 static int fts3SelectDocsize(
142869   Fts3Table *pTab,                /* FTS3 table handle */
142870   sqlite3_int64 iDocid,           /* Docid to bind for SQL_SELECT_DOCSIZE */
142871   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
142872 ){
142873   sqlite3_stmt *pStmt = 0;        /* Statement requested from fts3SqlStmt() */
142874   int rc;                         /* Return code */
142875
142876   rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
142877   if( rc==SQLITE_OK ){
142878     sqlite3_bind_int64(pStmt, 1, iDocid);
142879     rc = sqlite3_step(pStmt);
142880     if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
142881       rc = sqlite3_reset(pStmt);
142882       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
142883       pStmt = 0;
142884     }else{
142885       rc = SQLITE_OK;
142886     }
142887   }
142888
142889   *ppStmt = pStmt;
142890   return rc;
142891 }
142892
142893 SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
142894   Fts3Table *pTab,                /* Fts3 table handle */
142895   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
142896 ){
142897   sqlite3_stmt *pStmt = 0;
142898   int rc;
142899   rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
142900   if( rc==SQLITE_OK ){
142901     sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
142902     if( sqlite3_step(pStmt)!=SQLITE_ROW
142903      || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
142904     ){
142905       rc = sqlite3_reset(pStmt);
142906       if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
142907       pStmt = 0;
142908     }
142909   }
142910   *ppStmt = pStmt;
142911   return rc;
142912 }
142913
142914 SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
142915   Fts3Table *pTab,                /* Fts3 table handle */
142916   sqlite3_int64 iDocid,           /* Docid to read size data for */
142917   sqlite3_stmt **ppStmt           /* OUT: Statement handle */
142918 ){
142919   return fts3SelectDocsize(pTab, iDocid, ppStmt);
142920 }
142921
142922 /*
142923 ** Similar to fts3SqlStmt(). Except, after binding the parameters in
142924 ** array apVal[] to the SQL statement identified by eStmt, the statement
142925 ** is executed.
142926 **
142927 ** Returns SQLITE_OK if the statement is successfully executed, or an
142928 ** SQLite error code otherwise.
142929 */
142930 static void fts3SqlExec(
142931   int *pRC,                /* Result code */
142932   Fts3Table *p,            /* The FTS3 table */
142933   int eStmt,               /* Index of statement to evaluate */
142934   sqlite3_value **apVal    /* Parameters to bind */
142935 ){
142936   sqlite3_stmt *pStmt;
142937   int rc;
142938   if( *pRC ) return;
142939   rc = fts3SqlStmt(p, eStmt, &pStmt, apVal); 
142940   if( rc==SQLITE_OK ){
142941     sqlite3_step(pStmt);
142942     rc = sqlite3_reset(pStmt);
142943   }
142944   *pRC = rc;
142945 }
142946
142947
142948 /*
142949 ** This function ensures that the caller has obtained an exclusive 
142950 ** shared-cache table-lock on the %_segdir table. This is required before 
142951 ** writing data to the fts3 table. If this lock is not acquired first, then
142952 ** the caller may end up attempting to take this lock as part of committing
142953 ** a transaction, causing SQLite to return SQLITE_LOCKED or 
142954 ** LOCKED_SHAREDCACHEto a COMMIT command.
142955 **
142956 ** It is best to avoid this because if FTS3 returns any error when 
142957 ** committing a transaction, the whole transaction will be rolled back. 
142958 ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE. 
142959 ** It can still happen if the user locks the underlying tables directly 
142960 ** instead of accessing them via FTS.
142961 */
142962 static int fts3Writelock(Fts3Table *p){
142963   int rc = SQLITE_OK;
142964   
142965   if( p->nPendingData==0 ){
142966     sqlite3_stmt *pStmt;
142967     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
142968     if( rc==SQLITE_OK ){
142969       sqlite3_bind_null(pStmt, 1);
142970       sqlite3_step(pStmt);
142971       rc = sqlite3_reset(pStmt);
142972     }
142973   }
142974
142975   return rc;
142976 }
142977
142978 /*
142979 ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
142980 ** Within each language id, a separate index is maintained to store the
142981 ** document terms, and each configured prefix size (configured the FTS 
142982 ** "prefix=" option). And each index consists of multiple levels ("relative
142983 ** levels").
142984 **
142985 ** All three of these values (the language id, the specific index and the
142986 ** level within the index) are encoded in 64-bit integer values stored
142987 ** in the %_segdir table on disk. This function is used to convert three
142988 ** separate component values into the single 64-bit integer value that
142989 ** can be used to query the %_segdir table.
142990 **
142991 ** Specifically, each language-id/index combination is allocated 1024 
142992 ** 64-bit integer level values ("absolute levels"). The main terms index
142993 ** for language-id 0 is allocate values 0-1023. The first prefix index
142994 ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
142995 ** Language 1 indexes are allocated immediately following language 0.
142996 **
142997 ** So, for a system with nPrefix prefix indexes configured, the block of
142998 ** absolute levels that corresponds to language-id iLangid and index 
142999 ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
143000 */
143001 static sqlite3_int64 getAbsoluteLevel(
143002   Fts3Table *p,                   /* FTS3 table handle */
143003   int iLangid,                    /* Language id */
143004   int iIndex,                     /* Index in p->aIndex[] */
143005   int iLevel                      /* Level of segments */
143006 ){
143007   sqlite3_int64 iBase;            /* First absolute level for iLangid/iIndex */
143008   assert( iLangid>=0 );
143009   assert( p->nIndex>0 );
143010   assert( iIndex>=0 && iIndex<p->nIndex );
143011
143012   iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
143013   return iBase + iLevel;
143014 }
143015
143016 /*
143017 ** Set *ppStmt to a statement handle that may be used to iterate through
143018 ** all rows in the %_segdir table, from oldest to newest. If successful,
143019 ** return SQLITE_OK. If an error occurs while preparing the statement, 
143020 ** return an SQLite error code.
143021 **
143022 ** There is only ever one instance of this SQL statement compiled for
143023 ** each FTS3 table.
143024 **
143025 ** The statement returns the following columns from the %_segdir table:
143026 **
143027 **   0: idx
143028 **   1: start_block
143029 **   2: leaves_end_block
143030 **   3: end_block
143031 **   4: root
143032 */
143033 SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
143034   Fts3Table *p,                   /* FTS3 table */
143035   int iLangid,                    /* Language being queried */
143036   int iIndex,                     /* Index for p->aIndex[] */
143037   int iLevel,                     /* Level to select (relative level) */
143038   sqlite3_stmt **ppStmt           /* OUT: Compiled statement */
143039 ){
143040   int rc;
143041   sqlite3_stmt *pStmt = 0;
143042
143043   assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
143044   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
143045   assert( iIndex>=0 && iIndex<p->nIndex );
143046
143047   if( iLevel<0 ){
143048     /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
143049     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
143050     if( rc==SQLITE_OK ){ 
143051       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
143052       sqlite3_bind_int64(pStmt, 2, 
143053           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
143054       );
143055     }
143056   }else{
143057     /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
143058     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
143059     if( rc==SQLITE_OK ){ 
143060       sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
143061     }
143062   }
143063   *ppStmt = pStmt;
143064   return rc;
143065 }
143066
143067
143068 /*
143069 ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
143070 ** if successful, or an SQLite error code otherwise.
143071 **
143072 ** This function also serves to allocate the PendingList structure itself.
143073 ** For example, to create a new PendingList structure containing two
143074 ** varints:
143075 **
143076 **   PendingList *p = 0;
143077 **   fts3PendingListAppendVarint(&p, 1);
143078 **   fts3PendingListAppendVarint(&p, 2);
143079 */
143080 static int fts3PendingListAppendVarint(
143081   PendingList **pp,               /* IN/OUT: Pointer to PendingList struct */
143082   sqlite3_int64 i                 /* Value to append to data */
143083 ){
143084   PendingList *p = *pp;
143085
143086   /* Allocate or grow the PendingList as required. */
143087   if( !p ){
143088     p = sqlite3_malloc(sizeof(*p) + 100);
143089     if( !p ){
143090       return SQLITE_NOMEM;
143091     }
143092     p->nSpace = 100;
143093     p->aData = (char *)&p[1];
143094     p->nData = 0;
143095   }
143096   else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
143097     int nNew = p->nSpace * 2;
143098     p = sqlite3_realloc(p, sizeof(*p) + nNew);
143099     if( !p ){
143100       sqlite3_free(*pp);
143101       *pp = 0;
143102       return SQLITE_NOMEM;
143103     }
143104     p->nSpace = nNew;
143105     p->aData = (char *)&p[1];
143106   }
143107
143108   /* Append the new serialized varint to the end of the list. */
143109   p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
143110   p->aData[p->nData] = '\0';
143111   *pp = p;
143112   return SQLITE_OK;
143113 }
143114
143115 /*
143116 ** Add a docid/column/position entry to a PendingList structure. Non-zero
143117 ** is returned if the structure is sqlite3_realloced as part of adding
143118 ** the entry. Otherwise, zero.
143119 **
143120 ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
143121 ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
143122 ** it is set to SQLITE_OK.
143123 */
143124 static int fts3PendingListAppend(
143125   PendingList **pp,               /* IN/OUT: PendingList structure */
143126   sqlite3_int64 iDocid,           /* Docid for entry to add */
143127   sqlite3_int64 iCol,             /* Column for entry to add */
143128   sqlite3_int64 iPos,             /* Position of term for entry to add */
143129   int *pRc                        /* OUT: Return code */
143130 ){
143131   PendingList *p = *pp;
143132   int rc = SQLITE_OK;
143133
143134   assert( !p || p->iLastDocid<=iDocid );
143135
143136   if( !p || p->iLastDocid!=iDocid ){
143137     sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
143138     if( p ){
143139       assert( p->nData<p->nSpace );
143140       assert( p->aData[p->nData]==0 );
143141       p->nData++;
143142     }
143143     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
143144       goto pendinglistappend_out;
143145     }
143146     p->iLastCol = -1;
143147     p->iLastPos = 0;
143148     p->iLastDocid = iDocid;
143149   }
143150   if( iCol>0 && p->iLastCol!=iCol ){
143151     if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
143152      || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
143153     ){
143154       goto pendinglistappend_out;
143155     }
143156     p->iLastCol = iCol;
143157     p->iLastPos = 0;
143158   }
143159   if( iCol>=0 ){
143160     assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
143161     rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
143162     if( rc==SQLITE_OK ){
143163       p->iLastPos = iPos;
143164     }
143165   }
143166
143167  pendinglistappend_out:
143168   *pRc = rc;
143169   if( p!=*pp ){
143170     *pp = p;
143171     return 1;
143172   }
143173   return 0;
143174 }
143175
143176 /*
143177 ** Free a PendingList object allocated by fts3PendingListAppend().
143178 */
143179 static void fts3PendingListDelete(PendingList *pList){
143180   sqlite3_free(pList);
143181 }
143182
143183 /*
143184 ** Add an entry to one of the pending-terms hash tables.
143185 */
143186 static int fts3PendingTermsAddOne(
143187   Fts3Table *p,
143188   int iCol,
143189   int iPos,
143190   Fts3Hash *pHash,                /* Pending terms hash table to add entry to */
143191   const char *zToken,
143192   int nToken
143193 ){
143194   PendingList *pList;
143195   int rc = SQLITE_OK;
143196
143197   pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
143198   if( pList ){
143199     p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
143200   }
143201   if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
143202     if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
143203       /* Malloc failed while inserting the new entry. This can only 
143204       ** happen if there was no previous entry for this token.
143205       */
143206       assert( 0==fts3HashFind(pHash, zToken, nToken) );
143207       sqlite3_free(pList);
143208       rc = SQLITE_NOMEM;
143209     }
143210   }
143211   if( rc==SQLITE_OK ){
143212     p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
143213   }
143214   return rc;
143215 }
143216
143217 /*
143218 ** Tokenize the nul-terminated string zText and add all tokens to the
143219 ** pending-terms hash-table. The docid used is that currently stored in
143220 ** p->iPrevDocid, and the column is specified by argument iCol.
143221 **
143222 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
143223 */
143224 static int fts3PendingTermsAdd(
143225   Fts3Table *p,                   /* Table into which text will be inserted */
143226   int iLangid,                    /* Language id to use */
143227   const char *zText,              /* Text of document to be inserted */
143228   int iCol,                       /* Column into which text is being inserted */
143229   u32 *pnWord                     /* IN/OUT: Incr. by number tokens inserted */
143230 ){
143231   int rc;
143232   int iStart = 0;
143233   int iEnd = 0;
143234   int iPos = 0;
143235   int nWord = 0;
143236
143237   char const *zToken;
143238   int nToken = 0;
143239
143240   sqlite3_tokenizer *pTokenizer = p->pTokenizer;
143241   sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
143242   sqlite3_tokenizer_cursor *pCsr;
143243   int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
143244       const char**,int*,int*,int*,int*);
143245
143246   assert( pTokenizer && pModule );
143247
143248   /* If the user has inserted a NULL value, this function may be called with
143249   ** zText==0. In this case, add zero token entries to the hash table and 
143250   ** return early. */
143251   if( zText==0 ){
143252     *pnWord = 0;
143253     return SQLITE_OK;
143254   }
143255
143256   rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
143257   if( rc!=SQLITE_OK ){
143258     return rc;
143259   }
143260
143261   xNext = pModule->xNext;
143262   while( SQLITE_OK==rc
143263       && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
143264   ){
143265     int i;
143266     if( iPos>=nWord ) nWord = iPos+1;
143267
143268     /* Positions cannot be negative; we use -1 as a terminator internally.
143269     ** Tokens must have a non-zero length.
143270     */
143271     if( iPos<0 || !zToken || nToken<=0 ){
143272       rc = SQLITE_ERROR;
143273       break;
143274     }
143275
143276     /* Add the term to the terms index */
143277     rc = fts3PendingTermsAddOne(
143278         p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
143279     );
143280     
143281     /* Add the term to each of the prefix indexes that it is not too 
143282     ** short for. */
143283     for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
143284       struct Fts3Index *pIndex = &p->aIndex[i];
143285       if( nToken<pIndex->nPrefix ) continue;
143286       rc = fts3PendingTermsAddOne(
143287           p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
143288       );
143289     }
143290   }
143291
143292   pModule->xClose(pCsr);
143293   *pnWord += nWord;
143294   return (rc==SQLITE_DONE ? SQLITE_OK : rc);
143295 }
143296
143297 /* 
143298 ** Calling this function indicates that subsequent calls to 
143299 ** fts3PendingTermsAdd() are to add term/position-list pairs for the
143300 ** contents of the document with docid iDocid.
143301 */
143302 static int fts3PendingTermsDocid(
143303   Fts3Table *p,                   /* Full-text table handle */
143304   int iLangid,                    /* Language id of row being written */
143305   sqlite_int64 iDocid             /* Docid of row being written */
143306 ){
143307   assert( iLangid>=0 );
143308
143309   /* TODO(shess) Explore whether partially flushing the buffer on
143310   ** forced-flush would provide better performance.  I suspect that if
143311   ** we ordered the doclists by size and flushed the largest until the
143312   ** buffer was half empty, that would let the less frequent terms
143313   ** generate longer doclists.
143314   */
143315   if( iDocid<=p->iPrevDocid 
143316    || p->iPrevLangid!=iLangid
143317    || p->nPendingData>p->nMaxPendingData 
143318   ){
143319     int rc = sqlite3Fts3PendingTermsFlush(p);
143320     if( rc!=SQLITE_OK ) return rc;
143321   }
143322   p->iPrevDocid = iDocid;
143323   p->iPrevLangid = iLangid;
143324   return SQLITE_OK;
143325 }
143326
143327 /*
143328 ** Discard the contents of the pending-terms hash tables. 
143329 */
143330 SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
143331   int i;
143332   for(i=0; i<p->nIndex; i++){
143333     Fts3HashElem *pElem;
143334     Fts3Hash *pHash = &p->aIndex[i].hPending;
143335     for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
143336       PendingList *pList = (PendingList *)fts3HashData(pElem);
143337       fts3PendingListDelete(pList);
143338     }
143339     fts3HashClear(pHash);
143340   }
143341   p->nPendingData = 0;
143342 }
143343
143344 /*
143345 ** This function is called by the xUpdate() method as part of an INSERT
143346 ** operation. It adds entries for each term in the new record to the
143347 ** pendingTerms hash table.
143348 **
143349 ** Argument apVal is the same as the similarly named argument passed to
143350 ** fts3InsertData(). Parameter iDocid is the docid of the new row.
143351 */
143352 static int fts3InsertTerms(
143353   Fts3Table *p, 
143354   int iLangid, 
143355   sqlite3_value **apVal, 
143356   u32 *aSz
143357 ){
143358   int i;                          /* Iterator variable */
143359   for(i=2; i<p->nColumn+2; i++){
143360     int iCol = i-2;
143361     if( p->abNotindexed[iCol]==0 ){
143362       const char *zText = (const char *)sqlite3_value_text(apVal[i]);
143363       int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
143364       if( rc!=SQLITE_OK ){
143365         return rc;
143366       }
143367       aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
143368     }
143369   }
143370   return SQLITE_OK;
143371 }
143372
143373 /*
143374 ** This function is called by the xUpdate() method for an INSERT operation.
143375 ** The apVal parameter is passed a copy of the apVal argument passed by
143376 ** SQLite to the xUpdate() method. i.e:
143377 **
143378 **   apVal[0]                Not used for INSERT.
143379 **   apVal[1]                rowid
143380 **   apVal[2]                Left-most user-defined column
143381 **   ...
143382 **   apVal[p->nColumn+1]     Right-most user-defined column
143383 **   apVal[p->nColumn+2]     Hidden column with same name as table
143384 **   apVal[p->nColumn+3]     Hidden "docid" column (alias for rowid)
143385 **   apVal[p->nColumn+4]     Hidden languageid column
143386 */
143387 static int fts3InsertData(
143388   Fts3Table *p,                   /* Full-text table */
143389   sqlite3_value **apVal,          /* Array of values to insert */
143390   sqlite3_int64 *piDocid          /* OUT: Docid for row just inserted */
143391 ){
143392   int rc;                         /* Return code */
143393   sqlite3_stmt *pContentInsert;   /* INSERT INTO %_content VALUES(...) */
143394
143395   if( p->zContentTbl ){
143396     sqlite3_value *pRowid = apVal[p->nColumn+3];
143397     if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
143398       pRowid = apVal[1];
143399     }
143400     if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
143401       return SQLITE_CONSTRAINT;
143402     }
143403     *piDocid = sqlite3_value_int64(pRowid);
143404     return SQLITE_OK;
143405   }
143406
143407   /* Locate the statement handle used to insert data into the %_content
143408   ** table. The SQL for this statement is:
143409   **
143410   **   INSERT INTO %_content VALUES(?, ?, ?, ...)
143411   **
143412   ** The statement features N '?' variables, where N is the number of user
143413   ** defined columns in the FTS3 table, plus one for the docid field.
143414   */
143415   rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
143416   if( rc==SQLITE_OK && p->zLanguageid ){
143417     rc = sqlite3_bind_int(
143418         pContentInsert, p->nColumn+2, 
143419         sqlite3_value_int(apVal[p->nColumn+4])
143420     );
143421   }
143422   if( rc!=SQLITE_OK ) return rc;
143423
143424   /* There is a quirk here. The users INSERT statement may have specified
143425   ** a value for the "rowid" field, for the "docid" field, or for both.
143426   ** Which is a problem, since "rowid" and "docid" are aliases for the
143427   ** same value. For example:
143428   **
143429   **   INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
143430   **
143431   ** In FTS3, this is an error. It is an error to specify non-NULL values
143432   ** for both docid and some other rowid alias.
143433   */
143434   if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
143435     if( SQLITE_NULL==sqlite3_value_type(apVal[0])
143436      && SQLITE_NULL!=sqlite3_value_type(apVal[1])
143437     ){
143438       /* A rowid/docid conflict. */
143439       return SQLITE_ERROR;
143440     }
143441     rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
143442     if( rc!=SQLITE_OK ) return rc;
143443   }
143444
143445   /* Execute the statement to insert the record. Set *piDocid to the 
143446   ** new docid value. 
143447   */
143448   sqlite3_step(pContentInsert);
143449   rc = sqlite3_reset(pContentInsert);
143450
143451   *piDocid = sqlite3_last_insert_rowid(p->db);
143452   return rc;
143453 }
143454
143455
143456
143457 /*
143458 ** Remove all data from the FTS3 table. Clear the hash table containing
143459 ** pending terms.
143460 */
143461 static int fts3DeleteAll(Fts3Table *p, int bContent){
143462   int rc = SQLITE_OK;             /* Return code */
143463
143464   /* Discard the contents of the pending-terms hash table. */
143465   sqlite3Fts3PendingTermsClear(p);
143466
143467   /* Delete everything from the shadow tables. Except, leave %_content as
143468   ** is if bContent is false.  */
143469   assert( p->zContentTbl==0 || bContent==0 );
143470   if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
143471   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
143472   fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
143473   if( p->bHasDocsize ){
143474     fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
143475   }
143476   if( p->bHasStat ){
143477     fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
143478   }
143479   return rc;
143480 }
143481
143482 /*
143483 **
143484 */
143485 static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
143486   int iLangid = 0;
143487   if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
143488   return iLangid;
143489 }
143490
143491 /*
143492 ** The first element in the apVal[] array is assumed to contain the docid
143493 ** (an integer) of a row about to be deleted. Remove all terms from the
143494 ** full-text index.
143495 */
143496 static void fts3DeleteTerms( 
143497   int *pRC,               /* Result code */
143498   Fts3Table *p,           /* The FTS table to delete from */
143499   sqlite3_value *pRowid,  /* The docid to be deleted */
143500   u32 *aSz,               /* Sizes of deleted document written here */
143501   int *pbFound            /* OUT: Set to true if row really does exist */
143502 ){
143503   int rc;
143504   sqlite3_stmt *pSelect;
143505
143506   assert( *pbFound==0 );
143507   if( *pRC ) return;
143508   rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
143509   if( rc==SQLITE_OK ){
143510     if( SQLITE_ROW==sqlite3_step(pSelect) ){
143511       int i;
143512       int iLangid = langidFromSelect(p, pSelect);
143513       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
143514       for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
143515         int iCol = i-1;
143516         if( p->abNotindexed[iCol]==0 ){
143517           const char *zText = (const char *)sqlite3_column_text(pSelect, i);
143518           rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
143519           aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
143520         }
143521       }
143522       if( rc!=SQLITE_OK ){
143523         sqlite3_reset(pSelect);
143524         *pRC = rc;
143525         return;
143526       }
143527       *pbFound = 1;
143528     }
143529     rc = sqlite3_reset(pSelect);
143530   }else{
143531     sqlite3_reset(pSelect);
143532   }
143533   *pRC = rc;
143534 }
143535
143536 /*
143537 ** Forward declaration to account for the circular dependency between
143538 ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
143539 */
143540 static int fts3SegmentMerge(Fts3Table *, int, int, int);
143541
143542 /* 
143543 ** This function allocates a new level iLevel index in the segdir table.
143544 ** Usually, indexes are allocated within a level sequentially starting
143545 ** with 0, so the allocated index is one greater than the value returned
143546 ** by:
143547 **
143548 **   SELECT max(idx) FROM %_segdir WHERE level = :iLevel
143549 **
143550 ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
143551 ** level, they are merged into a single level (iLevel+1) segment and the 
143552 ** allocated index is 0.
143553 **
143554 ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
143555 ** returned. Otherwise, an SQLite error code is returned.
143556 */
143557 static int fts3AllocateSegdirIdx(
143558   Fts3Table *p, 
143559   int iLangid,                    /* Language id */
143560   int iIndex,                     /* Index for p->aIndex */
143561   int iLevel, 
143562   int *piIdx
143563 ){
143564   int rc;                         /* Return Code */
143565   sqlite3_stmt *pNextIdx;         /* Query for next idx at level iLevel */
143566   int iNext = 0;                  /* Result of query pNextIdx */
143567
143568   assert( iLangid>=0 );
143569   assert( p->nIndex>=1 );
143570
143571   /* Set variable iNext to the next available segdir index at level iLevel. */
143572   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
143573   if( rc==SQLITE_OK ){
143574     sqlite3_bind_int64(
143575         pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
143576     );
143577     if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
143578       iNext = sqlite3_column_int(pNextIdx, 0);
143579     }
143580     rc = sqlite3_reset(pNextIdx);
143581   }
143582
143583   if( rc==SQLITE_OK ){
143584     /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
143585     ** full, merge all segments in level iLevel into a single iLevel+1
143586     ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
143587     ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
143588     */
143589     if( iNext>=FTS3_MERGE_COUNT ){
143590       fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
143591       rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
143592       *piIdx = 0;
143593     }else{
143594       *piIdx = iNext;
143595     }
143596   }
143597
143598   return rc;
143599 }
143600
143601 /*
143602 ** The %_segments table is declared as follows:
143603 **
143604 **   CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
143605 **
143606 ** This function reads data from a single row of the %_segments table. The
143607 ** specific row is identified by the iBlockid parameter. If paBlob is not
143608 ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
143609 ** with the contents of the blob stored in the "block" column of the 
143610 ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
143611 ** to the size of the blob in bytes before returning.
143612 **
143613 ** If an error occurs, or the table does not contain the specified row,
143614 ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
143615 ** paBlob is non-NULL, then it is the responsibility of the caller to
143616 ** eventually free the returned buffer.
143617 **
143618 ** This function may leave an open sqlite3_blob* handle in the
143619 ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
143620 ** to this function. The handle may be closed by calling the
143621 ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
143622 ** performance improvement, but the blob handle should always be closed
143623 ** before control is returned to the user (to prevent a lock being held
143624 ** on the database file for longer than necessary). Thus, any virtual table
143625 ** method (xFilter etc.) that may directly or indirectly call this function
143626 ** must call sqlite3Fts3SegmentsClose() before returning.
143627 */
143628 SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
143629   Fts3Table *p,                   /* FTS3 table handle */
143630   sqlite3_int64 iBlockid,         /* Access the row with blockid=$iBlockid */
143631   char **paBlob,                  /* OUT: Blob data in malloc'd buffer */
143632   int *pnBlob,                    /* OUT: Size of blob data */
143633   int *pnLoad                     /* OUT: Bytes actually loaded */
143634 ){
143635   int rc;                         /* Return code */
143636
143637   /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
143638   assert( pnBlob );
143639
143640   if( p->pSegments ){
143641     rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
143642   }else{
143643     if( 0==p->zSegmentsTbl ){
143644       p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
143645       if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
143646     }
143647     rc = sqlite3_blob_open(
143648        p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
143649     );
143650   }
143651
143652   if( rc==SQLITE_OK ){
143653     int nByte = sqlite3_blob_bytes(p->pSegments);
143654     *pnBlob = nByte;
143655     if( paBlob ){
143656       char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
143657       if( !aByte ){
143658         rc = SQLITE_NOMEM;
143659       }else{
143660         if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
143661           nByte = FTS3_NODE_CHUNKSIZE;
143662           *pnLoad = nByte;
143663         }
143664         rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
143665         memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
143666         if( rc!=SQLITE_OK ){
143667           sqlite3_free(aByte);
143668           aByte = 0;
143669         }
143670       }
143671       *paBlob = aByte;
143672     }
143673   }
143674
143675   return rc;
143676 }
143677
143678 /*
143679 ** Close the blob handle at p->pSegments, if it is open. See comments above
143680 ** the sqlite3Fts3ReadBlock() function for details.
143681 */
143682 SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
143683   sqlite3_blob_close(p->pSegments);
143684   p->pSegments = 0;
143685 }
143686     
143687 static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
143688   int nRead;                      /* Number of bytes to read */
143689   int rc;                         /* Return code */
143690
143691   nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
143692   rc = sqlite3_blob_read(
143693       pReader->pBlob, 
143694       &pReader->aNode[pReader->nPopulate],
143695       nRead,
143696       pReader->nPopulate
143697   );
143698
143699   if( rc==SQLITE_OK ){
143700     pReader->nPopulate += nRead;
143701     memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
143702     if( pReader->nPopulate==pReader->nNode ){
143703       sqlite3_blob_close(pReader->pBlob);
143704       pReader->pBlob = 0;
143705       pReader->nPopulate = 0;
143706     }
143707   }
143708   return rc;
143709 }
143710
143711 static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
143712   int rc = SQLITE_OK;
143713   assert( !pReader->pBlob 
143714        || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
143715   );
143716   while( pReader->pBlob && rc==SQLITE_OK 
143717      &&  (pFrom - pReader->aNode + nByte)>pReader->nPopulate
143718   ){
143719     rc = fts3SegReaderIncrRead(pReader);
143720   }
143721   return rc;
143722 }
143723
143724 /*
143725 ** Set an Fts3SegReader cursor to point at EOF.
143726 */
143727 static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
143728   if( !fts3SegReaderIsRootOnly(pSeg) ){
143729     sqlite3_free(pSeg->aNode);
143730     sqlite3_blob_close(pSeg->pBlob);
143731     pSeg->pBlob = 0;
143732   }
143733   pSeg->aNode = 0;
143734 }
143735
143736 /*
143737 ** Move the iterator passed as the first argument to the next term in the
143738 ** segment. If successful, SQLITE_OK is returned. If there is no next term,
143739 ** SQLITE_DONE. Otherwise, an SQLite error code.
143740 */
143741 static int fts3SegReaderNext(
143742   Fts3Table *p, 
143743   Fts3SegReader *pReader,
143744   int bIncr
143745 ){
143746   int rc;                         /* Return code of various sub-routines */
143747   char *pNext;                    /* Cursor variable */
143748   int nPrefix;                    /* Number of bytes in term prefix */
143749   int nSuffix;                    /* Number of bytes in term suffix */
143750
143751   if( !pReader->aDoclist ){
143752     pNext = pReader->aNode;
143753   }else{
143754     pNext = &pReader->aDoclist[pReader->nDoclist];
143755   }
143756
143757   if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
143758
143759     if( fts3SegReaderIsPending(pReader) ){
143760       Fts3HashElem *pElem = *(pReader->ppNextElem);
143761       if( pElem==0 ){
143762         pReader->aNode = 0;
143763       }else{
143764         PendingList *pList = (PendingList *)fts3HashData(pElem);
143765         pReader->zTerm = (char *)fts3HashKey(pElem);
143766         pReader->nTerm = fts3HashKeysize(pElem);
143767         pReader->nNode = pReader->nDoclist = pList->nData + 1;
143768         pReader->aNode = pReader->aDoclist = pList->aData;
143769         pReader->ppNextElem++;
143770         assert( pReader->aNode );
143771       }
143772       return SQLITE_OK;
143773     }
143774
143775     fts3SegReaderSetEof(pReader);
143776
143777     /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf 
143778     ** blocks have already been traversed.  */
143779     assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
143780     if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
143781       return SQLITE_OK;
143782     }
143783
143784     rc = sqlite3Fts3ReadBlock(
143785         p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode, 
143786         (bIncr ? &pReader->nPopulate : 0)
143787     );
143788     if( rc!=SQLITE_OK ) return rc;
143789     assert( pReader->pBlob==0 );
143790     if( bIncr && pReader->nPopulate<pReader->nNode ){
143791       pReader->pBlob = p->pSegments;
143792       p->pSegments = 0;
143793     }
143794     pNext = pReader->aNode;
143795   }
143796
143797   assert( !fts3SegReaderIsPending(pReader) );
143798
143799   rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
143800   if( rc!=SQLITE_OK ) return rc;
143801   
143802   /* Because of the FTS3_NODE_PADDING bytes of padding, the following is 
143803   ** safe (no risk of overread) even if the node data is corrupted. */
143804   pNext += fts3GetVarint32(pNext, &nPrefix);
143805   pNext += fts3GetVarint32(pNext, &nSuffix);
143806   if( nPrefix<0 || nSuffix<=0 
143807    || &pNext[nSuffix]>&pReader->aNode[pReader->nNode] 
143808   ){
143809     return FTS_CORRUPT_VTAB;
143810   }
143811
143812   if( nPrefix+nSuffix>pReader->nTermAlloc ){
143813     int nNew = (nPrefix+nSuffix)*2;
143814     char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
143815     if( !zNew ){
143816       return SQLITE_NOMEM;
143817     }
143818     pReader->zTerm = zNew;
143819     pReader->nTermAlloc = nNew;
143820   }
143821
143822   rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
143823   if( rc!=SQLITE_OK ) return rc;
143824
143825   memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
143826   pReader->nTerm = nPrefix+nSuffix;
143827   pNext += nSuffix;
143828   pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
143829   pReader->aDoclist = pNext;
143830   pReader->pOffsetList = 0;
143831
143832   /* Check that the doclist does not appear to extend past the end of the
143833   ** b-tree node. And that the final byte of the doclist is 0x00. If either 
143834   ** of these statements is untrue, then the data structure is corrupt.
143835   */
143836   if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode] 
143837    || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
143838   ){
143839     return FTS_CORRUPT_VTAB;
143840   }
143841   return SQLITE_OK;
143842 }
143843
143844 /*
143845 ** Set the SegReader to point to the first docid in the doclist associated
143846 ** with the current term.
143847 */
143848 static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
143849   int rc = SQLITE_OK;
143850   assert( pReader->aDoclist );
143851   assert( !pReader->pOffsetList );
143852   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
143853     u8 bEof = 0;
143854     pReader->iDocid = 0;
143855     pReader->nOffsetList = 0;
143856     sqlite3Fts3DoclistPrev(0,
143857         pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList, 
143858         &pReader->iDocid, &pReader->nOffsetList, &bEof
143859     );
143860   }else{
143861     rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
143862     if( rc==SQLITE_OK ){
143863       int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
143864       pReader->pOffsetList = &pReader->aDoclist[n];
143865     }
143866   }
143867   return rc;
143868 }
143869
143870 /*
143871 ** Advance the SegReader to point to the next docid in the doclist
143872 ** associated with the current term.
143873 ** 
143874 ** If arguments ppOffsetList and pnOffsetList are not NULL, then 
143875 ** *ppOffsetList is set to point to the first column-offset list
143876 ** in the doclist entry (i.e. immediately past the docid varint).
143877 ** *pnOffsetList is set to the length of the set of column-offset
143878 ** lists, not including the nul-terminator byte. For example:
143879 */
143880 static int fts3SegReaderNextDocid(
143881   Fts3Table *pTab,
143882   Fts3SegReader *pReader,         /* Reader to advance to next docid */
143883   char **ppOffsetList,            /* OUT: Pointer to current position-list */
143884   int *pnOffsetList               /* OUT: Length of *ppOffsetList in bytes */
143885 ){
143886   int rc = SQLITE_OK;
143887   char *p = pReader->pOffsetList;
143888   char c = 0;
143889
143890   assert( p );
143891
143892   if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
143893     /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
143894     ** Pending-terms doclists are always built up in ascending order, so
143895     ** we have to iterate through them backwards here. */
143896     u8 bEof = 0;
143897     if( ppOffsetList ){
143898       *ppOffsetList = pReader->pOffsetList;
143899       *pnOffsetList = pReader->nOffsetList - 1;
143900     }
143901     sqlite3Fts3DoclistPrev(0,
143902         pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
143903         &pReader->nOffsetList, &bEof
143904     );
143905     if( bEof ){
143906       pReader->pOffsetList = 0;
143907     }else{
143908       pReader->pOffsetList = p;
143909     }
143910   }else{
143911     char *pEnd = &pReader->aDoclist[pReader->nDoclist];
143912
143913     /* Pointer p currently points at the first byte of an offset list. The
143914     ** following block advances it to point one byte past the end of
143915     ** the same offset list. */
143916     while( 1 ){
143917   
143918       /* The following line of code (and the "p++" below the while() loop) is
143919       ** normally all that is required to move pointer p to the desired 
143920       ** position. The exception is if this node is being loaded from disk
143921       ** incrementally and pointer "p" now points to the first byte past
143922       ** the populated part of pReader->aNode[].
143923       */
143924       while( *p | c ) c = *p++ & 0x80;
143925       assert( *p==0 );
143926   
143927       if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
143928       rc = fts3SegReaderIncrRead(pReader);
143929       if( rc!=SQLITE_OK ) return rc;
143930     }
143931     p++;
143932   
143933     /* If required, populate the output variables with a pointer to and the
143934     ** size of the previous offset-list.
143935     */
143936     if( ppOffsetList ){
143937       *ppOffsetList = pReader->pOffsetList;
143938       *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
143939     }
143940
143941     /* List may have been edited in place by fts3EvalNearTrim() */
143942     while( p<pEnd && *p==0 ) p++;
143943   
143944     /* If there are no more entries in the doclist, set pOffsetList to
143945     ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
143946     ** Fts3SegReader.pOffsetList to point to the next offset list before
143947     ** returning.
143948     */
143949     if( p>=pEnd ){
143950       pReader->pOffsetList = 0;
143951     }else{
143952       rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
143953       if( rc==SQLITE_OK ){
143954         sqlite3_int64 iDelta;
143955         pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
143956         if( pTab->bDescIdx ){
143957           pReader->iDocid -= iDelta;
143958         }else{
143959           pReader->iDocid += iDelta;
143960         }
143961       }
143962     }
143963   }
143964
143965   return SQLITE_OK;
143966 }
143967
143968
143969 SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
143970   Fts3Cursor *pCsr, 
143971   Fts3MultiSegReader *pMsr,
143972   int *pnOvfl
143973 ){
143974   Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
143975   int nOvfl = 0;
143976   int ii;
143977   int rc = SQLITE_OK;
143978   int pgsz = p->nPgsz;
143979
143980   assert( p->bFts4 );
143981   assert( pgsz>0 );
143982
143983   for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
143984     Fts3SegReader *pReader = pMsr->apSegment[ii];
143985     if( !fts3SegReaderIsPending(pReader) 
143986      && !fts3SegReaderIsRootOnly(pReader) 
143987     ){
143988       sqlite3_int64 jj;
143989       for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
143990         int nBlob;
143991         rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
143992         if( rc!=SQLITE_OK ) break;
143993         if( (nBlob+35)>pgsz ){
143994           nOvfl += (nBlob + 34)/pgsz;
143995         }
143996       }
143997     }
143998   }
143999   *pnOvfl = nOvfl;
144000   return rc;
144001 }
144002
144003 /*
144004 ** Free all allocations associated with the iterator passed as the 
144005 ** second argument.
144006 */
144007 SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
144008   if( pReader && !fts3SegReaderIsPending(pReader) ){
144009     sqlite3_free(pReader->zTerm);
144010     if( !fts3SegReaderIsRootOnly(pReader) ){
144011       sqlite3_free(pReader->aNode);
144012       sqlite3_blob_close(pReader->pBlob);
144013     }
144014   }
144015   sqlite3_free(pReader);
144016 }
144017
144018 /*
144019 ** Allocate a new SegReader object.
144020 */
144021 SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
144022   int iAge,                       /* Segment "age". */
144023   int bLookup,                    /* True for a lookup only */
144024   sqlite3_int64 iStartLeaf,       /* First leaf to traverse */
144025   sqlite3_int64 iEndLeaf,         /* Final leaf to traverse */
144026   sqlite3_int64 iEndBlock,        /* Final block of segment */
144027   const char *zRoot,              /* Buffer containing root node */
144028   int nRoot,                      /* Size of buffer containing root node */
144029   Fts3SegReader **ppReader        /* OUT: Allocated Fts3SegReader */
144030 ){
144031   Fts3SegReader *pReader;         /* Newly allocated SegReader object */
144032   int nExtra = 0;                 /* Bytes to allocate segment root node */
144033
144034   assert( iStartLeaf<=iEndLeaf );
144035   if( iStartLeaf==0 ){
144036     nExtra = nRoot + FTS3_NODE_PADDING;
144037   }
144038
144039   pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
144040   if( !pReader ){
144041     return SQLITE_NOMEM;
144042   }
144043   memset(pReader, 0, sizeof(Fts3SegReader));
144044   pReader->iIdx = iAge;
144045   pReader->bLookup = bLookup!=0;
144046   pReader->iStartBlock = iStartLeaf;
144047   pReader->iLeafEndBlock = iEndLeaf;
144048   pReader->iEndBlock = iEndBlock;
144049
144050   if( nExtra ){
144051     /* The entire segment is stored in the root node. */
144052     pReader->aNode = (char *)&pReader[1];
144053     pReader->rootOnly = 1;
144054     pReader->nNode = nRoot;
144055     memcpy(pReader->aNode, zRoot, nRoot);
144056     memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
144057   }else{
144058     pReader->iCurrentBlock = iStartLeaf-1;
144059   }
144060   *ppReader = pReader;
144061   return SQLITE_OK;
144062 }
144063
144064 /*
144065 ** This is a comparison function used as a qsort() callback when sorting
144066 ** an array of pending terms by term. This occurs as part of flushing
144067 ** the contents of the pending-terms hash table to the database.
144068 */
144069 static int SQLITE_CDECL fts3CompareElemByTerm(
144070   const void *lhs,
144071   const void *rhs
144072 ){
144073   char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
144074   char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
144075   int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
144076   int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
144077
144078   int n = (n1<n2 ? n1 : n2);
144079   int c = memcmp(z1, z2, n);
144080   if( c==0 ){
144081     c = n1 - n2;
144082   }
144083   return c;
144084 }
144085
144086 /*
144087 ** This function is used to allocate an Fts3SegReader that iterates through
144088 ** a subset of the terms stored in the Fts3Table.pendingTerms array.
144089 **
144090 ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
144091 ** through each term in the pending-terms table. Or, if isPrefixIter is
144092 ** non-zero, it iterates through each term and its prefixes. For example, if
144093 ** the pending terms hash table contains the terms "sqlite", "mysql" and
144094 ** "firebird", then the iterator visits the following 'terms' (in the order
144095 ** shown):
144096 **
144097 **   f fi fir fire fireb firebi firebir firebird
144098 **   m my mys mysq mysql
144099 **   s sq sql sqli sqlit sqlite
144100 **
144101 ** Whereas if isPrefixIter is zero, the terms visited are:
144102 **
144103 **   firebird mysql sqlite
144104 */
144105 SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
144106   Fts3Table *p,                   /* Virtual table handle */
144107   int iIndex,                     /* Index for p->aIndex */
144108   const char *zTerm,              /* Term to search for */
144109   int nTerm,                      /* Size of buffer zTerm */
144110   int bPrefix,                    /* True for a prefix iterator */
144111   Fts3SegReader **ppReader        /* OUT: SegReader for pending-terms */
144112 ){
144113   Fts3SegReader *pReader = 0;     /* Fts3SegReader object to return */
144114   Fts3HashElem *pE;               /* Iterator variable */
144115   Fts3HashElem **aElem = 0;       /* Array of term hash entries to scan */
144116   int nElem = 0;                  /* Size of array at aElem */
144117   int rc = SQLITE_OK;             /* Return Code */
144118   Fts3Hash *pHash;
144119
144120   pHash = &p->aIndex[iIndex].hPending;
144121   if( bPrefix ){
144122     int nAlloc = 0;               /* Size of allocated array at aElem */
144123
144124     for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
144125       char *zKey = (char *)fts3HashKey(pE);
144126       int nKey = fts3HashKeysize(pE);
144127       if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
144128         if( nElem==nAlloc ){
144129           Fts3HashElem **aElem2;
144130           nAlloc += 16;
144131           aElem2 = (Fts3HashElem **)sqlite3_realloc(
144132               aElem, nAlloc*sizeof(Fts3HashElem *)
144133           );
144134           if( !aElem2 ){
144135             rc = SQLITE_NOMEM;
144136             nElem = 0;
144137             break;
144138           }
144139           aElem = aElem2;
144140         }
144141
144142         aElem[nElem++] = pE;
144143       }
144144     }
144145
144146     /* If more than one term matches the prefix, sort the Fts3HashElem
144147     ** objects in term order using qsort(). This uses the same comparison
144148     ** callback as is used when flushing terms to disk.
144149     */
144150     if( nElem>1 ){
144151       qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
144152     }
144153
144154   }else{
144155     /* The query is a simple term lookup that matches at most one term in
144156     ** the index. All that is required is a straight hash-lookup. 
144157     **
144158     ** Because the stack address of pE may be accessed via the aElem pointer
144159     ** below, the "Fts3HashElem *pE" must be declared so that it is valid
144160     ** within this entire function, not just this "else{...}" block.
144161     */
144162     pE = fts3HashFindElem(pHash, zTerm, nTerm);
144163     if( pE ){
144164       aElem = &pE;
144165       nElem = 1;
144166     }
144167   }
144168
144169   if( nElem>0 ){
144170     int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
144171     pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
144172     if( !pReader ){
144173       rc = SQLITE_NOMEM;
144174     }else{
144175       memset(pReader, 0, nByte);
144176       pReader->iIdx = 0x7FFFFFFF;
144177       pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
144178       memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
144179     }
144180   }
144181
144182   if( bPrefix ){
144183     sqlite3_free(aElem);
144184   }
144185   *ppReader = pReader;
144186   return rc;
144187 }
144188
144189 /*
144190 ** Compare the entries pointed to by two Fts3SegReader structures. 
144191 ** Comparison is as follows:
144192 **
144193 **   1) EOF is greater than not EOF.
144194 **
144195 **   2) The current terms (if any) are compared using memcmp(). If one
144196 **      term is a prefix of another, the longer term is considered the
144197 **      larger.
144198 **
144199 **   3) By segment age. An older segment is considered larger.
144200 */
144201 static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
144202   int rc;
144203   if( pLhs->aNode && pRhs->aNode ){
144204     int rc2 = pLhs->nTerm - pRhs->nTerm;
144205     if( rc2<0 ){
144206       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
144207     }else{
144208       rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
144209     }
144210     if( rc==0 ){
144211       rc = rc2;
144212     }
144213   }else{
144214     rc = (pLhs->aNode==0) - (pRhs->aNode==0);
144215   }
144216   if( rc==0 ){
144217     rc = pRhs->iIdx - pLhs->iIdx;
144218   }
144219   assert( rc!=0 );
144220   return rc;
144221 }
144222
144223 /*
144224 ** A different comparison function for SegReader structures. In this
144225 ** version, it is assumed that each SegReader points to an entry in
144226 ** a doclist for identical terms. Comparison is made as follows:
144227 **
144228 **   1) EOF (end of doclist in this case) is greater than not EOF.
144229 **
144230 **   2) By current docid.
144231 **
144232 **   3) By segment age. An older segment is considered larger.
144233 */
144234 static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
144235   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
144236   if( rc==0 ){
144237     if( pLhs->iDocid==pRhs->iDocid ){
144238       rc = pRhs->iIdx - pLhs->iIdx;
144239     }else{
144240       rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
144241     }
144242   }
144243   assert( pLhs->aNode && pRhs->aNode );
144244   return rc;
144245 }
144246 static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
144247   int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
144248   if( rc==0 ){
144249     if( pLhs->iDocid==pRhs->iDocid ){
144250       rc = pRhs->iIdx - pLhs->iIdx;
144251     }else{
144252       rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
144253     }
144254   }
144255   assert( pLhs->aNode && pRhs->aNode );
144256   return rc;
144257 }
144258
144259 /*
144260 ** Compare the term that the Fts3SegReader object passed as the first argument
144261 ** points to with the term specified by arguments zTerm and nTerm. 
144262 **
144263 ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
144264 ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
144265 ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
144266 */
144267 static int fts3SegReaderTermCmp(
144268   Fts3SegReader *pSeg,            /* Segment reader object */
144269   const char *zTerm,              /* Term to compare to */
144270   int nTerm                       /* Size of term zTerm in bytes */
144271 ){
144272   int res = 0;
144273   if( pSeg->aNode ){
144274     if( pSeg->nTerm>nTerm ){
144275       res = memcmp(pSeg->zTerm, zTerm, nTerm);
144276     }else{
144277       res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
144278     }
144279     if( res==0 ){
144280       res = pSeg->nTerm-nTerm;
144281     }
144282   }
144283   return res;
144284 }
144285
144286 /*
144287 ** Argument apSegment is an array of nSegment elements. It is known that
144288 ** the final (nSegment-nSuspect) members are already in sorted order
144289 ** (according to the comparison function provided). This function shuffles
144290 ** the array around until all entries are in sorted order.
144291 */
144292 static void fts3SegReaderSort(
144293   Fts3SegReader **apSegment,                     /* Array to sort entries of */
144294   int nSegment,                                  /* Size of apSegment array */
144295   int nSuspect,                                  /* Unsorted entry count */
144296   int (*xCmp)(Fts3SegReader *, Fts3SegReader *)  /* Comparison function */
144297 ){
144298   int i;                          /* Iterator variable */
144299
144300   assert( nSuspect<=nSegment );
144301
144302   if( nSuspect==nSegment ) nSuspect--;
144303   for(i=nSuspect-1; i>=0; i--){
144304     int j;
144305     for(j=i; j<(nSegment-1); j++){
144306       Fts3SegReader *pTmp;
144307       if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
144308       pTmp = apSegment[j+1];
144309       apSegment[j+1] = apSegment[j];
144310       apSegment[j] = pTmp;
144311     }
144312   }
144313
144314 #ifndef NDEBUG
144315   /* Check that the list really is sorted now. */
144316   for(i=0; i<(nSuspect-1); i++){
144317     assert( xCmp(apSegment[i], apSegment[i+1])<0 );
144318   }
144319 #endif
144320 }
144321
144322 /* 
144323 ** Insert a record into the %_segments table.
144324 */
144325 static int fts3WriteSegment(
144326   Fts3Table *p,                   /* Virtual table handle */
144327   sqlite3_int64 iBlock,           /* Block id for new block */
144328   char *z,                        /* Pointer to buffer containing block data */
144329   int n                           /* Size of buffer z in bytes */
144330 ){
144331   sqlite3_stmt *pStmt;
144332   int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
144333   if( rc==SQLITE_OK ){
144334     sqlite3_bind_int64(pStmt, 1, iBlock);
144335     sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
144336     sqlite3_step(pStmt);
144337     rc = sqlite3_reset(pStmt);
144338   }
144339   return rc;
144340 }
144341
144342 /*
144343 ** Find the largest relative level number in the table. If successful, set
144344 ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
144345 ** set *pnMax to zero and return an SQLite error code.
144346 */
144347 SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
144348   int rc;
144349   int mxLevel = 0;
144350   sqlite3_stmt *pStmt = 0;
144351
144352   rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
144353   if( rc==SQLITE_OK ){
144354     if( SQLITE_ROW==sqlite3_step(pStmt) ){
144355       mxLevel = sqlite3_column_int(pStmt, 0);
144356     }
144357     rc = sqlite3_reset(pStmt);
144358   }
144359   *pnMax = mxLevel;
144360   return rc;
144361 }
144362
144363 /* 
144364 ** Insert a record into the %_segdir table.
144365 */
144366 static int fts3WriteSegdir(
144367   Fts3Table *p,                   /* Virtual table handle */
144368   sqlite3_int64 iLevel,           /* Value for "level" field (absolute level) */
144369   int iIdx,                       /* Value for "idx" field */
144370   sqlite3_int64 iStartBlock,      /* Value for "start_block" field */
144371   sqlite3_int64 iLeafEndBlock,    /* Value for "leaves_end_block" field */
144372   sqlite3_int64 iEndBlock,        /* Value for "end_block" field */
144373   sqlite3_int64 nLeafData,        /* Bytes of leaf data in segment */
144374   char *zRoot,                    /* Blob value for "root" field */
144375   int nRoot                       /* Number of bytes in buffer zRoot */
144376 ){
144377   sqlite3_stmt *pStmt;
144378   int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
144379   if( rc==SQLITE_OK ){
144380     sqlite3_bind_int64(pStmt, 1, iLevel);
144381     sqlite3_bind_int(pStmt, 2, iIdx);
144382     sqlite3_bind_int64(pStmt, 3, iStartBlock);
144383     sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
144384     if( nLeafData==0 ){
144385       sqlite3_bind_int64(pStmt, 5, iEndBlock);
144386     }else{
144387       char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
144388       if( !zEnd ) return SQLITE_NOMEM;
144389       sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
144390     }
144391     sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
144392     sqlite3_step(pStmt);
144393     rc = sqlite3_reset(pStmt);
144394   }
144395   return rc;
144396 }
144397
144398 /*
144399 ** Return the size of the common prefix (if any) shared by zPrev and
144400 ** zNext, in bytes. For example, 
144401 **
144402 **   fts3PrefixCompress("abc", 3, "abcdef", 6)   // returns 3
144403 **   fts3PrefixCompress("abX", 3, "abcdef", 6)   // returns 2
144404 **   fts3PrefixCompress("abX", 3, "Xbcdef", 6)   // returns 0
144405 */
144406 static int fts3PrefixCompress(
144407   const char *zPrev,              /* Buffer containing previous term */
144408   int nPrev,                      /* Size of buffer zPrev in bytes */
144409   const char *zNext,              /* Buffer containing next term */
144410   int nNext                       /* Size of buffer zNext in bytes */
144411 ){
144412   int n;
144413   UNUSED_PARAMETER(nNext);
144414   for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
144415   return n;
144416 }
144417
144418 /*
144419 ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
144420 ** (according to memcmp) than the previous term.
144421 */
144422 static int fts3NodeAddTerm(
144423   Fts3Table *p,                   /* Virtual table handle */
144424   SegmentNode **ppTree,           /* IN/OUT: SegmentNode handle */ 
144425   int isCopyTerm,                 /* True if zTerm/nTerm is transient */
144426   const char *zTerm,              /* Pointer to buffer containing term */
144427   int nTerm                       /* Size of term in bytes */
144428 ){
144429   SegmentNode *pTree = *ppTree;
144430   int rc;
144431   SegmentNode *pNew;
144432
144433   /* First try to append the term to the current node. Return early if 
144434   ** this is possible.
144435   */
144436   if( pTree ){
144437     int nData = pTree->nData;     /* Current size of node in bytes */
144438     int nReq = nData;             /* Required space after adding zTerm */
144439     int nPrefix;                  /* Number of bytes of prefix compression */
144440     int nSuffix;                  /* Suffix length */
144441
144442     nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
144443     nSuffix = nTerm-nPrefix;
144444
144445     nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
144446     if( nReq<=p->nNodeSize || !pTree->zTerm ){
144447
144448       if( nReq>p->nNodeSize ){
144449         /* An unusual case: this is the first term to be added to the node
144450         ** and the static node buffer (p->nNodeSize bytes) is not large
144451         ** enough. Use a separately malloced buffer instead This wastes
144452         ** p->nNodeSize bytes, but since this scenario only comes about when
144453         ** the database contain two terms that share a prefix of almost 2KB, 
144454         ** this is not expected to be a serious problem. 
144455         */
144456         assert( pTree->aData==(char *)&pTree[1] );
144457         pTree->aData = (char *)sqlite3_malloc(nReq);
144458         if( !pTree->aData ){
144459           return SQLITE_NOMEM;
144460         }
144461       }
144462
144463       if( pTree->zTerm ){
144464         /* There is no prefix-length field for first term in a node */
144465         nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
144466       }
144467
144468       nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
144469       memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
144470       pTree->nData = nData + nSuffix;
144471       pTree->nEntry++;
144472
144473       if( isCopyTerm ){
144474         if( pTree->nMalloc<nTerm ){
144475           char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
144476           if( !zNew ){
144477             return SQLITE_NOMEM;
144478           }
144479           pTree->nMalloc = nTerm*2;
144480           pTree->zMalloc = zNew;
144481         }
144482         pTree->zTerm = pTree->zMalloc;
144483         memcpy(pTree->zTerm, zTerm, nTerm);
144484         pTree->nTerm = nTerm;
144485       }else{
144486         pTree->zTerm = (char *)zTerm;
144487         pTree->nTerm = nTerm;
144488       }
144489       return SQLITE_OK;
144490     }
144491   }
144492
144493   /* If control flows to here, it was not possible to append zTerm to the
144494   ** current node. Create a new node (a right-sibling of the current node).
144495   ** If this is the first node in the tree, the term is added to it.
144496   **
144497   ** Otherwise, the term is not added to the new node, it is left empty for
144498   ** now. Instead, the term is inserted into the parent of pTree. If pTree 
144499   ** has no parent, one is created here.
144500   */
144501   pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
144502   if( !pNew ){
144503     return SQLITE_NOMEM;
144504   }
144505   memset(pNew, 0, sizeof(SegmentNode));
144506   pNew->nData = 1 + FTS3_VARINT_MAX;
144507   pNew->aData = (char *)&pNew[1];
144508
144509   if( pTree ){
144510     SegmentNode *pParent = pTree->pParent;
144511     rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
144512     if( pTree->pParent==0 ){
144513       pTree->pParent = pParent;
144514     }
144515     pTree->pRight = pNew;
144516     pNew->pLeftmost = pTree->pLeftmost;
144517     pNew->pParent = pParent;
144518     pNew->zMalloc = pTree->zMalloc;
144519     pNew->nMalloc = pTree->nMalloc;
144520     pTree->zMalloc = 0;
144521   }else{
144522     pNew->pLeftmost = pNew;
144523     rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm); 
144524   }
144525
144526   *ppTree = pNew;
144527   return rc;
144528 }
144529
144530 /*
144531 ** Helper function for fts3NodeWrite().
144532 */
144533 static int fts3TreeFinishNode(
144534   SegmentNode *pTree, 
144535   int iHeight, 
144536   sqlite3_int64 iLeftChild
144537 ){
144538   int nStart;
144539   assert( iHeight>=1 && iHeight<128 );
144540   nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
144541   pTree->aData[nStart] = (char)iHeight;
144542   sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
144543   return nStart;
144544 }
144545
144546 /*
144547 ** Write the buffer for the segment node pTree and all of its peers to the
144548 ** database. Then call this function recursively to write the parent of 
144549 ** pTree and its peers to the database. 
144550 **
144551 ** Except, if pTree is a root node, do not write it to the database. Instead,
144552 ** set output variables *paRoot and *pnRoot to contain the root node.
144553 **
144554 ** If successful, SQLITE_OK is returned and output variable *piLast is
144555 ** set to the largest blockid written to the database (or zero if no
144556 ** blocks were written to the db). Otherwise, an SQLite error code is 
144557 ** returned.
144558 */
144559 static int fts3NodeWrite(
144560   Fts3Table *p,                   /* Virtual table handle */
144561   SegmentNode *pTree,             /* SegmentNode handle */
144562   int iHeight,                    /* Height of this node in tree */
144563   sqlite3_int64 iLeaf,            /* Block id of first leaf node */
144564   sqlite3_int64 iFree,            /* Block id of next free slot in %_segments */
144565   sqlite3_int64 *piLast,          /* OUT: Block id of last entry written */
144566   char **paRoot,                  /* OUT: Data for root node */
144567   int *pnRoot                     /* OUT: Size of root node in bytes */
144568 ){
144569   int rc = SQLITE_OK;
144570
144571   if( !pTree->pParent ){
144572     /* Root node of the tree. */
144573     int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
144574     *piLast = iFree-1;
144575     *pnRoot = pTree->nData - nStart;
144576     *paRoot = &pTree->aData[nStart];
144577   }else{
144578     SegmentNode *pIter;
144579     sqlite3_int64 iNextFree = iFree;
144580     sqlite3_int64 iNextLeaf = iLeaf;
144581     for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
144582       int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
144583       int nWrite = pIter->nData - nStart;
144584   
144585       rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
144586       iNextFree++;
144587       iNextLeaf += (pIter->nEntry+1);
144588     }
144589     if( rc==SQLITE_OK ){
144590       assert( iNextLeaf==iFree );
144591       rc = fts3NodeWrite(
144592           p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
144593       );
144594     }
144595   }
144596
144597   return rc;
144598 }
144599
144600 /*
144601 ** Free all memory allocations associated with the tree pTree.
144602 */
144603 static void fts3NodeFree(SegmentNode *pTree){
144604   if( pTree ){
144605     SegmentNode *p = pTree->pLeftmost;
144606     fts3NodeFree(p->pParent);
144607     while( p ){
144608       SegmentNode *pRight = p->pRight;
144609       if( p->aData!=(char *)&p[1] ){
144610         sqlite3_free(p->aData);
144611       }
144612       assert( pRight==0 || p->zMalloc==0 );
144613       sqlite3_free(p->zMalloc);
144614       sqlite3_free(p);
144615       p = pRight;
144616     }
144617   }
144618 }
144619
144620 /*
144621 ** Add a term to the segment being constructed by the SegmentWriter object
144622 ** *ppWriter. When adding the first term to a segment, *ppWriter should
144623 ** be passed NULL. This function will allocate a new SegmentWriter object
144624 ** and return it via the input/output variable *ppWriter in this case.
144625 **
144626 ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
144627 */
144628 static int fts3SegWriterAdd(
144629   Fts3Table *p,                   /* Virtual table handle */
144630   SegmentWriter **ppWriter,       /* IN/OUT: SegmentWriter handle */ 
144631   int isCopyTerm,                 /* True if buffer zTerm must be copied */
144632   const char *zTerm,              /* Pointer to buffer containing term */
144633   int nTerm,                      /* Size of term in bytes */
144634   const char *aDoclist,           /* Pointer to buffer containing doclist */
144635   int nDoclist                    /* Size of doclist in bytes */
144636 ){
144637   int nPrefix;                    /* Size of term prefix in bytes */
144638   int nSuffix;                    /* Size of term suffix in bytes */
144639   int nReq;                       /* Number of bytes required on leaf page */
144640   int nData;
144641   SegmentWriter *pWriter = *ppWriter;
144642
144643   if( !pWriter ){
144644     int rc;
144645     sqlite3_stmt *pStmt;
144646
144647     /* Allocate the SegmentWriter structure */
144648     pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
144649     if( !pWriter ) return SQLITE_NOMEM;
144650     memset(pWriter, 0, sizeof(SegmentWriter));
144651     *ppWriter = pWriter;
144652
144653     /* Allocate a buffer in which to accumulate data */
144654     pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
144655     if( !pWriter->aData ) return SQLITE_NOMEM;
144656     pWriter->nSize = p->nNodeSize;
144657
144658     /* Find the next free blockid in the %_segments table */
144659     rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
144660     if( rc!=SQLITE_OK ) return rc;
144661     if( SQLITE_ROW==sqlite3_step(pStmt) ){
144662       pWriter->iFree = sqlite3_column_int64(pStmt, 0);
144663       pWriter->iFirst = pWriter->iFree;
144664     }
144665     rc = sqlite3_reset(pStmt);
144666     if( rc!=SQLITE_OK ) return rc;
144667   }
144668   nData = pWriter->nData;
144669
144670   nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
144671   nSuffix = nTerm-nPrefix;
144672
144673   /* Figure out how many bytes are required by this new entry */
144674   nReq = sqlite3Fts3VarintLen(nPrefix) +    /* varint containing prefix size */
144675     sqlite3Fts3VarintLen(nSuffix) +         /* varint containing suffix size */
144676     nSuffix +                               /* Term suffix */
144677     sqlite3Fts3VarintLen(nDoclist) +        /* Size of doclist */
144678     nDoclist;                               /* Doclist data */
144679
144680   if( nData>0 && nData+nReq>p->nNodeSize ){
144681     int rc;
144682
144683     /* The current leaf node is full. Write it out to the database. */
144684     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
144685     if( rc!=SQLITE_OK ) return rc;
144686     p->nLeafAdd++;
144687
144688     /* Add the current term to the interior node tree. The term added to
144689     ** the interior tree must:
144690     **
144691     **   a) be greater than the largest term on the leaf node just written
144692     **      to the database (still available in pWriter->zTerm), and
144693     **
144694     **   b) be less than or equal to the term about to be added to the new
144695     **      leaf node (zTerm/nTerm).
144696     **
144697     ** In other words, it must be the prefix of zTerm 1 byte longer than
144698     ** the common prefix (if any) of zTerm and pWriter->zTerm.
144699     */
144700     assert( nPrefix<nTerm );
144701     rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
144702     if( rc!=SQLITE_OK ) return rc;
144703
144704     nData = 0;
144705     pWriter->nTerm = 0;
144706
144707     nPrefix = 0;
144708     nSuffix = nTerm;
144709     nReq = 1 +                              /* varint containing prefix size */
144710       sqlite3Fts3VarintLen(nTerm) +         /* varint containing suffix size */
144711       nTerm +                               /* Term suffix */
144712       sqlite3Fts3VarintLen(nDoclist) +      /* Size of doclist */
144713       nDoclist;                             /* Doclist data */
144714   }
144715
144716   /* Increase the total number of bytes written to account for the new entry. */
144717   pWriter->nLeafData += nReq;
144718
144719   /* If the buffer currently allocated is too small for this entry, realloc
144720   ** the buffer to make it large enough.
144721   */
144722   if( nReq>pWriter->nSize ){
144723     char *aNew = sqlite3_realloc(pWriter->aData, nReq);
144724     if( !aNew ) return SQLITE_NOMEM;
144725     pWriter->aData = aNew;
144726     pWriter->nSize = nReq;
144727   }
144728   assert( nData+nReq<=pWriter->nSize );
144729
144730   /* Append the prefix-compressed term and doclist to the buffer. */
144731   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
144732   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
144733   memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
144734   nData += nSuffix;
144735   nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
144736   memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
144737   pWriter->nData = nData + nDoclist;
144738
144739   /* Save the current term so that it can be used to prefix-compress the next.
144740   ** If the isCopyTerm parameter is true, then the buffer pointed to by
144741   ** zTerm is transient, so take a copy of the term data. Otherwise, just
144742   ** store a copy of the pointer.
144743   */
144744   if( isCopyTerm ){
144745     if( nTerm>pWriter->nMalloc ){
144746       char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
144747       if( !zNew ){
144748         return SQLITE_NOMEM;
144749       }
144750       pWriter->nMalloc = nTerm*2;
144751       pWriter->zMalloc = zNew;
144752       pWriter->zTerm = zNew;
144753     }
144754     assert( pWriter->zTerm==pWriter->zMalloc );
144755     memcpy(pWriter->zTerm, zTerm, nTerm);
144756   }else{
144757     pWriter->zTerm = (char *)zTerm;
144758   }
144759   pWriter->nTerm = nTerm;
144760
144761   return SQLITE_OK;
144762 }
144763
144764 /*
144765 ** Flush all data associated with the SegmentWriter object pWriter to the
144766 ** database. This function must be called after all terms have been added
144767 ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
144768 ** returned. Otherwise, an SQLite error code.
144769 */
144770 static int fts3SegWriterFlush(
144771   Fts3Table *p,                   /* Virtual table handle */
144772   SegmentWriter *pWriter,         /* SegmentWriter to flush to the db */
144773   sqlite3_int64 iLevel,           /* Value for 'level' column of %_segdir */
144774   int iIdx                        /* Value for 'idx' column of %_segdir */
144775 ){
144776   int rc;                         /* Return code */
144777   if( pWriter->pTree ){
144778     sqlite3_int64 iLast = 0;      /* Largest block id written to database */
144779     sqlite3_int64 iLastLeaf;      /* Largest leaf block id written to db */
144780     char *zRoot = NULL;           /* Pointer to buffer containing root node */
144781     int nRoot = 0;                /* Size of buffer zRoot */
144782
144783     iLastLeaf = pWriter->iFree;
144784     rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
144785     if( rc==SQLITE_OK ){
144786       rc = fts3NodeWrite(p, pWriter->pTree, 1,
144787           pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
144788     }
144789     if( rc==SQLITE_OK ){
144790       rc = fts3WriteSegdir(p, iLevel, iIdx, 
144791           pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
144792     }
144793   }else{
144794     /* The entire tree fits on the root node. Write it to the segdir table. */
144795     rc = fts3WriteSegdir(p, iLevel, iIdx, 
144796         0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
144797   }
144798   p->nLeafAdd++;
144799   return rc;
144800 }
144801
144802 /*
144803 ** Release all memory held by the SegmentWriter object passed as the 
144804 ** first argument.
144805 */
144806 static void fts3SegWriterFree(SegmentWriter *pWriter){
144807   if( pWriter ){
144808     sqlite3_free(pWriter->aData);
144809     sqlite3_free(pWriter->zMalloc);
144810     fts3NodeFree(pWriter->pTree);
144811     sqlite3_free(pWriter);
144812   }
144813 }
144814
144815 /*
144816 ** The first value in the apVal[] array is assumed to contain an integer.
144817 ** This function tests if there exist any documents with docid values that
144818 ** are different from that integer. i.e. if deleting the document with docid
144819 ** pRowid would mean the FTS3 table were empty.
144820 **
144821 ** If successful, *pisEmpty is set to true if the table is empty except for
144822 ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
144823 ** error occurs, an SQLite error code is returned.
144824 */
144825 static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
144826   sqlite3_stmt *pStmt;
144827   int rc;
144828   if( p->zContentTbl ){
144829     /* If using the content=xxx option, assume the table is never empty */
144830     *pisEmpty = 0;
144831     rc = SQLITE_OK;
144832   }else{
144833     rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
144834     if( rc==SQLITE_OK ){
144835       if( SQLITE_ROW==sqlite3_step(pStmt) ){
144836         *pisEmpty = sqlite3_column_int(pStmt, 0);
144837       }
144838       rc = sqlite3_reset(pStmt);
144839     }
144840   }
144841   return rc;
144842 }
144843
144844 /*
144845 ** Set *pnMax to the largest segment level in the database for the index
144846 ** iIndex.
144847 **
144848 ** Segment levels are stored in the 'level' column of the %_segdir table.
144849 **
144850 ** Return SQLITE_OK if successful, or an SQLite error code if not.
144851 */
144852 static int fts3SegmentMaxLevel(
144853   Fts3Table *p, 
144854   int iLangid,
144855   int iIndex, 
144856   sqlite3_int64 *pnMax
144857 ){
144858   sqlite3_stmt *pStmt;
144859   int rc;
144860   assert( iIndex>=0 && iIndex<p->nIndex );
144861
144862   /* Set pStmt to the compiled version of:
144863   **
144864   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
144865   **
144866   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
144867   */
144868   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
144869   if( rc!=SQLITE_OK ) return rc;
144870   sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
144871   sqlite3_bind_int64(pStmt, 2, 
144872       getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
144873   );
144874   if( SQLITE_ROW==sqlite3_step(pStmt) ){
144875     *pnMax = sqlite3_column_int64(pStmt, 0);
144876   }
144877   return sqlite3_reset(pStmt);
144878 }
144879
144880 /*
144881 ** iAbsLevel is an absolute level that may be assumed to exist within
144882 ** the database. This function checks if it is the largest level number
144883 ** within its index. Assuming no error occurs, *pbMax is set to 1 if
144884 ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
144885 ** is returned. If an error occurs, an error code is returned and the
144886 ** final value of *pbMax is undefined.
144887 */
144888 static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
144889
144890   /* Set pStmt to the compiled version of:
144891   **
144892   **   SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
144893   **
144894   ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
144895   */
144896   sqlite3_stmt *pStmt;
144897   int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
144898   if( rc!=SQLITE_OK ) return rc;
144899   sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
144900   sqlite3_bind_int64(pStmt, 2, 
144901       ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
144902   );
144903
144904   *pbMax = 0;
144905   if( SQLITE_ROW==sqlite3_step(pStmt) ){
144906     *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
144907   }
144908   return sqlite3_reset(pStmt);
144909 }
144910
144911 /*
144912 ** Delete all entries in the %_segments table associated with the segment
144913 ** opened with seg-reader pSeg. This function does not affect the contents
144914 ** of the %_segdir table.
144915 */
144916 static int fts3DeleteSegment(
144917   Fts3Table *p,                   /* FTS table handle */
144918   Fts3SegReader *pSeg             /* Segment to delete */
144919 ){
144920   int rc = SQLITE_OK;             /* Return code */
144921   if( pSeg->iStartBlock ){
144922     sqlite3_stmt *pDelete;        /* SQL statement to delete rows */
144923     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
144924     if( rc==SQLITE_OK ){
144925       sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
144926       sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
144927       sqlite3_step(pDelete);
144928       rc = sqlite3_reset(pDelete);
144929     }
144930   }
144931   return rc;
144932 }
144933
144934 /*
144935 ** This function is used after merging multiple segments into a single large
144936 ** segment to delete the old, now redundant, segment b-trees. Specifically,
144937 ** it:
144938 ** 
144939 **   1) Deletes all %_segments entries for the segments associated with 
144940 **      each of the SegReader objects in the array passed as the third 
144941 **      argument, and
144942 **
144943 **   2) deletes all %_segdir entries with level iLevel, or all %_segdir
144944 **      entries regardless of level if (iLevel<0).
144945 **
144946 ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
144947 */
144948 static int fts3DeleteSegdir(
144949   Fts3Table *p,                   /* Virtual table handle */
144950   int iLangid,                    /* Language id */
144951   int iIndex,                     /* Index for p->aIndex */
144952   int iLevel,                     /* Level of %_segdir entries to delete */
144953   Fts3SegReader **apSegment,      /* Array of SegReader objects */
144954   int nReader                     /* Size of array apSegment */
144955 ){
144956   int rc = SQLITE_OK;             /* Return Code */
144957   int i;                          /* Iterator variable */
144958   sqlite3_stmt *pDelete = 0;      /* SQL statement to delete rows */
144959
144960   for(i=0; rc==SQLITE_OK && i<nReader; i++){
144961     rc = fts3DeleteSegment(p, apSegment[i]);
144962   }
144963   if( rc!=SQLITE_OK ){
144964     return rc;
144965   }
144966
144967   assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
144968   if( iLevel==FTS3_SEGCURSOR_ALL ){
144969     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
144970     if( rc==SQLITE_OK ){
144971       sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
144972       sqlite3_bind_int64(pDelete, 2, 
144973           getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
144974       );
144975     }
144976   }else{
144977     rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
144978     if( rc==SQLITE_OK ){
144979       sqlite3_bind_int64(
144980           pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
144981       );
144982     }
144983   }
144984
144985   if( rc==SQLITE_OK ){
144986     sqlite3_step(pDelete);
144987     rc = sqlite3_reset(pDelete);
144988   }
144989
144990   return rc;
144991 }
144992
144993 /*
144994 ** When this function is called, buffer *ppList (size *pnList bytes) contains 
144995 ** a position list that may (or may not) feature multiple columns. This
144996 ** function adjusts the pointer *ppList and the length *pnList so that they
144997 ** identify the subset of the position list that corresponds to column iCol.
144998 **
144999 ** If there are no entries in the input position list for column iCol, then
145000 ** *pnList is set to zero before returning.
145001 **
145002 ** If parameter bZero is non-zero, then any part of the input list following
145003 ** the end of the output list is zeroed before returning.
145004 */
145005 static void fts3ColumnFilter(
145006   int iCol,                       /* Column to filter on */
145007   int bZero,                      /* Zero out anything following *ppList */
145008   char **ppList,                  /* IN/OUT: Pointer to position list */
145009   int *pnList                     /* IN/OUT: Size of buffer *ppList in bytes */
145010 ){
145011   char *pList = *ppList;
145012   int nList = *pnList;
145013   char *pEnd = &pList[nList];
145014   int iCurrent = 0;
145015   char *p = pList;
145016
145017   assert( iCol>=0 );
145018   while( 1 ){
145019     char c = 0;
145020     while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
145021   
145022     if( iCol==iCurrent ){
145023       nList = (int)(p - pList);
145024       break;
145025     }
145026
145027     nList -= (int)(p - pList);
145028     pList = p;
145029     if( nList==0 ){
145030       break;
145031     }
145032     p = &pList[1];
145033     p += fts3GetVarint32(p, &iCurrent);
145034   }
145035
145036   if( bZero && &pList[nList]!=pEnd ){
145037     memset(&pList[nList], 0, pEnd - &pList[nList]);
145038   }
145039   *ppList = pList;
145040   *pnList = nList;
145041 }
145042
145043 /*
145044 ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
145045 ** existing data). Grow the buffer if required.
145046 **
145047 ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
145048 ** trying to resize the buffer, return SQLITE_NOMEM.
145049 */
145050 static int fts3MsrBufferData(
145051   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
145052   char *pList,
145053   int nList
145054 ){
145055   if( nList>pMsr->nBuffer ){
145056     char *pNew;
145057     pMsr->nBuffer = nList*2;
145058     pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
145059     if( !pNew ) return SQLITE_NOMEM;
145060     pMsr->aBuffer = pNew;
145061   }
145062
145063   memcpy(pMsr->aBuffer, pList, nList);
145064   return SQLITE_OK;
145065 }
145066
145067 SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
145068   Fts3Table *p,                   /* Virtual table handle */
145069   Fts3MultiSegReader *pMsr,       /* Multi-segment-reader handle */
145070   sqlite3_int64 *piDocid,         /* OUT: Docid value */
145071   char **paPoslist,               /* OUT: Pointer to position list */
145072   int *pnPoslist                  /* OUT: Size of position list in bytes */
145073 ){
145074   int nMerge = pMsr->nAdvance;
145075   Fts3SegReader **apSegment = pMsr->apSegment;
145076   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
145077     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
145078   );
145079
145080   if( nMerge==0 ){
145081     *paPoslist = 0;
145082     return SQLITE_OK;
145083   }
145084
145085   while( 1 ){
145086     Fts3SegReader *pSeg;
145087     pSeg = pMsr->apSegment[0];
145088
145089     if( pSeg->pOffsetList==0 ){
145090       *paPoslist = 0;
145091       break;
145092     }else{
145093       int rc;
145094       char *pList;
145095       int nList;
145096       int j;
145097       sqlite3_int64 iDocid = apSegment[0]->iDocid;
145098
145099       rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
145100       j = 1;
145101       while( rc==SQLITE_OK 
145102         && j<nMerge
145103         && apSegment[j]->pOffsetList
145104         && apSegment[j]->iDocid==iDocid
145105       ){
145106         rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
145107         j++;
145108       }
145109       if( rc!=SQLITE_OK ) return rc;
145110       fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
145111
145112       if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
145113         rc = fts3MsrBufferData(pMsr, pList, nList+1);
145114         if( rc!=SQLITE_OK ) return rc;
145115         assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
145116         pList = pMsr->aBuffer;
145117       }
145118
145119       if( pMsr->iColFilter>=0 ){
145120         fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
145121       }
145122
145123       if( nList>0 ){
145124         *paPoslist = pList;
145125         *piDocid = iDocid;
145126         *pnPoslist = nList;
145127         break;
145128       }
145129     }
145130   }
145131
145132   return SQLITE_OK;
145133 }
145134
145135 static int fts3SegReaderStart(
145136   Fts3Table *p,                   /* Virtual table handle */
145137   Fts3MultiSegReader *pCsr,       /* Cursor object */
145138   const char *zTerm,              /* Term searched for (or NULL) */
145139   int nTerm                       /* Length of zTerm in bytes */
145140 ){
145141   int i;
145142   int nSeg = pCsr->nSegment;
145143
145144   /* If the Fts3SegFilter defines a specific term (or term prefix) to search 
145145   ** for, then advance each segment iterator until it points to a term of
145146   ** equal or greater value than the specified term. This prevents many
145147   ** unnecessary merge/sort operations for the case where single segment
145148   ** b-tree leaf nodes contain more than one term.
145149   */
145150   for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
145151     int res = 0;
145152     Fts3SegReader *pSeg = pCsr->apSegment[i];
145153     do {
145154       int rc = fts3SegReaderNext(p, pSeg, 0);
145155       if( rc!=SQLITE_OK ) return rc;
145156     }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
145157
145158     if( pSeg->bLookup && res!=0 ){
145159       fts3SegReaderSetEof(pSeg);
145160     }
145161   }
145162   fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
145163
145164   return SQLITE_OK;
145165 }
145166
145167 SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
145168   Fts3Table *p,                   /* Virtual table handle */
145169   Fts3MultiSegReader *pCsr,       /* Cursor object */
145170   Fts3SegFilter *pFilter          /* Restrictions on range of iteration */
145171 ){
145172   pCsr->pFilter = pFilter;
145173   return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
145174 }
145175
145176 SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
145177   Fts3Table *p,                   /* Virtual table handle */
145178   Fts3MultiSegReader *pCsr,       /* Cursor object */
145179   int iCol,                       /* Column to match on. */
145180   const char *zTerm,              /* Term to iterate through a doclist for */
145181   int nTerm                       /* Number of bytes in zTerm */
145182 ){
145183   int i;
145184   int rc;
145185   int nSegment = pCsr->nSegment;
145186   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
145187     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
145188   );
145189
145190   assert( pCsr->pFilter==0 );
145191   assert( zTerm && nTerm>0 );
145192
145193   /* Advance each segment iterator until it points to the term zTerm/nTerm. */
145194   rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
145195   if( rc!=SQLITE_OK ) return rc;
145196
145197   /* Determine how many of the segments actually point to zTerm/nTerm. */
145198   for(i=0; i<nSegment; i++){
145199     Fts3SegReader *pSeg = pCsr->apSegment[i];
145200     if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
145201       break;
145202     }
145203   }
145204   pCsr->nAdvance = i;
145205
145206   /* Advance each of the segments to point to the first docid. */
145207   for(i=0; i<pCsr->nAdvance; i++){
145208     rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
145209     if( rc!=SQLITE_OK ) return rc;
145210   }
145211   fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
145212
145213   assert( iCol<0 || iCol<p->nColumn );
145214   pCsr->iColFilter = iCol;
145215
145216   return SQLITE_OK;
145217 }
145218
145219 /*
145220 ** This function is called on a MultiSegReader that has been started using
145221 ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
145222 ** have been made. Calling this function puts the MultiSegReader in such
145223 ** a state that if the next two calls are:
145224 **
145225 **   sqlite3Fts3SegReaderStart()
145226 **   sqlite3Fts3SegReaderStep()
145227 **
145228 ** then the entire doclist for the term is available in 
145229 ** MultiSegReader.aDoclist/nDoclist.
145230 */
145231 SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
145232   int i;                          /* Used to iterate through segment-readers */
145233
145234   assert( pCsr->zTerm==0 );
145235   assert( pCsr->nTerm==0 );
145236   assert( pCsr->aDoclist==0 );
145237   assert( pCsr->nDoclist==0 );
145238
145239   pCsr->nAdvance = 0;
145240   pCsr->bRestart = 1;
145241   for(i=0; i<pCsr->nSegment; i++){
145242     pCsr->apSegment[i]->pOffsetList = 0;
145243     pCsr->apSegment[i]->nOffsetList = 0;
145244     pCsr->apSegment[i]->iDocid = 0;
145245   }
145246
145247   return SQLITE_OK;
145248 }
145249
145250
145251 SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
145252   Fts3Table *p,                   /* Virtual table handle */
145253   Fts3MultiSegReader *pCsr        /* Cursor object */
145254 ){
145255   int rc = SQLITE_OK;
145256
145257   int isIgnoreEmpty =  (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
145258   int isRequirePos =   (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
145259   int isColFilter =    (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
145260   int isPrefix =       (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
145261   int isScan =         (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
145262   int isFirst =        (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
145263
145264   Fts3SegReader **apSegment = pCsr->apSegment;
145265   int nSegment = pCsr->nSegment;
145266   Fts3SegFilter *pFilter = pCsr->pFilter;
145267   int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
145268     p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
145269   );
145270
145271   if( pCsr->nSegment==0 ) return SQLITE_OK;
145272
145273   do {
145274     int nMerge;
145275     int i;
145276   
145277     /* Advance the first pCsr->nAdvance entries in the apSegment[] array
145278     ** forward. Then sort the list in order of current term again.  
145279     */
145280     for(i=0; i<pCsr->nAdvance; i++){
145281       Fts3SegReader *pSeg = apSegment[i];
145282       if( pSeg->bLookup ){
145283         fts3SegReaderSetEof(pSeg);
145284       }else{
145285         rc = fts3SegReaderNext(p, pSeg, 0);
145286       }
145287       if( rc!=SQLITE_OK ) return rc;
145288     }
145289     fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
145290     pCsr->nAdvance = 0;
145291
145292     /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
145293     assert( rc==SQLITE_OK );
145294     if( apSegment[0]->aNode==0 ) break;
145295
145296     pCsr->nTerm = apSegment[0]->nTerm;
145297     pCsr->zTerm = apSegment[0]->zTerm;
145298
145299     /* If this is a prefix-search, and if the term that apSegment[0] points
145300     ** to does not share a suffix with pFilter->zTerm/nTerm, then all 
145301     ** required callbacks have been made. In this case exit early.
145302     **
145303     ** Similarly, if this is a search for an exact match, and the first term
145304     ** of segment apSegment[0] is not a match, exit early.
145305     */
145306     if( pFilter->zTerm && !isScan ){
145307       if( pCsr->nTerm<pFilter->nTerm 
145308        || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
145309        || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm) 
145310       ){
145311         break;
145312       }
145313     }
145314
145315     nMerge = 1;
145316     while( nMerge<nSegment 
145317         && apSegment[nMerge]->aNode
145318         && apSegment[nMerge]->nTerm==pCsr->nTerm 
145319         && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
145320     ){
145321       nMerge++;
145322     }
145323
145324     assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
145325     if( nMerge==1 
145326      && !isIgnoreEmpty 
145327      && !isFirst 
145328      && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
145329     ){
145330       pCsr->nDoclist = apSegment[0]->nDoclist;
145331       if( fts3SegReaderIsPending(apSegment[0]) ){
145332         rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
145333         pCsr->aDoclist = pCsr->aBuffer;
145334       }else{
145335         pCsr->aDoclist = apSegment[0]->aDoclist;
145336       }
145337       if( rc==SQLITE_OK ) rc = SQLITE_ROW;
145338     }else{
145339       int nDoclist = 0;           /* Size of doclist */
145340       sqlite3_int64 iPrev = 0;    /* Previous docid stored in doclist */
145341
145342       /* The current term of the first nMerge entries in the array
145343       ** of Fts3SegReader objects is the same. The doclists must be merged
145344       ** and a single term returned with the merged doclist.
145345       */
145346       for(i=0; i<nMerge; i++){
145347         fts3SegReaderFirstDocid(p, apSegment[i]);
145348       }
145349       fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
145350       while( apSegment[0]->pOffsetList ){
145351         int j;                    /* Number of segments that share a docid */
145352         char *pList = 0;
145353         int nList = 0;
145354         int nByte;
145355         sqlite3_int64 iDocid = apSegment[0]->iDocid;
145356         fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
145357         j = 1;
145358         while( j<nMerge
145359             && apSegment[j]->pOffsetList
145360             && apSegment[j]->iDocid==iDocid
145361         ){
145362           fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
145363           j++;
145364         }
145365
145366         if( isColFilter ){
145367           fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
145368         }
145369
145370         if( !isIgnoreEmpty || nList>0 ){
145371
145372           /* Calculate the 'docid' delta value to write into the merged 
145373           ** doclist. */
145374           sqlite3_int64 iDelta;
145375           if( p->bDescIdx && nDoclist>0 ){
145376             iDelta = iPrev - iDocid;
145377           }else{
145378             iDelta = iDocid - iPrev;
145379           }
145380           assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
145381           assert( nDoclist>0 || iDelta==iDocid );
145382
145383           nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
145384           if( nDoclist+nByte>pCsr->nBuffer ){
145385             char *aNew;
145386             pCsr->nBuffer = (nDoclist+nByte)*2;
145387             aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
145388             if( !aNew ){
145389               return SQLITE_NOMEM;
145390             }
145391             pCsr->aBuffer = aNew;
145392           }
145393
145394           if( isFirst ){
145395             char *a = &pCsr->aBuffer[nDoclist];
145396             int nWrite;
145397            
145398             nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
145399             if( nWrite ){
145400               iPrev = iDocid;
145401               nDoclist += nWrite;
145402             }
145403           }else{
145404             nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
145405             iPrev = iDocid;
145406             if( isRequirePos ){
145407               memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
145408               nDoclist += nList;
145409               pCsr->aBuffer[nDoclist++] = '\0';
145410             }
145411           }
145412         }
145413
145414         fts3SegReaderSort(apSegment, nMerge, j, xCmp);
145415       }
145416       if( nDoclist>0 ){
145417         pCsr->aDoclist = pCsr->aBuffer;
145418         pCsr->nDoclist = nDoclist;
145419         rc = SQLITE_ROW;
145420       }
145421     }
145422     pCsr->nAdvance = nMerge;
145423   }while( rc==SQLITE_OK );
145424
145425   return rc;
145426 }
145427
145428
145429 SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
145430   Fts3MultiSegReader *pCsr       /* Cursor object */
145431 ){
145432   if( pCsr ){
145433     int i;
145434     for(i=0; i<pCsr->nSegment; i++){
145435       sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
145436     }
145437     sqlite3_free(pCsr->apSegment);
145438     sqlite3_free(pCsr->aBuffer);
145439
145440     pCsr->nSegment = 0;
145441     pCsr->apSegment = 0;
145442     pCsr->aBuffer = 0;
145443   }
145444 }
145445
145446 /*
145447 ** Decode the "end_block" field, selected by column iCol of the SELECT 
145448 ** statement passed as the first argument. 
145449 **
145450 ** The "end_block" field may contain either an integer, or a text field
145451 ** containing the text representation of two non-negative integers separated 
145452 ** by one or more space (0x20) characters. In the first case, set *piEndBlock 
145453 ** to the integer value and *pnByte to zero before returning. In the second, 
145454 ** set *piEndBlock to the first value and *pnByte to the second.
145455 */
145456 static void fts3ReadEndBlockField(
145457   sqlite3_stmt *pStmt, 
145458   int iCol, 
145459   i64 *piEndBlock,
145460   i64 *pnByte
145461 ){
145462   const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
145463   if( zText ){
145464     int i;
145465     int iMul = 1;
145466     i64 iVal = 0;
145467     for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
145468       iVal = iVal*10 + (zText[i] - '0');
145469     }
145470     *piEndBlock = iVal;
145471     while( zText[i]==' ' ) i++;
145472     iVal = 0;
145473     if( zText[i]=='-' ){
145474       i++;
145475       iMul = -1;
145476     }
145477     for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
145478       iVal = iVal*10 + (zText[i] - '0');
145479     }
145480     *pnByte = (iVal * (i64)iMul);
145481   }
145482 }
145483
145484
145485 /*
145486 ** A segment of size nByte bytes has just been written to absolute level
145487 ** iAbsLevel. Promote any segments that should be promoted as a result.
145488 */
145489 static int fts3PromoteSegments(
145490   Fts3Table *p,                   /* FTS table handle */
145491   sqlite3_int64 iAbsLevel,        /* Absolute level just updated */
145492   sqlite3_int64 nByte             /* Size of new segment at iAbsLevel */
145493 ){
145494   int rc = SQLITE_OK;
145495   sqlite3_stmt *pRange;
145496
145497   rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
145498
145499   if( rc==SQLITE_OK ){
145500     int bOk = 0;
145501     i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
145502     i64 nLimit = (nByte*3)/2;
145503
145504     /* Loop through all entries in the %_segdir table corresponding to 
145505     ** segments in this index on levels greater than iAbsLevel. If there is
145506     ** at least one such segment, and it is possible to determine that all 
145507     ** such segments are smaller than nLimit bytes in size, they will be 
145508     ** promoted to level iAbsLevel.  */
145509     sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
145510     sqlite3_bind_int64(pRange, 2, iLast);
145511     while( SQLITE_ROW==sqlite3_step(pRange) ){
145512       i64 nSize = 0, dummy;
145513       fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
145514       if( nSize<=0 || nSize>nLimit ){
145515         /* If nSize==0, then the %_segdir.end_block field does not not 
145516         ** contain a size value. This happens if it was written by an
145517         ** old version of FTS. In this case it is not possible to determine
145518         ** the size of the segment, and so segment promotion does not
145519         ** take place.  */
145520         bOk = 0;
145521         break;
145522       }
145523       bOk = 1;
145524     }
145525     rc = sqlite3_reset(pRange);
145526
145527     if( bOk ){
145528       int iIdx = 0;
145529       sqlite3_stmt *pUpdate1 = 0;
145530       sqlite3_stmt *pUpdate2 = 0;
145531
145532       if( rc==SQLITE_OK ){
145533         rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
145534       }
145535       if( rc==SQLITE_OK ){
145536         rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
145537       }
145538
145539       if( rc==SQLITE_OK ){
145540
145541         /* Loop through all %_segdir entries for segments in this index with
145542         ** levels equal to or greater than iAbsLevel. As each entry is visited,
145543         ** updated it to set (level = -1) and (idx = N), where N is 0 for the
145544         ** oldest segment in the range, 1 for the next oldest, and so on.
145545         **
145546         ** In other words, move all segments being promoted to level -1,
145547         ** setting the "idx" fields as appropriate to keep them in the same
145548         ** order. The contents of level -1 (which is never used, except
145549         ** transiently here), will be moved back to level iAbsLevel below.  */
145550         sqlite3_bind_int64(pRange, 1, iAbsLevel);
145551         while( SQLITE_ROW==sqlite3_step(pRange) ){
145552           sqlite3_bind_int(pUpdate1, 1, iIdx++);
145553           sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
145554           sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
145555           sqlite3_step(pUpdate1);
145556           rc = sqlite3_reset(pUpdate1);
145557           if( rc!=SQLITE_OK ){
145558             sqlite3_reset(pRange);
145559             break;
145560           }
145561         }
145562       }
145563       if( rc==SQLITE_OK ){
145564         rc = sqlite3_reset(pRange);
145565       }
145566
145567       /* Move level -1 to level iAbsLevel */
145568       if( rc==SQLITE_OK ){
145569         sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
145570         sqlite3_step(pUpdate2);
145571         rc = sqlite3_reset(pUpdate2);
145572       }
145573     }
145574   }
145575
145576
145577   return rc;
145578 }
145579
145580 /*
145581 ** Merge all level iLevel segments in the database into a single 
145582 ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
145583 ** single segment with a level equal to the numerically largest level 
145584 ** currently present in the database.
145585 **
145586 ** If this function is called with iLevel<0, but there is only one
145587 ** segment in the database, SQLITE_DONE is returned immediately. 
145588 ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs, 
145589 ** an SQLite error code is returned.
145590 */
145591 static int fts3SegmentMerge(
145592   Fts3Table *p, 
145593   int iLangid,                    /* Language id to merge */
145594   int iIndex,                     /* Index in p->aIndex[] to merge */
145595   int iLevel                      /* Level to merge */
145596 ){
145597   int rc;                         /* Return code */
145598   int iIdx = 0;                   /* Index of new segment */
145599   sqlite3_int64 iNewLevel = 0;    /* Level/index to create new segment at */
145600   SegmentWriter *pWriter = 0;     /* Used to write the new, merged, segment */
145601   Fts3SegFilter filter;           /* Segment term filter condition */
145602   Fts3MultiSegReader csr;         /* Cursor to iterate through level(s) */
145603   int bIgnoreEmpty = 0;           /* True to ignore empty segments */
145604   i64 iMaxLevel = 0;              /* Max level number for this index/langid */
145605
145606   assert( iLevel==FTS3_SEGCURSOR_ALL
145607        || iLevel==FTS3_SEGCURSOR_PENDING
145608        || iLevel>=0
145609   );
145610   assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
145611   assert( iIndex>=0 && iIndex<p->nIndex );
145612
145613   rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
145614   if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
145615
145616   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
145617     rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
145618     if( rc!=SQLITE_OK ) goto finished;
145619   }
145620
145621   if( iLevel==FTS3_SEGCURSOR_ALL ){
145622     /* This call is to merge all segments in the database to a single
145623     ** segment. The level of the new segment is equal to the numerically
145624     ** greatest segment level currently present in the database for this
145625     ** index. The idx of the new segment is always 0.  */
145626     if( csr.nSegment==1 ){
145627       rc = SQLITE_DONE;
145628       goto finished;
145629     }
145630     iNewLevel = iMaxLevel;
145631     bIgnoreEmpty = 1;
145632
145633   }else{
145634     /* This call is to merge all segments at level iLevel. find the next
145635     ** available segment index at level iLevel+1. The call to
145636     ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to 
145637     ** a single iLevel+2 segment if necessary.  */
145638     assert( FTS3_SEGCURSOR_PENDING==-1 );
145639     iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
145640     rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
145641     bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
145642   }
145643   if( rc!=SQLITE_OK ) goto finished;
145644
145645   assert( csr.nSegment>0 );
145646   assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
145647   assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
145648
145649   memset(&filter, 0, sizeof(Fts3SegFilter));
145650   filter.flags = FTS3_SEGMENT_REQUIRE_POS;
145651   filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
145652
145653   rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
145654   while( SQLITE_OK==rc ){
145655     rc = sqlite3Fts3SegReaderStep(p, &csr);
145656     if( rc!=SQLITE_ROW ) break;
145657     rc = fts3SegWriterAdd(p, &pWriter, 1, 
145658         csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
145659   }
145660   if( rc!=SQLITE_OK ) goto finished;
145661   assert( pWriter || bIgnoreEmpty );
145662
145663   if( iLevel!=FTS3_SEGCURSOR_PENDING ){
145664     rc = fts3DeleteSegdir(
145665         p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
145666     );
145667     if( rc!=SQLITE_OK ) goto finished;
145668   }
145669   if( pWriter ){
145670     rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
145671     if( rc==SQLITE_OK ){
145672       if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
145673         rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
145674       }
145675     }
145676   }
145677
145678  finished:
145679   fts3SegWriterFree(pWriter);
145680   sqlite3Fts3SegReaderFinish(&csr);
145681   return rc;
145682 }
145683
145684
145685 /* 
145686 ** Flush the contents of pendingTerms to level 0 segments. 
145687 */
145688 SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
145689   int rc = SQLITE_OK;
145690   int i;
145691         
145692   for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
145693     rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
145694     if( rc==SQLITE_DONE ) rc = SQLITE_OK;
145695   }
145696   sqlite3Fts3PendingTermsClear(p);
145697
145698   /* Determine the auto-incr-merge setting if unknown.  If enabled,
145699   ** estimate the number of leaf blocks of content to be written
145700   */
145701   if( rc==SQLITE_OK && p->bHasStat
145702    && p->nAutoincrmerge==0xff && p->nLeafAdd>0
145703   ){
145704     sqlite3_stmt *pStmt = 0;
145705     rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
145706     if( rc==SQLITE_OK ){
145707       sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
145708       rc = sqlite3_step(pStmt);
145709       if( rc==SQLITE_ROW ){
145710         p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
145711         if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
145712       }else if( rc==SQLITE_DONE ){
145713         p->nAutoincrmerge = 0;
145714       }
145715       rc = sqlite3_reset(pStmt);
145716     }
145717   }
145718   return rc;
145719 }
145720
145721 /*
145722 ** Encode N integers as varints into a blob.
145723 */
145724 static void fts3EncodeIntArray(
145725   int N,             /* The number of integers to encode */
145726   u32 *a,            /* The integer values */
145727   char *zBuf,        /* Write the BLOB here */
145728   int *pNBuf         /* Write number of bytes if zBuf[] used here */
145729 ){
145730   int i, j;
145731   for(i=j=0; i<N; i++){
145732     j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
145733   }
145734   *pNBuf = j;
145735 }
145736
145737 /*
145738 ** Decode a blob of varints into N integers
145739 */
145740 static void fts3DecodeIntArray(
145741   int N,             /* The number of integers to decode */
145742   u32 *a,            /* Write the integer values */
145743   const char *zBuf,  /* The BLOB containing the varints */
145744   int nBuf           /* size of the BLOB */
145745 ){
145746   int i, j;
145747   UNUSED_PARAMETER(nBuf);
145748   for(i=j=0; i<N; i++){
145749     sqlite3_int64 x;
145750     j += sqlite3Fts3GetVarint(&zBuf[j], &x);
145751     assert(j<=nBuf);
145752     a[i] = (u32)(x & 0xffffffff);
145753   }
145754 }
145755
145756 /*
145757 ** Insert the sizes (in tokens) for each column of the document
145758 ** with docid equal to p->iPrevDocid.  The sizes are encoded as
145759 ** a blob of varints.
145760 */
145761 static void fts3InsertDocsize(
145762   int *pRC,                       /* Result code */
145763   Fts3Table *p,                   /* Table into which to insert */
145764   u32 *aSz                        /* Sizes of each column, in tokens */
145765 ){
145766   char *pBlob;             /* The BLOB encoding of the document size */
145767   int nBlob;               /* Number of bytes in the BLOB */
145768   sqlite3_stmt *pStmt;     /* Statement used to insert the encoding */
145769   int rc;                  /* Result code from subfunctions */
145770
145771   if( *pRC ) return;
145772   pBlob = sqlite3_malloc( 10*p->nColumn );
145773   if( pBlob==0 ){
145774     *pRC = SQLITE_NOMEM;
145775     return;
145776   }
145777   fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
145778   rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
145779   if( rc ){
145780     sqlite3_free(pBlob);
145781     *pRC = rc;
145782     return;
145783   }
145784   sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
145785   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
145786   sqlite3_step(pStmt);
145787   *pRC = sqlite3_reset(pStmt);
145788 }
145789
145790 /*
145791 ** Record 0 of the %_stat table contains a blob consisting of N varints,
145792 ** where N is the number of user defined columns in the fts3 table plus
145793 ** two. If nCol is the number of user defined columns, then values of the 
145794 ** varints are set as follows:
145795 **
145796 **   Varint 0:       Total number of rows in the table.
145797 **
145798 **   Varint 1..nCol: For each column, the total number of tokens stored in
145799 **                   the column for all rows of the table.
145800 **
145801 **   Varint 1+nCol:  The total size, in bytes, of all text values in all
145802 **                   columns of all rows of the table.
145803 **
145804 */
145805 static void fts3UpdateDocTotals(
145806   int *pRC,                       /* The result code */
145807   Fts3Table *p,                   /* Table being updated */
145808   u32 *aSzIns,                    /* Size increases */
145809   u32 *aSzDel,                    /* Size decreases */
145810   int nChng                       /* Change in the number of documents */
145811 ){
145812   char *pBlob;             /* Storage for BLOB written into %_stat */
145813   int nBlob;               /* Size of BLOB written into %_stat */
145814   u32 *a;                  /* Array of integers that becomes the BLOB */
145815   sqlite3_stmt *pStmt;     /* Statement for reading and writing */
145816   int i;                   /* Loop counter */
145817   int rc;                  /* Result code from subfunctions */
145818
145819   const int nStat = p->nColumn+2;
145820
145821   if( *pRC ) return;
145822   a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
145823   if( a==0 ){
145824     *pRC = SQLITE_NOMEM;
145825     return;
145826   }
145827   pBlob = (char*)&a[nStat];
145828   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
145829   if( rc ){
145830     sqlite3_free(a);
145831     *pRC = rc;
145832     return;
145833   }
145834   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
145835   if( sqlite3_step(pStmt)==SQLITE_ROW ){
145836     fts3DecodeIntArray(nStat, a,
145837          sqlite3_column_blob(pStmt, 0),
145838          sqlite3_column_bytes(pStmt, 0));
145839   }else{
145840     memset(a, 0, sizeof(u32)*(nStat) );
145841   }
145842   rc = sqlite3_reset(pStmt);
145843   if( rc!=SQLITE_OK ){
145844     sqlite3_free(a);
145845     *pRC = rc;
145846     return;
145847   }
145848   if( nChng<0 && a[0]<(u32)(-nChng) ){
145849     a[0] = 0;
145850   }else{
145851     a[0] += nChng;
145852   }
145853   for(i=0; i<p->nColumn+1; i++){
145854     u32 x = a[i+1];
145855     if( x+aSzIns[i] < aSzDel[i] ){
145856       x = 0;
145857     }else{
145858       x = x + aSzIns[i] - aSzDel[i];
145859     }
145860     a[i+1] = x;
145861   }
145862   fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
145863   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
145864   if( rc ){
145865     sqlite3_free(a);
145866     *pRC = rc;
145867     return;
145868   }
145869   sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
145870   sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
145871   sqlite3_step(pStmt);
145872   *pRC = sqlite3_reset(pStmt);
145873   sqlite3_free(a);
145874 }
145875
145876 /*
145877 ** Merge the entire database so that there is one segment for each 
145878 ** iIndex/iLangid combination.
145879 */
145880 static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
145881   int bSeenDone = 0;
145882   int rc;
145883   sqlite3_stmt *pAllLangid = 0;
145884
145885   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
145886   if( rc==SQLITE_OK ){
145887     int rc2;
145888     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
145889     while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
145890       int i;
145891       int iLangid = sqlite3_column_int(pAllLangid, 0);
145892       for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
145893         rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
145894         if( rc==SQLITE_DONE ){
145895           bSeenDone = 1;
145896           rc = SQLITE_OK;
145897         }
145898       }
145899     }
145900     rc2 = sqlite3_reset(pAllLangid);
145901     if( rc==SQLITE_OK ) rc = rc2;
145902   }
145903
145904   sqlite3Fts3SegmentsClose(p);
145905   sqlite3Fts3PendingTermsClear(p);
145906
145907   return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
145908 }
145909
145910 /*
145911 ** This function is called when the user executes the following statement:
145912 **
145913 **     INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
145914 **
145915 ** The entire FTS index is discarded and rebuilt. If the table is one 
145916 ** created using the content=xxx option, then the new index is based on
145917 ** the current contents of the xxx table. Otherwise, it is rebuilt based
145918 ** on the contents of the %_content table.
145919 */
145920 static int fts3DoRebuild(Fts3Table *p){
145921   int rc;                         /* Return Code */
145922
145923   rc = fts3DeleteAll(p, 0);
145924   if( rc==SQLITE_OK ){
145925     u32 *aSz = 0;
145926     u32 *aSzIns = 0;
145927     u32 *aSzDel = 0;
145928     sqlite3_stmt *pStmt = 0;
145929     int nEntry = 0;
145930
145931     /* Compose and prepare an SQL statement to loop through the content table */
145932     char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
145933     if( !zSql ){
145934       rc = SQLITE_NOMEM;
145935     }else{
145936       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
145937       sqlite3_free(zSql);
145938     }
145939
145940     if( rc==SQLITE_OK ){
145941       int nByte = sizeof(u32) * (p->nColumn+1)*3;
145942       aSz = (u32 *)sqlite3_malloc(nByte);
145943       if( aSz==0 ){
145944         rc = SQLITE_NOMEM;
145945       }else{
145946         memset(aSz, 0, nByte);
145947         aSzIns = &aSz[p->nColumn+1];
145948         aSzDel = &aSzIns[p->nColumn+1];
145949       }
145950     }
145951
145952     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
145953       int iCol;
145954       int iLangid = langidFromSelect(p, pStmt);
145955       rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
145956       memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
145957       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
145958         if( p->abNotindexed[iCol]==0 ){
145959           const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
145960           rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
145961           aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
145962         }
145963       }
145964       if( p->bHasDocsize ){
145965         fts3InsertDocsize(&rc, p, aSz);
145966       }
145967       if( rc!=SQLITE_OK ){
145968         sqlite3_finalize(pStmt);
145969         pStmt = 0;
145970       }else{
145971         nEntry++;
145972         for(iCol=0; iCol<=p->nColumn; iCol++){
145973           aSzIns[iCol] += aSz[iCol];
145974         }
145975       }
145976     }
145977     if( p->bFts4 ){
145978       fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
145979     }
145980     sqlite3_free(aSz);
145981
145982     if( pStmt ){
145983       int rc2 = sqlite3_finalize(pStmt);
145984       if( rc==SQLITE_OK ){
145985         rc = rc2;
145986       }
145987     }
145988   }
145989
145990   return rc;
145991 }
145992
145993
145994 /*
145995 ** This function opens a cursor used to read the input data for an 
145996 ** incremental merge operation. Specifically, it opens a cursor to scan
145997 ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute 
145998 ** level iAbsLevel.
145999 */
146000 static int fts3IncrmergeCsr(
146001   Fts3Table *p,                   /* FTS3 table handle */
146002   sqlite3_int64 iAbsLevel,        /* Absolute level to open */
146003   int nSeg,                       /* Number of segments to merge */
146004   Fts3MultiSegReader *pCsr        /* Cursor object to populate */
146005 ){
146006   int rc;                         /* Return Code */
146007   sqlite3_stmt *pStmt = 0;        /* Statement used to read %_segdir entry */  
146008   int nByte;                      /* Bytes allocated at pCsr->apSegment[] */
146009
146010   /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
146011   memset(pCsr, 0, sizeof(*pCsr));
146012   nByte = sizeof(Fts3SegReader *) * nSeg;
146013   pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
146014
146015   if( pCsr->apSegment==0 ){
146016     rc = SQLITE_NOMEM;
146017   }else{
146018     memset(pCsr->apSegment, 0, nByte);
146019     rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
146020   }
146021   if( rc==SQLITE_OK ){
146022     int i;
146023     int rc2;
146024     sqlite3_bind_int64(pStmt, 1, iAbsLevel);
146025     assert( pCsr->nSegment==0 );
146026     for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
146027       rc = sqlite3Fts3SegReaderNew(i, 0,
146028           sqlite3_column_int64(pStmt, 1),        /* segdir.start_block */
146029           sqlite3_column_int64(pStmt, 2),        /* segdir.leaves_end_block */
146030           sqlite3_column_int64(pStmt, 3),        /* segdir.end_block */
146031           sqlite3_column_blob(pStmt, 4),         /* segdir.root */
146032           sqlite3_column_bytes(pStmt, 4),        /* segdir.root */
146033           &pCsr->apSegment[i]
146034       );
146035       pCsr->nSegment++;
146036     }
146037     rc2 = sqlite3_reset(pStmt);
146038     if( rc==SQLITE_OK ) rc = rc2;
146039   }
146040
146041   return rc;
146042 }
146043
146044 typedef struct IncrmergeWriter IncrmergeWriter;
146045 typedef struct NodeWriter NodeWriter;
146046 typedef struct Blob Blob;
146047 typedef struct NodeReader NodeReader;
146048
146049 /*
146050 ** An instance of the following structure is used as a dynamic buffer
146051 ** to build up nodes or other blobs of data in.
146052 **
146053 ** The function blobGrowBuffer() is used to extend the allocation.
146054 */
146055 struct Blob {
146056   char *a;                        /* Pointer to allocation */
146057   int n;                          /* Number of valid bytes of data in a[] */
146058   int nAlloc;                     /* Allocated size of a[] (nAlloc>=n) */
146059 };
146060
146061 /*
146062 ** This structure is used to build up buffers containing segment b-tree 
146063 ** nodes (blocks).
146064 */
146065 struct NodeWriter {
146066   sqlite3_int64 iBlock;           /* Current block id */
146067   Blob key;                       /* Last key written to the current block */
146068   Blob block;                     /* Current block image */
146069 };
146070
146071 /*
146072 ** An object of this type contains the state required to create or append
146073 ** to an appendable b-tree segment.
146074 */
146075 struct IncrmergeWriter {
146076   int nLeafEst;                   /* Space allocated for leaf blocks */
146077   int nWork;                      /* Number of leaf pages flushed */
146078   sqlite3_int64 iAbsLevel;        /* Absolute level of input segments */
146079   int iIdx;                       /* Index of *output* segment in iAbsLevel+1 */
146080   sqlite3_int64 iStart;           /* Block number of first allocated block */
146081   sqlite3_int64 iEnd;             /* Block number of last allocated block */
146082   sqlite3_int64 nLeafData;        /* Bytes of leaf page data so far */
146083   u8 bNoLeafData;                 /* If true, store 0 for segment size */
146084   NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
146085 };
146086
146087 /*
146088 ** An object of the following type is used to read data from a single
146089 ** FTS segment node. See the following functions:
146090 **
146091 **     nodeReaderInit()
146092 **     nodeReaderNext()
146093 **     nodeReaderRelease()
146094 */
146095 struct NodeReader {
146096   const char *aNode;
146097   int nNode;
146098   int iOff;                       /* Current offset within aNode[] */
146099
146100   /* Output variables. Containing the current node entry. */
146101   sqlite3_int64 iChild;           /* Pointer to child node */
146102   Blob term;                      /* Current term */
146103   const char *aDoclist;           /* Pointer to doclist */
146104   int nDoclist;                   /* Size of doclist in bytes */
146105 };
146106
146107 /*
146108 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
146109 ** Otherwise, if the allocation at pBlob->a is not already at least nMin
146110 ** bytes in size, extend (realloc) it to be so.
146111 **
146112 ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
146113 ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
146114 ** to reflect the new size of the pBlob->a[] buffer.
146115 */
146116 static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
146117   if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
146118     int nAlloc = nMin;
146119     char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
146120     if( a ){
146121       pBlob->nAlloc = nAlloc;
146122       pBlob->a = a;
146123     }else{
146124       *pRc = SQLITE_NOMEM;
146125     }
146126   }
146127 }
146128
146129 /*
146130 ** Attempt to advance the node-reader object passed as the first argument to
146131 ** the next entry on the node. 
146132 **
146133 ** Return an error code if an error occurs (SQLITE_NOMEM is possible). 
146134 ** Otherwise return SQLITE_OK. If there is no next entry on the node
146135 ** (e.g. because the current entry is the last) set NodeReader->aNode to
146136 ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output 
146137 ** variables for the new entry.
146138 */
146139 static int nodeReaderNext(NodeReader *p){
146140   int bFirst = (p->term.n==0);    /* True for first term on the node */
146141   int nPrefix = 0;                /* Bytes to copy from previous term */
146142   int nSuffix = 0;                /* Bytes to append to the prefix */
146143   int rc = SQLITE_OK;             /* Return code */
146144
146145   assert( p->aNode );
146146   if( p->iChild && bFirst==0 ) p->iChild++;
146147   if( p->iOff>=p->nNode ){
146148     /* EOF */
146149     p->aNode = 0;
146150   }else{
146151     if( bFirst==0 ){
146152       p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
146153     }
146154     p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
146155
146156     blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
146157     if( rc==SQLITE_OK ){
146158       memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
146159       p->term.n = nPrefix+nSuffix;
146160       p->iOff += nSuffix;
146161       if( p->iChild==0 ){
146162         p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
146163         p->aDoclist = &p->aNode[p->iOff];
146164         p->iOff += p->nDoclist;
146165       }
146166     }
146167   }
146168
146169   assert( p->iOff<=p->nNode );
146170
146171   return rc;
146172 }
146173
146174 /*
146175 ** Release all dynamic resources held by node-reader object *p.
146176 */
146177 static void nodeReaderRelease(NodeReader *p){
146178   sqlite3_free(p->term.a);
146179 }
146180
146181 /*
146182 ** Initialize a node-reader object to read the node in buffer aNode/nNode.
146183 **
146184 ** If successful, SQLITE_OK is returned and the NodeReader object set to 
146185 ** point to the first entry on the node (if any). Otherwise, an SQLite
146186 ** error code is returned.
146187 */
146188 static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
146189   memset(p, 0, sizeof(NodeReader));
146190   p->aNode = aNode;
146191   p->nNode = nNode;
146192
146193   /* Figure out if this is a leaf or an internal node. */
146194   if( p->aNode[0] ){
146195     /* An internal node. */
146196     p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
146197   }else{
146198     p->iOff = 1;
146199   }
146200
146201   return nodeReaderNext(p);
146202 }
146203
146204 /*
146205 ** This function is called while writing an FTS segment each time a leaf o
146206 ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
146207 ** to be greater than the largest key on the node just written, but smaller
146208 ** than or equal to the first key that will be written to the next leaf
146209 ** node.
146210 **
146211 ** The block id of the leaf node just written to disk may be found in
146212 ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
146213 */
146214 static int fts3IncrmergePush(
146215   Fts3Table *p,                   /* Fts3 table handle */
146216   IncrmergeWriter *pWriter,       /* Writer object */
146217   const char *zTerm,              /* Term to write to internal node */
146218   int nTerm                       /* Bytes at zTerm */
146219 ){
146220   sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
146221   int iLayer;
146222
146223   assert( nTerm>0 );
146224   for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
146225     sqlite3_int64 iNextPtr = 0;
146226     NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
146227     int rc = SQLITE_OK;
146228     int nPrefix;
146229     int nSuffix;
146230     int nSpace;
146231
146232     /* Figure out how much space the key will consume if it is written to
146233     ** the current node of layer iLayer. Due to the prefix compression, 
146234     ** the space required changes depending on which node the key is to
146235     ** be added to.  */
146236     nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
146237     nSuffix = nTerm - nPrefix;
146238     nSpace  = sqlite3Fts3VarintLen(nPrefix);
146239     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
146240
146241     if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){ 
146242       /* If the current node of layer iLayer contains zero keys, or if adding
146243       ** the key to it will not cause it to grow to larger than nNodeSize 
146244       ** bytes in size, write the key here.  */
146245
146246       Blob *pBlk = &pNode->block;
146247       if( pBlk->n==0 ){
146248         blobGrowBuffer(pBlk, p->nNodeSize, &rc);
146249         if( rc==SQLITE_OK ){
146250           pBlk->a[0] = (char)iLayer;
146251           pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
146252         }
146253       }
146254       blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
146255       blobGrowBuffer(&pNode->key, nTerm, &rc);
146256
146257       if( rc==SQLITE_OK ){
146258         if( pNode->key.n ){
146259           pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
146260         }
146261         pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
146262         memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
146263         pBlk->n += nSuffix;
146264
146265         memcpy(pNode->key.a, zTerm, nTerm);
146266         pNode->key.n = nTerm;
146267       }
146268     }else{
146269       /* Otherwise, flush the current node of layer iLayer to disk.
146270       ** Then allocate a new, empty sibling node. The key will be written
146271       ** into the parent of this node. */
146272       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
146273
146274       assert( pNode->block.nAlloc>=p->nNodeSize );
146275       pNode->block.a[0] = (char)iLayer;
146276       pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
146277
146278       iNextPtr = pNode->iBlock;
146279       pNode->iBlock++;
146280       pNode->key.n = 0;
146281     }
146282
146283     if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
146284     iPtr = iNextPtr;
146285   }
146286
146287   assert( 0 );
146288   return 0;
146289 }
146290
146291 /*
146292 ** Append a term and (optionally) doclist to the FTS segment node currently
146293 ** stored in blob *pNode. The node need not contain any terms, but the
146294 ** header must be written before this function is called.
146295 **
146296 ** A node header is a single 0x00 byte for a leaf node, or a height varint
146297 ** followed by the left-hand-child varint for an internal node.
146298 **
146299 ** The term to be appended is passed via arguments zTerm/nTerm. For a 
146300 ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
146301 ** node, both aDoclist and nDoclist must be passed 0.
146302 **
146303 ** If the size of the value in blob pPrev is zero, then this is the first
146304 ** term written to the node. Otherwise, pPrev contains a copy of the 
146305 ** previous term. Before this function returns, it is updated to contain a
146306 ** copy of zTerm/nTerm.
146307 **
146308 ** It is assumed that the buffer associated with pNode is already large
146309 ** enough to accommodate the new entry. The buffer associated with pPrev
146310 ** is extended by this function if requrired.
146311 **
146312 ** If an error (i.e. OOM condition) occurs, an SQLite error code is
146313 ** returned. Otherwise, SQLITE_OK.
146314 */
146315 static int fts3AppendToNode(
146316   Blob *pNode,                    /* Current node image to append to */
146317   Blob *pPrev,                    /* Buffer containing previous term written */
146318   const char *zTerm,              /* New term to write */
146319   int nTerm,                      /* Size of zTerm in bytes */
146320   const char *aDoclist,           /* Doclist (or NULL) to write */
146321   int nDoclist                    /* Size of aDoclist in bytes */ 
146322 ){
146323   int rc = SQLITE_OK;             /* Return code */
146324   int bFirst = (pPrev->n==0);     /* True if this is the first term written */
146325   int nPrefix;                    /* Size of term prefix in bytes */
146326   int nSuffix;                    /* Size of term suffix in bytes */
146327
146328   /* Node must have already been started. There must be a doclist for a
146329   ** leaf node, and there must not be a doclist for an internal node.  */
146330   assert( pNode->n>0 );
146331   assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
146332
146333   blobGrowBuffer(pPrev, nTerm, &rc);
146334   if( rc!=SQLITE_OK ) return rc;
146335
146336   nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
146337   nSuffix = nTerm - nPrefix;
146338   memcpy(pPrev->a, zTerm, nTerm);
146339   pPrev->n = nTerm;
146340
146341   if( bFirst==0 ){
146342     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
146343   }
146344   pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
146345   memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
146346   pNode->n += nSuffix;
146347
146348   if( aDoclist ){
146349     pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
146350     memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
146351     pNode->n += nDoclist;
146352   }
146353
146354   assert( pNode->n<=pNode->nAlloc );
146355
146356   return SQLITE_OK;
146357 }
146358
146359 /*
146360 ** Append the current term and doclist pointed to by cursor pCsr to the
146361 ** appendable b-tree segment opened for writing by pWriter.
146362 **
146363 ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
146364 */
146365 static int fts3IncrmergeAppend(
146366   Fts3Table *p,                   /* Fts3 table handle */
146367   IncrmergeWriter *pWriter,       /* Writer object */
146368   Fts3MultiSegReader *pCsr        /* Cursor containing term and doclist */
146369 ){
146370   const char *zTerm = pCsr->zTerm;
146371   int nTerm = pCsr->nTerm;
146372   const char *aDoclist = pCsr->aDoclist;
146373   int nDoclist = pCsr->nDoclist;
146374   int rc = SQLITE_OK;           /* Return code */
146375   int nSpace;                   /* Total space in bytes required on leaf */
146376   int nPrefix;                  /* Size of prefix shared with previous term */
146377   int nSuffix;                  /* Size of suffix (nTerm - nPrefix) */
146378   NodeWriter *pLeaf;            /* Object used to write leaf nodes */
146379
146380   pLeaf = &pWriter->aNodeWriter[0];
146381   nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
146382   nSuffix = nTerm - nPrefix;
146383
146384   nSpace  = sqlite3Fts3VarintLen(nPrefix);
146385   nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
146386   nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
146387
146388   /* If the current block is not empty, and if adding this term/doclist
146389   ** to the current block would make it larger than Fts3Table.nNodeSize
146390   ** bytes, write this block out to the database. */
146391   if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
146392     rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
146393     pWriter->nWork++;
146394
146395     /* Add the current term to the parent node. The term added to the 
146396     ** parent must:
146397     **
146398     **   a) be greater than the largest term on the leaf node just written
146399     **      to the database (still available in pLeaf->key), and
146400     **
146401     **   b) be less than or equal to the term about to be added to the new
146402     **      leaf node (zTerm/nTerm).
146403     **
146404     ** In other words, it must be the prefix of zTerm 1 byte longer than
146405     ** the common prefix (if any) of zTerm and pWriter->zTerm.
146406     */
146407     if( rc==SQLITE_OK ){
146408       rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
146409     }
146410
146411     /* Advance to the next output block */
146412     pLeaf->iBlock++;
146413     pLeaf->key.n = 0;
146414     pLeaf->block.n = 0;
146415
146416     nSuffix = nTerm;
146417     nSpace  = 1;
146418     nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
146419     nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
146420   }
146421
146422   pWriter->nLeafData += nSpace;
146423   blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
146424   if( rc==SQLITE_OK ){
146425     if( pLeaf->block.n==0 ){
146426       pLeaf->block.n = 1;
146427       pLeaf->block.a[0] = '\0';
146428     }
146429     rc = fts3AppendToNode(
146430         &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
146431     );
146432   }
146433
146434   return rc;
146435 }
146436
146437 /*
146438 ** This function is called to release all dynamic resources held by the
146439 ** merge-writer object pWriter, and if no error has occurred, to flush
146440 ** all outstanding node buffers held by pWriter to disk.
146441 **
146442 ** If *pRc is not SQLITE_OK when this function is called, then no attempt
146443 ** is made to write any data to disk. Instead, this function serves only
146444 ** to release outstanding resources.
146445 **
146446 ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
146447 ** flushing buffers to disk, *pRc is set to an SQLite error code before
146448 ** returning.
146449 */
146450 static void fts3IncrmergeRelease(
146451   Fts3Table *p,                   /* FTS3 table handle */
146452   IncrmergeWriter *pWriter,       /* Merge-writer object */
146453   int *pRc                        /* IN/OUT: Error code */
146454 ){
146455   int i;                          /* Used to iterate through non-root layers */
146456   int iRoot;                      /* Index of root in pWriter->aNodeWriter */
146457   NodeWriter *pRoot;              /* NodeWriter for root node */
146458   int rc = *pRc;                  /* Error code */
146459
146460   /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment 
146461   ** root node. If the segment fits entirely on a single leaf node, iRoot
146462   ** will be set to 0. If the root node is the parent of the leaves, iRoot
146463   ** will be 1. And so on.  */
146464   for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
146465     NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
146466     if( pNode->block.n>0 ) break;
146467     assert( *pRc || pNode->block.nAlloc==0 );
146468     assert( *pRc || pNode->key.nAlloc==0 );
146469     sqlite3_free(pNode->block.a);
146470     sqlite3_free(pNode->key.a);
146471   }
146472
146473   /* Empty output segment. This is a no-op. */
146474   if( iRoot<0 ) return;
146475
146476   /* The entire output segment fits on a single node. Normally, this means
146477   ** the node would be stored as a blob in the "root" column of the %_segdir
146478   ** table. However, this is not permitted in this case. The problem is that 
146479   ** space has already been reserved in the %_segments table, and so the 
146480   ** start_block and end_block fields of the %_segdir table must be populated. 
146481   ** And, by design or by accident, released versions of FTS cannot handle 
146482   ** segments that fit entirely on the root node with start_block!=0.
146483   **
146484   ** Instead, create a synthetic root node that contains nothing but a 
146485   ** pointer to the single content node. So that the segment consists of a
146486   ** single leaf and a single interior (root) node.
146487   **
146488   ** Todo: Better might be to defer allocating space in the %_segments 
146489   ** table until we are sure it is needed.
146490   */
146491   if( iRoot==0 ){
146492     Blob *pBlock = &pWriter->aNodeWriter[1].block;
146493     blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
146494     if( rc==SQLITE_OK ){
146495       pBlock->a[0] = 0x01;
146496       pBlock->n = 1 + sqlite3Fts3PutVarint(
146497           &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
146498       );
146499     }
146500     iRoot = 1;
146501   }
146502   pRoot = &pWriter->aNodeWriter[iRoot];
146503
146504   /* Flush all currently outstanding nodes to disk. */
146505   for(i=0; i<iRoot; i++){
146506     NodeWriter *pNode = &pWriter->aNodeWriter[i];
146507     if( pNode->block.n>0 && rc==SQLITE_OK ){
146508       rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
146509     }
146510     sqlite3_free(pNode->block.a);
146511     sqlite3_free(pNode->key.a);
146512   }
146513
146514   /* Write the %_segdir record. */
146515   if( rc==SQLITE_OK ){
146516     rc = fts3WriteSegdir(p, 
146517         pWriter->iAbsLevel+1,               /* level */
146518         pWriter->iIdx,                      /* idx */
146519         pWriter->iStart,                    /* start_block */
146520         pWriter->aNodeWriter[0].iBlock,     /* leaves_end_block */
146521         pWriter->iEnd,                      /* end_block */
146522         (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0),   /* end_block */
146523         pRoot->block.a, pRoot->block.n      /* root */
146524     );
146525   }
146526   sqlite3_free(pRoot->block.a);
146527   sqlite3_free(pRoot->key.a);
146528
146529   *pRc = rc;
146530 }
146531
146532 /*
146533 ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
146534 ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
146535 ** the other, it is considered to be smaller than the other.
146536 **
146537 ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
146538 ** if it is greater.
146539 */
146540 static int fts3TermCmp(
146541   const char *zLhs, int nLhs,     /* LHS of comparison */
146542   const char *zRhs, int nRhs      /* RHS of comparison */
146543 ){
146544   int nCmp = MIN(nLhs, nRhs);
146545   int res;
146546
146547   res = memcmp(zLhs, zRhs, nCmp);
146548   if( res==0 ) res = nLhs - nRhs;
146549
146550   return res;
146551 }
146552
146553
146554 /*
146555 ** Query to see if the entry in the %_segments table with blockid iEnd is 
146556 ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
146557 ** returning. Otherwise, set *pbRes to 0. 
146558 **
146559 ** Or, if an error occurs while querying the database, return an SQLite 
146560 ** error code. The final value of *pbRes is undefined in this case.
146561 **
146562 ** This is used to test if a segment is an "appendable" segment. If it
146563 ** is, then a NULL entry has been inserted into the %_segments table
146564 ** with blockid %_segdir.end_block.
146565 */
146566 static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
146567   int bRes = 0;                   /* Result to set *pbRes to */
146568   sqlite3_stmt *pCheck = 0;       /* Statement to query database with */
146569   int rc;                         /* Return code */
146570
146571   rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
146572   if( rc==SQLITE_OK ){
146573     sqlite3_bind_int64(pCheck, 1, iEnd);
146574     if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
146575     rc = sqlite3_reset(pCheck);
146576   }
146577   
146578   *pbRes = bRes;
146579   return rc;
146580 }
146581
146582 /*
146583 ** This function is called when initializing an incremental-merge operation.
146584 ** It checks if the existing segment with index value iIdx at absolute level 
146585 ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
146586 ** merge-writer object *pWriter is initialized to write to it.
146587 **
146588 ** An existing segment can be appended to by an incremental merge if:
146589 **
146590 **   * It was initially created as an appendable segment (with all required
146591 **     space pre-allocated), and
146592 **
146593 **   * The first key read from the input (arguments zKey and nKey) is 
146594 **     greater than the largest key currently stored in the potential
146595 **     output segment.
146596 */
146597 static int fts3IncrmergeLoad(
146598   Fts3Table *p,                   /* Fts3 table handle */
146599   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
146600   int iIdx,                       /* Index of candidate output segment */
146601   const char *zKey,               /* First key to write */
146602   int nKey,                       /* Number of bytes in nKey */
146603   IncrmergeWriter *pWriter        /* Populate this object */
146604 ){
146605   int rc;                         /* Return code */
146606   sqlite3_stmt *pSelect = 0;      /* SELECT to read %_segdir entry */
146607
146608   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
146609   if( rc==SQLITE_OK ){
146610     sqlite3_int64 iStart = 0;     /* Value of %_segdir.start_block */
146611     sqlite3_int64 iLeafEnd = 0;   /* Value of %_segdir.leaves_end_block */
146612     sqlite3_int64 iEnd = 0;       /* Value of %_segdir.end_block */
146613     const char *aRoot = 0;        /* Pointer to %_segdir.root buffer */
146614     int nRoot = 0;                /* Size of aRoot[] in bytes */
146615     int rc2;                      /* Return code from sqlite3_reset() */
146616     int bAppendable = 0;          /* Set to true if segment is appendable */
146617
146618     /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
146619     sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
146620     sqlite3_bind_int(pSelect, 2, iIdx);
146621     if( sqlite3_step(pSelect)==SQLITE_ROW ){
146622       iStart = sqlite3_column_int64(pSelect, 1);
146623       iLeafEnd = sqlite3_column_int64(pSelect, 2);
146624       fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
146625       if( pWriter->nLeafData<0 ){
146626         pWriter->nLeafData = pWriter->nLeafData * -1;
146627       }
146628       pWriter->bNoLeafData = (pWriter->nLeafData==0);
146629       nRoot = sqlite3_column_bytes(pSelect, 4);
146630       aRoot = sqlite3_column_blob(pSelect, 4);
146631     }else{
146632       return sqlite3_reset(pSelect);
146633     }
146634
146635     /* Check for the zero-length marker in the %_segments table */
146636     rc = fts3IsAppendable(p, iEnd, &bAppendable);
146637
146638     /* Check that zKey/nKey is larger than the largest key the candidate */
146639     if( rc==SQLITE_OK && bAppendable ){
146640       char *aLeaf = 0;
146641       int nLeaf = 0;
146642
146643       rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
146644       if( rc==SQLITE_OK ){
146645         NodeReader reader;
146646         for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
146647             rc==SQLITE_OK && reader.aNode;
146648             rc = nodeReaderNext(&reader)
146649         ){
146650           assert( reader.aNode );
146651         }
146652         if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
146653           bAppendable = 0;
146654         }
146655         nodeReaderRelease(&reader);
146656       }
146657       sqlite3_free(aLeaf);
146658     }
146659
146660     if( rc==SQLITE_OK && bAppendable ){
146661       /* It is possible to append to this segment. Set up the IncrmergeWriter
146662       ** object to do so.  */
146663       int i;
146664       int nHeight = (int)aRoot[0];
146665       NodeWriter *pNode;
146666
146667       pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
146668       pWriter->iStart = iStart;
146669       pWriter->iEnd = iEnd;
146670       pWriter->iAbsLevel = iAbsLevel;
146671       pWriter->iIdx = iIdx;
146672
146673       for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
146674         pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
146675       }
146676
146677       pNode = &pWriter->aNodeWriter[nHeight];
146678       pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
146679       blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
146680       if( rc==SQLITE_OK ){
146681         memcpy(pNode->block.a, aRoot, nRoot);
146682         pNode->block.n = nRoot;
146683       }
146684
146685       for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
146686         NodeReader reader;
146687         pNode = &pWriter->aNodeWriter[i];
146688
146689         rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
146690         while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
146691         blobGrowBuffer(&pNode->key, reader.term.n, &rc);
146692         if( rc==SQLITE_OK ){
146693           memcpy(pNode->key.a, reader.term.a, reader.term.n);
146694           pNode->key.n = reader.term.n;
146695           if( i>0 ){
146696             char *aBlock = 0;
146697             int nBlock = 0;
146698             pNode = &pWriter->aNodeWriter[i-1];
146699             pNode->iBlock = reader.iChild;
146700             rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
146701             blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
146702             if( rc==SQLITE_OK ){
146703               memcpy(pNode->block.a, aBlock, nBlock);
146704               pNode->block.n = nBlock;
146705             }
146706             sqlite3_free(aBlock);
146707           }
146708         }
146709         nodeReaderRelease(&reader);
146710       }
146711     }
146712
146713     rc2 = sqlite3_reset(pSelect);
146714     if( rc==SQLITE_OK ) rc = rc2;
146715   }
146716
146717   return rc;
146718 }
146719
146720 /*
146721 ** Determine the largest segment index value that exists within absolute
146722 ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
146723 ** one before returning SQLITE_OK. Or, if there are no segments at all 
146724 ** within level iAbsLevel, set *piIdx to zero.
146725 **
146726 ** If an error occurs, return an SQLite error code. The final value of
146727 ** *piIdx is undefined in this case.
146728 */
146729 static int fts3IncrmergeOutputIdx( 
146730   Fts3Table *p,                   /* FTS Table handle */
146731   sqlite3_int64 iAbsLevel,        /* Absolute index of input segments */
146732   int *piIdx                      /* OUT: Next free index at iAbsLevel+1 */
146733 ){
146734   int rc;
146735   sqlite3_stmt *pOutputIdx = 0;   /* SQL used to find output index */
146736
146737   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
146738   if( rc==SQLITE_OK ){
146739     sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
146740     sqlite3_step(pOutputIdx);
146741     *piIdx = sqlite3_column_int(pOutputIdx, 0);
146742     rc = sqlite3_reset(pOutputIdx);
146743   }
146744
146745   return rc;
146746 }
146747
146748 /* 
146749 ** Allocate an appendable output segment on absolute level iAbsLevel+1
146750 ** with idx value iIdx.
146751 **
146752 ** In the %_segdir table, a segment is defined by the values in three
146753 ** columns:
146754 **
146755 **     start_block
146756 **     leaves_end_block
146757 **     end_block
146758 **
146759 ** When an appendable segment is allocated, it is estimated that the
146760 ** maximum number of leaf blocks that may be required is the sum of the
146761 ** number of leaf blocks consumed by the input segments, plus the number
146762 ** of input segments, multiplied by two. This value is stored in stack 
146763 ** variable nLeafEst.
146764 **
146765 ** A total of 16*nLeafEst blocks are allocated when an appendable segment
146766 ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
146767 ** array of leaf nodes starts at the first block allocated. The array
146768 ** of interior nodes that are parents of the leaf nodes start at block
146769 ** (start_block + (1 + end_block - start_block) / 16). And so on.
146770 **
146771 ** In the actual code below, the value "16" is replaced with the 
146772 ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
146773 */
146774 static int fts3IncrmergeWriter( 
146775   Fts3Table *p,                   /* Fts3 table handle */
146776   sqlite3_int64 iAbsLevel,        /* Absolute level of input segments */
146777   int iIdx,                       /* Index of new output segment */
146778   Fts3MultiSegReader *pCsr,       /* Cursor that data will be read from */
146779   IncrmergeWriter *pWriter        /* Populate this object */
146780 ){
146781   int rc;                         /* Return Code */
146782   int i;                          /* Iterator variable */
146783   int nLeafEst = 0;               /* Blocks allocated for leaf nodes */
146784   sqlite3_stmt *pLeafEst = 0;     /* SQL used to determine nLeafEst */
146785   sqlite3_stmt *pFirstBlock = 0;  /* SQL used to determine first block */
146786
146787   /* Calculate nLeafEst. */
146788   rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
146789   if( rc==SQLITE_OK ){
146790     sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
146791     sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
146792     if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
146793       nLeafEst = sqlite3_column_int(pLeafEst, 0);
146794     }
146795     rc = sqlite3_reset(pLeafEst);
146796   }
146797   if( rc!=SQLITE_OK ) return rc;
146798
146799   /* Calculate the first block to use in the output segment */
146800   rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
146801   if( rc==SQLITE_OK ){
146802     if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
146803       pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
146804       pWriter->iEnd = pWriter->iStart - 1;
146805       pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
146806     }
146807     rc = sqlite3_reset(pFirstBlock);
146808   }
146809   if( rc!=SQLITE_OK ) return rc;
146810
146811   /* Insert the marker in the %_segments table to make sure nobody tries
146812   ** to steal the space just allocated. This is also used to identify 
146813   ** appendable segments.  */
146814   rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
146815   if( rc!=SQLITE_OK ) return rc;
146816
146817   pWriter->iAbsLevel = iAbsLevel;
146818   pWriter->nLeafEst = nLeafEst;
146819   pWriter->iIdx = iIdx;
146820
146821   /* Set up the array of NodeWriter objects */
146822   for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
146823     pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
146824   }
146825   return SQLITE_OK;
146826 }
146827
146828 /*
146829 ** Remove an entry from the %_segdir table. This involves running the 
146830 ** following two statements:
146831 **
146832 **   DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
146833 **   UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
146834 **
146835 ** The DELETE statement removes the specific %_segdir level. The UPDATE 
146836 ** statement ensures that the remaining segments have contiguously allocated
146837 ** idx values.
146838 */
146839 static int fts3RemoveSegdirEntry(
146840   Fts3Table *p,                   /* FTS3 table handle */
146841   sqlite3_int64 iAbsLevel,        /* Absolute level to delete from */
146842   int iIdx                        /* Index of %_segdir entry to delete */
146843 ){
146844   int rc;                         /* Return code */
146845   sqlite3_stmt *pDelete = 0;      /* DELETE statement */
146846
146847   rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
146848   if( rc==SQLITE_OK ){
146849     sqlite3_bind_int64(pDelete, 1, iAbsLevel);
146850     sqlite3_bind_int(pDelete, 2, iIdx);
146851     sqlite3_step(pDelete);
146852     rc = sqlite3_reset(pDelete);
146853   }
146854
146855   return rc;
146856 }
146857
146858 /*
146859 ** One or more segments have just been removed from absolute level iAbsLevel.
146860 ** Update the 'idx' values of the remaining segments in the level so that
146861 ** the idx values are a contiguous sequence starting from 0.
146862 */
146863 static int fts3RepackSegdirLevel(
146864   Fts3Table *p,                   /* FTS3 table handle */
146865   sqlite3_int64 iAbsLevel         /* Absolute level to repack */
146866 ){
146867   int rc;                         /* Return code */
146868   int *aIdx = 0;                  /* Array of remaining idx values */
146869   int nIdx = 0;                   /* Valid entries in aIdx[] */
146870   int nAlloc = 0;                 /* Allocated size of aIdx[] */
146871   int i;                          /* Iterator variable */
146872   sqlite3_stmt *pSelect = 0;      /* Select statement to read idx values */
146873   sqlite3_stmt *pUpdate = 0;      /* Update statement to modify idx values */
146874
146875   rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
146876   if( rc==SQLITE_OK ){
146877     int rc2;
146878     sqlite3_bind_int64(pSelect, 1, iAbsLevel);
146879     while( SQLITE_ROW==sqlite3_step(pSelect) ){
146880       if( nIdx>=nAlloc ){
146881         int *aNew;
146882         nAlloc += 16;
146883         aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
146884         if( !aNew ){
146885           rc = SQLITE_NOMEM;
146886           break;
146887         }
146888         aIdx = aNew;
146889       }
146890       aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
146891     }
146892     rc2 = sqlite3_reset(pSelect);
146893     if( rc==SQLITE_OK ) rc = rc2;
146894   }
146895
146896   if( rc==SQLITE_OK ){
146897     rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
146898   }
146899   if( rc==SQLITE_OK ){
146900     sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
146901   }
146902
146903   assert( p->bIgnoreSavepoint==0 );
146904   p->bIgnoreSavepoint = 1;
146905   for(i=0; rc==SQLITE_OK && i<nIdx; i++){
146906     if( aIdx[i]!=i ){
146907       sqlite3_bind_int(pUpdate, 3, aIdx[i]);
146908       sqlite3_bind_int(pUpdate, 1, i);
146909       sqlite3_step(pUpdate);
146910       rc = sqlite3_reset(pUpdate);
146911     }
146912   }
146913   p->bIgnoreSavepoint = 0;
146914
146915   sqlite3_free(aIdx);
146916   return rc;
146917 }
146918
146919 static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
146920   pNode->a[0] = (char)iHeight;
146921   if( iChild ){
146922     assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
146923     pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
146924   }else{
146925     assert( pNode->nAlloc>=1 );
146926     pNode->n = 1;
146927   }
146928 }
146929
146930 /*
146931 ** The first two arguments are a pointer to and the size of a segment b-tree
146932 ** node. The node may be a leaf or an internal node.
146933 **
146934 ** This function creates a new node image in blob object *pNew by copying
146935 ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
146936 ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
146937 */
146938 static int fts3TruncateNode(
146939   const char *aNode,              /* Current node image */
146940   int nNode,                      /* Size of aNode in bytes */
146941   Blob *pNew,                     /* OUT: Write new node image here */
146942   const char *zTerm,              /* Omit all terms smaller than this */
146943   int nTerm,                      /* Size of zTerm in bytes */
146944   sqlite3_int64 *piBlock          /* OUT: Block number in next layer down */
146945 ){
146946   NodeReader reader;              /* Reader object */
146947   Blob prev = {0, 0, 0};          /* Previous term written to new node */
146948   int rc = SQLITE_OK;             /* Return code */
146949   int bLeaf = aNode[0]=='\0';     /* True for a leaf node */
146950
146951   /* Allocate required output space */
146952   blobGrowBuffer(pNew, nNode, &rc);
146953   if( rc!=SQLITE_OK ) return rc;
146954   pNew->n = 0;
146955
146956   /* Populate new node buffer */
146957   for(rc = nodeReaderInit(&reader, aNode, nNode); 
146958       rc==SQLITE_OK && reader.aNode; 
146959       rc = nodeReaderNext(&reader)
146960   ){
146961     if( pNew->n==0 ){
146962       int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
146963       if( res<0 || (bLeaf==0 && res==0) ) continue;
146964       fts3StartNode(pNew, (int)aNode[0], reader.iChild);
146965       *piBlock = reader.iChild;
146966     }
146967     rc = fts3AppendToNode(
146968         pNew, &prev, reader.term.a, reader.term.n,
146969         reader.aDoclist, reader.nDoclist
146970     );
146971     if( rc!=SQLITE_OK ) break;
146972   }
146973   if( pNew->n==0 ){
146974     fts3StartNode(pNew, (int)aNode[0], reader.iChild);
146975     *piBlock = reader.iChild;
146976   }
146977   assert( pNew->n<=pNew->nAlloc );
146978
146979   nodeReaderRelease(&reader);
146980   sqlite3_free(prev.a);
146981   return rc;
146982 }
146983
146984 /*
146985 ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute 
146986 ** level iAbsLevel. This may involve deleting entries from the %_segments
146987 ** table, and modifying existing entries in both the %_segments and %_segdir
146988 ** tables.
146989 **
146990 ** SQLITE_OK is returned if the segment is updated successfully. Or an
146991 ** SQLite error code otherwise.
146992 */
146993 static int fts3TruncateSegment(
146994   Fts3Table *p,                   /* FTS3 table handle */
146995   sqlite3_int64 iAbsLevel,        /* Absolute level of segment to modify */
146996   int iIdx,                       /* Index within level of segment to modify */
146997   const char *zTerm,              /* Remove terms smaller than this */
146998   int nTerm                      /* Number of bytes in buffer zTerm */
146999 ){
147000   int rc = SQLITE_OK;             /* Return code */
147001   Blob root = {0,0,0};            /* New root page image */
147002   Blob block = {0,0,0};           /* Buffer used for any other block */
147003   sqlite3_int64 iBlock = 0;       /* Block id */
147004   sqlite3_int64 iNewStart = 0;    /* New value for iStartBlock */
147005   sqlite3_int64 iOldStart = 0;    /* Old value for iStartBlock */
147006   sqlite3_stmt *pFetch = 0;       /* Statement used to fetch segdir */
147007
147008   rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
147009   if( rc==SQLITE_OK ){
147010     int rc2;                      /* sqlite3_reset() return code */
147011     sqlite3_bind_int64(pFetch, 1, iAbsLevel);
147012     sqlite3_bind_int(pFetch, 2, iIdx);
147013     if( SQLITE_ROW==sqlite3_step(pFetch) ){
147014       const char *aRoot = sqlite3_column_blob(pFetch, 4);
147015       int nRoot = sqlite3_column_bytes(pFetch, 4);
147016       iOldStart = sqlite3_column_int64(pFetch, 1);
147017       rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
147018     }
147019     rc2 = sqlite3_reset(pFetch);
147020     if( rc==SQLITE_OK ) rc = rc2;
147021   }
147022
147023   while( rc==SQLITE_OK && iBlock ){
147024     char *aBlock = 0;
147025     int nBlock = 0;
147026     iNewStart = iBlock;
147027
147028     rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
147029     if( rc==SQLITE_OK ){
147030       rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
147031     }
147032     if( rc==SQLITE_OK ){
147033       rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
147034     }
147035     sqlite3_free(aBlock);
147036   }
147037
147038   /* Variable iNewStart now contains the first valid leaf node. */
147039   if( rc==SQLITE_OK && iNewStart ){
147040     sqlite3_stmt *pDel = 0;
147041     rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
147042     if( rc==SQLITE_OK ){
147043       sqlite3_bind_int64(pDel, 1, iOldStart);
147044       sqlite3_bind_int64(pDel, 2, iNewStart-1);
147045       sqlite3_step(pDel);
147046       rc = sqlite3_reset(pDel);
147047     }
147048   }
147049
147050   if( rc==SQLITE_OK ){
147051     sqlite3_stmt *pChomp = 0;
147052     rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
147053     if( rc==SQLITE_OK ){
147054       sqlite3_bind_int64(pChomp, 1, iNewStart);
147055       sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
147056       sqlite3_bind_int64(pChomp, 3, iAbsLevel);
147057       sqlite3_bind_int(pChomp, 4, iIdx);
147058       sqlite3_step(pChomp);
147059       rc = sqlite3_reset(pChomp);
147060     }
147061   }
147062
147063   sqlite3_free(root.a);
147064   sqlite3_free(block.a);
147065   return rc;
147066 }
147067
147068 /*
147069 ** This function is called after an incrmental-merge operation has run to
147070 ** merge (or partially merge) two or more segments from absolute level
147071 ** iAbsLevel.
147072 **
147073 ** Each input segment is either removed from the db completely (if all of
147074 ** its data was copied to the output segment by the incrmerge operation)
147075 ** or modified in place so that it no longer contains those entries that
147076 ** have been duplicated in the output segment.
147077 */
147078 static int fts3IncrmergeChomp(
147079   Fts3Table *p,                   /* FTS table handle */
147080   sqlite3_int64 iAbsLevel,        /* Absolute level containing segments */
147081   Fts3MultiSegReader *pCsr,       /* Chomp all segments opened by this cursor */
147082   int *pnRem                      /* Number of segments not deleted */
147083 ){
147084   int i;
147085   int nRem = 0;
147086   int rc = SQLITE_OK;
147087
147088   for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
147089     Fts3SegReader *pSeg = 0;
147090     int j;
147091
147092     /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
147093     ** somewhere in the pCsr->apSegment[] array.  */
147094     for(j=0; ALWAYS(j<pCsr->nSegment); j++){
147095       pSeg = pCsr->apSegment[j];
147096       if( pSeg->iIdx==i ) break;
147097     }
147098     assert( j<pCsr->nSegment && pSeg->iIdx==i );
147099
147100     if( pSeg->aNode==0 ){
147101       /* Seg-reader is at EOF. Remove the entire input segment. */
147102       rc = fts3DeleteSegment(p, pSeg);
147103       if( rc==SQLITE_OK ){
147104         rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
147105       }
147106       *pnRem = 0;
147107     }else{
147108       /* The incremental merge did not copy all the data from this 
147109       ** segment to the upper level. The segment is modified in place
147110       ** so that it contains no keys smaller than zTerm/nTerm. */ 
147111       const char *zTerm = pSeg->zTerm;
147112       int nTerm = pSeg->nTerm;
147113       rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
147114       nRem++;
147115     }
147116   }
147117
147118   if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
147119     rc = fts3RepackSegdirLevel(p, iAbsLevel);
147120   }
147121
147122   *pnRem = nRem;
147123   return rc;
147124 }
147125
147126 /*
147127 ** Store an incr-merge hint in the database.
147128 */
147129 static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
147130   sqlite3_stmt *pReplace = 0;
147131   int rc;                         /* Return code */
147132
147133   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
147134   if( rc==SQLITE_OK ){
147135     sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
147136     sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
147137     sqlite3_step(pReplace);
147138     rc = sqlite3_reset(pReplace);
147139   }
147140
147141   return rc;
147142 }
147143
147144 /*
147145 ** Load an incr-merge hint from the database. The incr-merge hint, if one 
147146 ** exists, is stored in the rowid==1 row of the %_stat table.
147147 **
147148 ** If successful, populate blob *pHint with the value read from the %_stat
147149 ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
147150 ** SQLite error code.
147151 */
147152 static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
147153   sqlite3_stmt *pSelect = 0;
147154   int rc;
147155
147156   pHint->n = 0;
147157   rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
147158   if( rc==SQLITE_OK ){
147159     int rc2;
147160     sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
147161     if( SQLITE_ROW==sqlite3_step(pSelect) ){
147162       const char *aHint = sqlite3_column_blob(pSelect, 0);
147163       int nHint = sqlite3_column_bytes(pSelect, 0);
147164       if( aHint ){
147165         blobGrowBuffer(pHint, nHint, &rc);
147166         if( rc==SQLITE_OK ){
147167           memcpy(pHint->a, aHint, nHint);
147168           pHint->n = nHint;
147169         }
147170       }
147171     }
147172     rc2 = sqlite3_reset(pSelect);
147173     if( rc==SQLITE_OK ) rc = rc2;
147174   }
147175
147176   return rc;
147177 }
147178
147179 /*
147180 ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
147181 ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
147182 ** consists of two varints, the absolute level number of the input segments 
147183 ** and the number of input segments.
147184 **
147185 ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
147186 ** set *pRc to an SQLite error code before returning.
147187 */
147188 static void fts3IncrmergeHintPush(
147189   Blob *pHint,                    /* Hint blob to append to */
147190   i64 iAbsLevel,                  /* First varint to store in hint */
147191   int nInput,                     /* Second varint to store in hint */
147192   int *pRc                        /* IN/OUT: Error code */
147193 ){
147194   blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
147195   if( *pRc==SQLITE_OK ){
147196     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
147197     pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
147198   }
147199 }
147200
147201 /*
147202 ** Read the last entry (most recently pushed) from the hint blob *pHint
147203 ** and then remove the entry. Write the two values read to *piAbsLevel and 
147204 ** *pnInput before returning.
147205 **
147206 ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
147207 ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
147208 */
147209 static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
147210   const int nHint = pHint->n;
147211   int i;
147212
147213   i = pHint->n-2;
147214   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
147215   while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
147216
147217   pHint->n = i;
147218   i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
147219   i += fts3GetVarint32(&pHint->a[i], pnInput);
147220   if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
147221
147222   return SQLITE_OK;
147223 }
147224
147225
147226 /*
147227 ** Attempt an incremental merge that writes nMerge leaf blocks.
147228 **
147229 ** Incremental merges happen nMin segments at a time. The segments 
147230 ** to be merged are the nMin oldest segments (the ones with the smallest 
147231 ** values for the _segdir.idx field) in the highest level that contains 
147232 ** at least nMin segments. Multiple merges might occur in an attempt to 
147233 ** write the quota of nMerge leaf blocks.
147234 */
147235 SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
147236   int rc;                         /* Return code */
147237   int nRem = nMerge;              /* Number of leaf pages yet to  be written */
147238   Fts3MultiSegReader *pCsr;       /* Cursor used to read input data */
147239   Fts3SegFilter *pFilter;         /* Filter used with cursor pCsr */
147240   IncrmergeWriter *pWriter;       /* Writer object */
147241   int nSeg = 0;                   /* Number of input segments */
147242   sqlite3_int64 iAbsLevel = 0;    /* Absolute level number to work on */
147243   Blob hint = {0, 0, 0};          /* Hint read from %_stat table */
147244   int bDirtyHint = 0;             /* True if blob 'hint' has been modified */
147245
147246   /* Allocate space for the cursor, filter and writer objects */
147247   const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
147248   pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
147249   if( !pWriter ) return SQLITE_NOMEM;
147250   pFilter = (Fts3SegFilter *)&pWriter[1];
147251   pCsr = (Fts3MultiSegReader *)&pFilter[1];
147252
147253   rc = fts3IncrmergeHintLoad(p, &hint);
147254   while( rc==SQLITE_OK && nRem>0 ){
147255     const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
147256     sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
147257     int bUseHint = 0;             /* True if attempting to append */
147258     int iIdx = 0;                 /* Largest idx in level (iAbsLevel+1) */
147259
147260     /* Search the %_segdir table for the absolute level with the smallest
147261     ** relative level number that contains at least nMin segments, if any.
147262     ** If one is found, set iAbsLevel to the absolute level number and
147263     ** nSeg to nMin. If no level with at least nMin segments can be found, 
147264     ** set nSeg to -1.
147265     */
147266     rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
147267     sqlite3_bind_int(pFindLevel, 1, nMin);
147268     if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
147269       iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
147270       nSeg = nMin;
147271     }else{
147272       nSeg = -1;
147273     }
147274     rc = sqlite3_reset(pFindLevel);
147275
147276     /* If the hint read from the %_stat table is not empty, check if the
147277     ** last entry in it specifies a relative level smaller than or equal
147278     ** to the level identified by the block above (if any). If so, this 
147279     ** iteration of the loop will work on merging at the hinted level.
147280     */
147281     if( rc==SQLITE_OK && hint.n ){
147282       int nHint = hint.n;
147283       sqlite3_int64 iHintAbsLevel = 0;      /* Hint level */
147284       int nHintSeg = 0;                     /* Hint number of segments */
147285
147286       rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
147287       if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
147288         iAbsLevel = iHintAbsLevel;
147289         nSeg = nHintSeg;
147290         bUseHint = 1;
147291         bDirtyHint = 1;
147292       }else{
147293         /* This undoes the effect of the HintPop() above - so that no entry
147294         ** is removed from the hint blob.  */
147295         hint.n = nHint;
147296       }
147297     }
147298
147299     /* If nSeg is less that zero, then there is no level with at least
147300     ** nMin segments and no hint in the %_stat table. No work to do.
147301     ** Exit early in this case.  */
147302     if( nSeg<0 ) break;
147303
147304     /* Open a cursor to iterate through the contents of the oldest nSeg 
147305     ** indexes of absolute level iAbsLevel. If this cursor is opened using 
147306     ** the 'hint' parameters, it is possible that there are less than nSeg
147307     ** segments available in level iAbsLevel. In this case, no work is
147308     ** done on iAbsLevel - fall through to the next iteration of the loop 
147309     ** to start work on some other level.  */
147310     memset(pWriter, 0, nAlloc);
147311     pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
147312
147313     if( rc==SQLITE_OK ){
147314       rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
147315       assert( bUseHint==1 || bUseHint==0 );
147316       if( iIdx==0 || (bUseHint && iIdx==1) ){
147317         int bIgnore = 0;
147318         rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
147319         if( bIgnore ){
147320           pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
147321         }
147322       }
147323     }
147324
147325     if( rc==SQLITE_OK ){
147326       rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
147327     }
147328     if( SQLITE_OK==rc && pCsr->nSegment==nSeg
147329      && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
147330      && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
147331     ){
147332       if( bUseHint && iIdx>0 ){
147333         const char *zKey = pCsr->zTerm;
147334         int nKey = pCsr->nTerm;
147335         rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
147336       }else{
147337         rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
147338       }
147339
147340       if( rc==SQLITE_OK && pWriter->nLeafEst ){
147341         fts3LogMerge(nSeg, iAbsLevel);
147342         do {
147343           rc = fts3IncrmergeAppend(p, pWriter, pCsr);
147344           if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
147345           if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
147346         }while( rc==SQLITE_ROW );
147347
147348         /* Update or delete the input segments */
147349         if( rc==SQLITE_OK ){
147350           nRem -= (1 + pWriter->nWork);
147351           rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
147352           if( nSeg!=0 ){
147353             bDirtyHint = 1;
147354             fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
147355           }
147356         }
147357       }
147358
147359       if( nSeg!=0 ){
147360         pWriter->nLeafData = pWriter->nLeafData * -1;
147361       }
147362       fts3IncrmergeRelease(p, pWriter, &rc);
147363       if( nSeg==0 && pWriter->bNoLeafData==0 ){
147364         fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
147365       }
147366     }
147367
147368     sqlite3Fts3SegReaderFinish(pCsr);
147369   }
147370
147371   /* Write the hint values into the %_stat table for the next incr-merger */
147372   if( bDirtyHint && rc==SQLITE_OK ){
147373     rc = fts3IncrmergeHintStore(p, &hint);
147374   }
147375
147376   sqlite3_free(pWriter);
147377   sqlite3_free(hint.a);
147378   return rc;
147379 }
147380
147381 /*
147382 ** Convert the text beginning at *pz into an integer and return
147383 ** its value.  Advance *pz to point to the first character past
147384 ** the integer.
147385 */
147386 static int fts3Getint(const char **pz){
147387   const char *z = *pz;
147388   int i = 0;
147389   while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
147390   *pz = z;
147391   return i;
147392 }
147393
147394 /*
147395 ** Process statements of the form:
147396 **
147397 **    INSERT INTO table(table) VALUES('merge=A,B');
147398 **
147399 ** A and B are integers that decode to be the number of leaf pages
147400 ** written for the merge, and the minimum number of segments on a level
147401 ** before it will be selected for a merge, respectively.
147402 */
147403 static int fts3DoIncrmerge(
147404   Fts3Table *p,                   /* FTS3 table handle */
147405   const char *zParam              /* Nul-terminated string containing "A,B" */
147406 ){
147407   int rc;
147408   int nMin = (FTS3_MERGE_COUNT / 2);
147409   int nMerge = 0;
147410   const char *z = zParam;
147411
147412   /* Read the first integer value */
147413   nMerge = fts3Getint(&z);
147414
147415   /* If the first integer value is followed by a ',',  read the second
147416   ** integer value. */
147417   if( z[0]==',' && z[1]!='\0' ){
147418     z++;
147419     nMin = fts3Getint(&z);
147420   }
147421
147422   if( z[0]!='\0' || nMin<2 ){
147423     rc = SQLITE_ERROR;
147424   }else{
147425     rc = SQLITE_OK;
147426     if( !p->bHasStat ){
147427       assert( p->bFts4==0 );
147428       sqlite3Fts3CreateStatTable(&rc, p);
147429     }
147430     if( rc==SQLITE_OK ){
147431       rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
147432     }
147433     sqlite3Fts3SegmentsClose(p);
147434   }
147435   return rc;
147436 }
147437
147438 /*
147439 ** Process statements of the form:
147440 **
147441 **    INSERT INTO table(table) VALUES('automerge=X');
147442 **
147443 ** where X is an integer.  X==0 means to turn automerge off.  X!=0 means
147444 ** turn it on.  The setting is persistent.
147445 */
147446 static int fts3DoAutoincrmerge(
147447   Fts3Table *p,                   /* FTS3 table handle */
147448   const char *zParam              /* Nul-terminated string containing boolean */
147449 ){
147450   int rc = SQLITE_OK;
147451   sqlite3_stmt *pStmt = 0;
147452   p->nAutoincrmerge = fts3Getint(&zParam);
147453   if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
147454     p->nAutoincrmerge = 8;
147455   }
147456   if( !p->bHasStat ){
147457     assert( p->bFts4==0 );
147458     sqlite3Fts3CreateStatTable(&rc, p);
147459     if( rc ) return rc;
147460   }
147461   rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
147462   if( rc ) return rc;
147463   sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
147464   sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
147465   sqlite3_step(pStmt);
147466   rc = sqlite3_reset(pStmt);
147467   return rc;
147468 }
147469
147470 /*
147471 ** Return a 64-bit checksum for the FTS index entry specified by the
147472 ** arguments to this function.
147473 */
147474 static u64 fts3ChecksumEntry(
147475   const char *zTerm,              /* Pointer to buffer containing term */
147476   int nTerm,                      /* Size of zTerm in bytes */
147477   int iLangid,                    /* Language id for current row */
147478   int iIndex,                     /* Index (0..Fts3Table.nIndex-1) */
147479   i64 iDocid,                     /* Docid for current row. */
147480   int iCol,                       /* Column number */
147481   int iPos                        /* Position */
147482 ){
147483   int i;
147484   u64 ret = (u64)iDocid;
147485
147486   ret += (ret<<3) + iLangid;
147487   ret += (ret<<3) + iIndex;
147488   ret += (ret<<3) + iCol;
147489   ret += (ret<<3) + iPos;
147490   for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
147491
147492   return ret;
147493 }
147494
147495 /*
147496 ** Return a checksum of all entries in the FTS index that correspond to
147497 ** language id iLangid. The checksum is calculated by XORing the checksums
147498 ** of each individual entry (see fts3ChecksumEntry()) together.
147499 **
147500 ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
147501 ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
147502 ** return value is undefined in this case.
147503 */
147504 static u64 fts3ChecksumIndex(
147505   Fts3Table *p,                   /* FTS3 table handle */
147506   int iLangid,                    /* Language id to return cksum for */
147507   int iIndex,                     /* Index to cksum (0..p->nIndex-1) */
147508   int *pRc                        /* OUT: Return code */
147509 ){
147510   Fts3SegFilter filter;
147511   Fts3MultiSegReader csr;
147512   int rc;
147513   u64 cksum = 0;
147514
147515   assert( *pRc==SQLITE_OK );
147516
147517   memset(&filter, 0, sizeof(filter));
147518   memset(&csr, 0, sizeof(csr));
147519   filter.flags =  FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
147520   filter.flags |= FTS3_SEGMENT_SCAN;
147521
147522   rc = sqlite3Fts3SegReaderCursor(
147523       p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
147524   );
147525   if( rc==SQLITE_OK ){
147526     rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
147527   }
147528
147529   if( rc==SQLITE_OK ){
147530     while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
147531       char *pCsr = csr.aDoclist;
147532       char *pEnd = &pCsr[csr.nDoclist];
147533
147534       i64 iDocid = 0;
147535       i64 iCol = 0;
147536       i64 iPos = 0;
147537
147538       pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
147539       while( pCsr<pEnd ){
147540         i64 iVal = 0;
147541         pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
147542         if( pCsr<pEnd ){
147543           if( iVal==0 || iVal==1 ){
147544             iCol = 0;
147545             iPos = 0;
147546             if( iVal ){
147547               pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
147548             }else{
147549               pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
147550               iDocid += iVal;
147551             }
147552           }else{
147553             iPos += (iVal - 2);
147554             cksum = cksum ^ fts3ChecksumEntry(
147555                 csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
147556                 (int)iCol, (int)iPos
147557             );
147558           }
147559         }
147560       }
147561     }
147562   }
147563   sqlite3Fts3SegReaderFinish(&csr);
147564
147565   *pRc = rc;
147566   return cksum;
147567 }
147568
147569 /*
147570 ** Check if the contents of the FTS index match the current contents of the
147571 ** content table. If no error occurs and the contents do match, set *pbOk
147572 ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
147573 ** to false before returning.
147574 **
147575 ** If an error occurs (e.g. an OOM or IO error), return an SQLite error 
147576 ** code. The final value of *pbOk is undefined in this case.
147577 */
147578 static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
147579   int rc = SQLITE_OK;             /* Return code */
147580   u64 cksum1 = 0;                 /* Checksum based on FTS index contents */
147581   u64 cksum2 = 0;                 /* Checksum based on %_content contents */
147582   sqlite3_stmt *pAllLangid = 0;   /* Statement to return all language-ids */
147583
147584   /* This block calculates the checksum according to the FTS index. */
147585   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
147586   if( rc==SQLITE_OK ){
147587     int rc2;
147588     sqlite3_bind_int(pAllLangid, 1, p->nIndex);
147589     while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
147590       int iLangid = sqlite3_column_int(pAllLangid, 0);
147591       int i;
147592       for(i=0; i<p->nIndex; i++){
147593         cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
147594       }
147595     }
147596     rc2 = sqlite3_reset(pAllLangid);
147597     if( rc==SQLITE_OK ) rc = rc2;
147598   }
147599
147600   /* This block calculates the checksum according to the %_content table */
147601   rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
147602   if( rc==SQLITE_OK ){
147603     sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
147604     sqlite3_stmt *pStmt = 0;
147605     char *zSql;
147606    
147607     zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
147608     if( !zSql ){
147609       rc = SQLITE_NOMEM;
147610     }else{
147611       rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
147612       sqlite3_free(zSql);
147613     }
147614
147615     while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
147616       i64 iDocid = sqlite3_column_int64(pStmt, 0);
147617       int iLang = langidFromSelect(p, pStmt);
147618       int iCol;
147619
147620       for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
147621         if( p->abNotindexed[iCol]==0 ){
147622           const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
147623           int nText = sqlite3_column_bytes(pStmt, iCol+1);
147624           sqlite3_tokenizer_cursor *pT = 0;
147625
147626           rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
147627           while( rc==SQLITE_OK ){
147628             char const *zToken;       /* Buffer containing token */
147629             int nToken = 0;           /* Number of bytes in token */
147630             int iDum1 = 0, iDum2 = 0; /* Dummy variables */
147631             int iPos = 0;             /* Position of token in zText */
147632
147633             rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
147634             if( rc==SQLITE_OK ){
147635               int i;
147636               cksum2 = cksum2 ^ fts3ChecksumEntry(
147637                   zToken, nToken, iLang, 0, iDocid, iCol, iPos
147638               );
147639               for(i=1; i<p->nIndex; i++){
147640                 if( p->aIndex[i].nPrefix<=nToken ){
147641                   cksum2 = cksum2 ^ fts3ChecksumEntry(
147642                       zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
147643                   );
147644                 }
147645               }
147646             }
147647           }
147648           if( pT ) pModule->xClose(pT);
147649           if( rc==SQLITE_DONE ) rc = SQLITE_OK;
147650         }
147651       }
147652     }
147653
147654     sqlite3_finalize(pStmt);
147655   }
147656
147657   *pbOk = (cksum1==cksum2);
147658   return rc;
147659 }
147660
147661 /*
147662 ** Run the integrity-check. If no error occurs and the current contents of
147663 ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
147664 ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
147665 **
147666 ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite 
147667 ** error code.
147668 **
147669 ** The integrity-check works as follows. For each token and indexed token
147670 ** prefix in the document set, a 64-bit checksum is calculated (by code
147671 ** in fts3ChecksumEntry()) based on the following:
147672 **
147673 **     + The index number (0 for the main index, 1 for the first prefix
147674 **       index etc.),
147675 **     + The token (or token prefix) text itself, 
147676 **     + The language-id of the row it appears in,
147677 **     + The docid of the row it appears in,
147678 **     + The column it appears in, and
147679 **     + The tokens position within that column.
147680 **
147681 ** The checksums for all entries in the index are XORed together to create
147682 ** a single checksum for the entire index.
147683 **
147684 ** The integrity-check code calculates the same checksum in two ways:
147685 **
147686 **     1. By scanning the contents of the FTS index, and 
147687 **     2. By scanning and tokenizing the content table.
147688 **
147689 ** If the two checksums are identical, the integrity-check is deemed to have
147690 ** passed.
147691 */
147692 static int fts3DoIntegrityCheck(
147693   Fts3Table *p                    /* FTS3 table handle */
147694 ){
147695   int rc;
147696   int bOk = 0;
147697   rc = fts3IntegrityCheck(p, &bOk);
147698   if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
147699   return rc;
147700 }
147701
147702 /*
147703 ** Handle a 'special' INSERT of the form:
147704 **
147705 **   "INSERT INTO tbl(tbl) VALUES(<expr>)"
147706 **
147707 ** Argument pVal contains the result of <expr>. Currently the only 
147708 ** meaningful value to insert is the text 'optimize'.
147709 */
147710 static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
147711   int rc;                         /* Return Code */
147712   const char *zVal = (const char *)sqlite3_value_text(pVal);
147713   int nVal = sqlite3_value_bytes(pVal);
147714
147715   if( !zVal ){
147716     return SQLITE_NOMEM;
147717   }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
147718     rc = fts3DoOptimize(p, 0);
147719   }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
147720     rc = fts3DoRebuild(p);
147721   }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
147722     rc = fts3DoIntegrityCheck(p);
147723   }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
147724     rc = fts3DoIncrmerge(p, &zVal[6]);
147725   }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
147726     rc = fts3DoAutoincrmerge(p, &zVal[10]);
147727 #ifdef SQLITE_TEST
147728   }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
147729     p->nNodeSize = atoi(&zVal[9]);
147730     rc = SQLITE_OK;
147731   }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
147732     p->nMaxPendingData = atoi(&zVal[11]);
147733     rc = SQLITE_OK;
147734   }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
147735     p->bNoIncrDoclist = atoi(&zVal[21]);
147736     rc = SQLITE_OK;
147737 #endif
147738   }else{
147739     rc = SQLITE_ERROR;
147740   }
147741
147742   return rc;
147743 }
147744
147745 #ifndef SQLITE_DISABLE_FTS4_DEFERRED
147746 /*
147747 ** Delete all cached deferred doclists. Deferred doclists are cached
147748 ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
147749 */
147750 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
147751   Fts3DeferredToken *pDef;
147752   for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
147753     fts3PendingListDelete(pDef->pList);
147754     pDef->pList = 0;
147755   }
147756 }
147757
147758 /*
147759 ** Free all entries in the pCsr->pDeffered list. Entries are added to 
147760 ** this list using sqlite3Fts3DeferToken().
147761 */
147762 SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
147763   Fts3DeferredToken *pDef;
147764   Fts3DeferredToken *pNext;
147765   for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
147766     pNext = pDef->pNext;
147767     fts3PendingListDelete(pDef->pList);
147768     sqlite3_free(pDef);
147769   }
147770   pCsr->pDeferred = 0;
147771 }
147772
147773 /*
147774 ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
147775 ** based on the row that pCsr currently points to.
147776 **
147777 ** A deferred-doclist is like any other doclist with position information
147778 ** included, except that it only contains entries for a single row of the
147779 ** table, not for all rows.
147780 */
147781 SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
147782   int rc = SQLITE_OK;             /* Return code */
147783   if( pCsr->pDeferred ){
147784     int i;                        /* Used to iterate through table columns */
147785     sqlite3_int64 iDocid;         /* Docid of the row pCsr points to */
147786     Fts3DeferredToken *pDef;      /* Used to iterate through deferred tokens */
147787   
147788     Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
147789     sqlite3_tokenizer *pT = p->pTokenizer;
147790     sqlite3_tokenizer_module const *pModule = pT->pModule;
147791    
147792     assert( pCsr->isRequireSeek==0 );
147793     iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
147794   
147795     for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
147796       if( p->abNotindexed[i]==0 ){
147797         const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
147798         sqlite3_tokenizer_cursor *pTC = 0;
147799
147800         rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
147801         while( rc==SQLITE_OK ){
147802           char const *zToken;       /* Buffer containing token */
147803           int nToken = 0;           /* Number of bytes in token */
147804           int iDum1 = 0, iDum2 = 0; /* Dummy variables */
147805           int iPos = 0;             /* Position of token in zText */
147806
147807           rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
147808           for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
147809             Fts3PhraseToken *pPT = pDef->pToken;
147810             if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
147811                 && (pPT->bFirst==0 || iPos==0)
147812                 && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
147813                 && (0==memcmp(zToken, pPT->z, pPT->n))
147814               ){
147815               fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
147816             }
147817           }
147818         }
147819         if( pTC ) pModule->xClose(pTC);
147820         if( rc==SQLITE_DONE ) rc = SQLITE_OK;
147821       }
147822     }
147823
147824     for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
147825       if( pDef->pList ){
147826         rc = fts3PendingListAppendVarint(&pDef->pList, 0);
147827       }
147828     }
147829   }
147830
147831   return rc;
147832 }
147833
147834 SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
147835   Fts3DeferredToken *p, 
147836   char **ppData, 
147837   int *pnData
147838 ){
147839   char *pRet;
147840   int nSkip;
147841   sqlite3_int64 dummy;
147842
147843   *ppData = 0;
147844   *pnData = 0;
147845
147846   if( p->pList==0 ){
147847     return SQLITE_OK;
147848   }
147849
147850   pRet = (char *)sqlite3_malloc(p->pList->nData);
147851   if( !pRet ) return SQLITE_NOMEM;
147852
147853   nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
147854   *pnData = p->pList->nData - nSkip;
147855   *ppData = pRet;
147856   
147857   memcpy(pRet, &p->pList->aData[nSkip], *pnData);
147858   return SQLITE_OK;
147859 }
147860
147861 /*
147862 ** Add an entry for token pToken to the pCsr->pDeferred list.
147863 */
147864 SQLITE_PRIVATE int sqlite3Fts3DeferToken(
147865   Fts3Cursor *pCsr,               /* Fts3 table cursor */
147866   Fts3PhraseToken *pToken,        /* Token to defer */
147867   int iCol                        /* Column that token must appear in (or -1) */
147868 ){
147869   Fts3DeferredToken *pDeferred;
147870   pDeferred = sqlite3_malloc(sizeof(*pDeferred));
147871   if( !pDeferred ){
147872     return SQLITE_NOMEM;
147873   }
147874   memset(pDeferred, 0, sizeof(*pDeferred));
147875   pDeferred->pToken = pToken;
147876   pDeferred->pNext = pCsr->pDeferred; 
147877   pDeferred->iCol = iCol;
147878   pCsr->pDeferred = pDeferred;
147879
147880   assert( pToken->pDeferred==0 );
147881   pToken->pDeferred = pDeferred;
147882
147883   return SQLITE_OK;
147884 }
147885 #endif
147886
147887 /*
147888 ** SQLite value pRowid contains the rowid of a row that may or may not be
147889 ** present in the FTS3 table. If it is, delete it and adjust the contents
147890 ** of subsiduary data structures accordingly.
147891 */
147892 static int fts3DeleteByRowid(
147893   Fts3Table *p, 
147894   sqlite3_value *pRowid, 
147895   int *pnChng,                    /* IN/OUT: Decrement if row is deleted */
147896   u32 *aSzDel
147897 ){
147898   int rc = SQLITE_OK;             /* Return code */
147899   int bFound = 0;                 /* True if *pRowid really is in the table */
147900
147901   fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
147902   if( bFound && rc==SQLITE_OK ){
147903     int isEmpty = 0;              /* Deleting *pRowid leaves the table empty */
147904     rc = fts3IsEmpty(p, pRowid, &isEmpty);
147905     if( rc==SQLITE_OK ){
147906       if( isEmpty ){
147907         /* Deleting this row means the whole table is empty. In this case
147908         ** delete the contents of all three tables and throw away any
147909         ** data in the pendingTerms hash table.  */
147910         rc = fts3DeleteAll(p, 1);
147911         *pnChng = 0;
147912         memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
147913       }else{
147914         *pnChng = *pnChng - 1;
147915         if( p->zContentTbl==0 ){
147916           fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
147917         }
147918         if( p->bHasDocsize ){
147919           fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
147920         }
147921       }
147922     }
147923   }
147924
147925   return rc;
147926 }
147927
147928 /*
147929 ** This function does the work for the xUpdate method of FTS3 virtual
147930 ** tables. The schema of the virtual table being:
147931 **
147932 **     CREATE TABLE <table name>( 
147933 **       <user columns>,
147934 **       <table name> HIDDEN, 
147935 **       docid HIDDEN, 
147936 **       <langid> HIDDEN
147937 **     );
147938 **
147939 ** 
147940 */
147941 SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
147942   sqlite3_vtab *pVtab,            /* FTS3 vtab object */
147943   int nArg,                       /* Size of argument array */
147944   sqlite3_value **apVal,          /* Array of arguments */
147945   sqlite_int64 *pRowid            /* OUT: The affected (or effected) rowid */
147946 ){
147947   Fts3Table *p = (Fts3Table *)pVtab;
147948   int rc = SQLITE_OK;             /* Return Code */
147949   int isRemove = 0;               /* True for an UPDATE or DELETE */
147950   u32 *aSzIns = 0;                /* Sizes of inserted documents */
147951   u32 *aSzDel = 0;                /* Sizes of deleted documents */
147952   int nChng = 0;                  /* Net change in number of documents */
147953   int bInsertDone = 0;
147954
147955   /* At this point it must be known if the %_stat table exists or not.
147956   ** So bHasStat may not be 2.  */
147957   assert( p->bHasStat==0 || p->bHasStat==1 );
147958
147959   assert( p->pSegments==0 );
147960   assert( 
147961       nArg==1                     /* DELETE operations */
147962    || nArg==(2 + p->nColumn + 3)  /* INSERT or UPDATE operations */
147963   );
147964
147965   /* Check for a "special" INSERT operation. One of the form:
147966   **
147967   **   INSERT INTO xyz(xyz) VALUES('command');
147968   */
147969   if( nArg>1 
147970    && sqlite3_value_type(apVal[0])==SQLITE_NULL 
147971    && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL 
147972   ){
147973     rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
147974     goto update_out;
147975   }
147976
147977   if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
147978     rc = SQLITE_CONSTRAINT;
147979     goto update_out;
147980   }
147981
147982   /* Allocate space to hold the change in document sizes */
147983   aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
147984   if( aSzDel==0 ){
147985     rc = SQLITE_NOMEM;
147986     goto update_out;
147987   }
147988   aSzIns = &aSzDel[p->nColumn+1];
147989   memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
147990
147991   rc = fts3Writelock(p);
147992   if( rc!=SQLITE_OK ) goto update_out;
147993
147994   /* If this is an INSERT operation, or an UPDATE that modifies the rowid
147995   ** value, then this operation requires constraint handling.
147996   **
147997   ** If the on-conflict mode is REPLACE, this means that the existing row
147998   ** should be deleted from the database before inserting the new row. Or,
147999   ** if the on-conflict mode is other than REPLACE, then this method must
148000   ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
148001   ** modify the database file.
148002   */
148003   if( nArg>1 && p->zContentTbl==0 ){
148004     /* Find the value object that holds the new rowid value. */
148005     sqlite3_value *pNewRowid = apVal[3+p->nColumn];
148006     if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
148007       pNewRowid = apVal[1];
148008     }
148009
148010     if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && ( 
148011         sqlite3_value_type(apVal[0])==SQLITE_NULL
148012      || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
148013     )){
148014       /* The new rowid is not NULL (in this case the rowid will be
148015       ** automatically assigned and there is no chance of a conflict), and 
148016       ** the statement is either an INSERT or an UPDATE that modifies the
148017       ** rowid column. So if the conflict mode is REPLACE, then delete any
148018       ** existing row with rowid=pNewRowid. 
148019       **
148020       ** Or, if the conflict mode is not REPLACE, insert the new record into 
148021       ** the %_content table. If we hit the duplicate rowid constraint (or any
148022       ** other error) while doing so, return immediately.
148023       **
148024       ** This branch may also run if pNewRowid contains a value that cannot
148025       ** be losslessly converted to an integer. In this case, the eventual 
148026       ** call to fts3InsertData() (either just below or further on in this
148027       ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is 
148028       ** invoked, it will delete zero rows (since no row will have
148029       ** docid=$pNewRowid if $pNewRowid is not an integer value).
148030       */
148031       if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
148032         rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
148033       }else{
148034         rc = fts3InsertData(p, apVal, pRowid);
148035         bInsertDone = 1;
148036       }
148037     }
148038   }
148039   if( rc!=SQLITE_OK ){
148040     goto update_out;
148041   }
148042
148043   /* If this is a DELETE or UPDATE operation, remove the old record. */
148044   if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
148045     assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
148046     rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
148047     isRemove = 1;
148048   }
148049   
148050   /* If this is an INSERT or UPDATE operation, insert the new record. */
148051   if( nArg>1 && rc==SQLITE_OK ){
148052     int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
148053     if( bInsertDone==0 ){
148054       rc = fts3InsertData(p, apVal, pRowid);
148055       if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
148056         rc = FTS_CORRUPT_VTAB;
148057       }
148058     }
148059     if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
148060       rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
148061     }
148062     if( rc==SQLITE_OK ){
148063       assert( p->iPrevDocid==*pRowid );
148064       rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
148065     }
148066     if( p->bHasDocsize ){
148067       fts3InsertDocsize(&rc, p, aSzIns);
148068     }
148069     nChng++;
148070   }
148071
148072   if( p->bFts4 ){
148073     fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
148074   }
148075
148076  update_out:
148077   sqlite3_free(aSzDel);
148078   sqlite3Fts3SegmentsClose(p);
148079   return rc;
148080 }
148081
148082 /* 
148083 ** Flush any data in the pending-terms hash table to disk. If successful,
148084 ** merge all segments in the database (including the new segment, if 
148085 ** there was any data to flush) into a single segment. 
148086 */
148087 SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
148088   int rc;
148089   rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
148090   if( rc==SQLITE_OK ){
148091     rc = fts3DoOptimize(p, 1);
148092     if( rc==SQLITE_OK || rc==SQLITE_DONE ){
148093       int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
148094       if( rc2!=SQLITE_OK ) rc = rc2;
148095     }else{
148096       sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
148097       sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
148098     }
148099   }
148100   sqlite3Fts3SegmentsClose(p);
148101   return rc;
148102 }
148103
148104 #endif
148105
148106 /************** End of fts3_write.c ******************************************/
148107 /************** Begin file fts3_snippet.c ************************************/
148108 /*
148109 ** 2009 Oct 23
148110 **
148111 ** The author disclaims copyright to this source code.  In place of
148112 ** a legal notice, here is a blessing:
148113 **
148114 **    May you do good and not evil.
148115 **    May you find forgiveness for yourself and forgive others.
148116 **    May you share freely, never taking more than you give.
148117 **
148118 ******************************************************************************
148119 */
148120
148121 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
148122
148123 /* #include <string.h> */
148124 /* #include <assert.h> */
148125
148126 /*
148127 ** Characters that may appear in the second argument to matchinfo().
148128 */
148129 #define FTS3_MATCHINFO_NPHRASE   'p'        /* 1 value */
148130 #define FTS3_MATCHINFO_NCOL      'c'        /* 1 value */
148131 #define FTS3_MATCHINFO_NDOC      'n'        /* 1 value */
148132 #define FTS3_MATCHINFO_AVGLENGTH 'a'        /* nCol values */
148133 #define FTS3_MATCHINFO_LENGTH    'l'        /* nCol values */
148134 #define FTS3_MATCHINFO_LCS       's'        /* nCol values */
148135 #define FTS3_MATCHINFO_HITS      'x'        /* 3*nCol*nPhrase values */
148136
148137 /*
148138 ** The default value for the second argument to matchinfo(). 
148139 */
148140 #define FTS3_MATCHINFO_DEFAULT   "pcx"
148141
148142
148143 /*
148144 ** Used as an fts3ExprIterate() context when loading phrase doclists to
148145 ** Fts3Expr.aDoclist[]/nDoclist.
148146 */
148147 typedef struct LoadDoclistCtx LoadDoclistCtx;
148148 struct LoadDoclistCtx {
148149   Fts3Cursor *pCsr;               /* FTS3 Cursor */
148150   int nPhrase;                    /* Number of phrases seen so far */
148151   int nToken;                     /* Number of tokens seen so far */
148152 };
148153
148154 /*
148155 ** The following types are used as part of the implementation of the 
148156 ** fts3BestSnippet() routine.
148157 */
148158 typedef struct SnippetIter SnippetIter;
148159 typedef struct SnippetPhrase SnippetPhrase;
148160 typedef struct SnippetFragment SnippetFragment;
148161
148162 struct SnippetIter {
148163   Fts3Cursor *pCsr;               /* Cursor snippet is being generated from */
148164   int iCol;                       /* Extract snippet from this column */
148165   int nSnippet;                   /* Requested snippet length (in tokens) */
148166   int nPhrase;                    /* Number of phrases in query */
148167   SnippetPhrase *aPhrase;         /* Array of size nPhrase */
148168   int iCurrent;                   /* First token of current snippet */
148169 };
148170
148171 struct SnippetPhrase {
148172   int nToken;                     /* Number of tokens in phrase */
148173   char *pList;                    /* Pointer to start of phrase position list */
148174   int iHead;                      /* Next value in position list */
148175   char *pHead;                    /* Position list data following iHead */
148176   int iTail;                      /* Next value in trailing position list */
148177   char *pTail;                    /* Position list data following iTail */
148178 };
148179
148180 struct SnippetFragment {
148181   int iCol;                       /* Column snippet is extracted from */
148182   int iPos;                       /* Index of first token in snippet */
148183   u64 covered;                    /* Mask of query phrases covered */
148184   u64 hlmask;                     /* Mask of snippet terms to highlight */
148185 };
148186
148187 /*
148188 ** This type is used as an fts3ExprIterate() context object while 
148189 ** accumulating the data returned by the matchinfo() function.
148190 */
148191 typedef struct MatchInfo MatchInfo;
148192 struct MatchInfo {
148193   Fts3Cursor *pCursor;            /* FTS3 Cursor */
148194   int nCol;                       /* Number of columns in table */
148195   int nPhrase;                    /* Number of matchable phrases in query */
148196   sqlite3_int64 nDoc;             /* Number of docs in database */
148197   u32 *aMatchinfo;                /* Pre-allocated buffer */
148198 };
148199
148200
148201
148202 /*
148203 ** The snippet() and offsets() functions both return text values. An instance
148204 ** of the following structure is used to accumulate those values while the
148205 ** functions are running. See fts3StringAppend() for details.
148206 */
148207 typedef struct StrBuffer StrBuffer;
148208 struct StrBuffer {
148209   char *z;                        /* Pointer to buffer containing string */
148210   int n;                          /* Length of z in bytes (excl. nul-term) */
148211   int nAlloc;                     /* Allocated size of buffer z in bytes */
148212 };
148213
148214
148215 /*
148216 ** This function is used to help iterate through a position-list. A position
148217 ** list is a list of unique integers, sorted from smallest to largest. Each
148218 ** element of the list is represented by an FTS3 varint that takes the value
148219 ** of the difference between the current element and the previous one plus
148220 ** two. For example, to store the position-list:
148221 **
148222 **     4 9 113
148223 **
148224 ** the three varints:
148225 **
148226 **     6 7 106
148227 **
148228 ** are encoded.
148229 **
148230 ** When this function is called, *pp points to the start of an element of
148231 ** the list. *piPos contains the value of the previous entry in the list.
148232 ** After it returns, *piPos contains the value of the next element of the
148233 ** list and *pp is advanced to the following varint.
148234 */
148235 static void fts3GetDeltaPosition(char **pp, int *piPos){
148236   int iVal;
148237   *pp += fts3GetVarint32(*pp, &iVal);
148238   *piPos += (iVal-2);
148239 }
148240
148241 /*
148242 ** Helper function for fts3ExprIterate() (see below).
148243 */
148244 static int fts3ExprIterate2(
148245   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
148246   int *piPhrase,                  /* Pointer to phrase counter */
148247   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
148248   void *pCtx                      /* Second argument to pass to callback */
148249 ){
148250   int rc;                         /* Return code */
148251   int eType = pExpr->eType;       /* Type of expression node pExpr */
148252
148253   if( eType!=FTSQUERY_PHRASE ){
148254     assert( pExpr->pLeft && pExpr->pRight );
148255     rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
148256     if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
148257       rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
148258     }
148259   }else{
148260     rc = x(pExpr, *piPhrase, pCtx);
148261     (*piPhrase)++;
148262   }
148263   return rc;
148264 }
148265
148266 /*
148267 ** Iterate through all phrase nodes in an FTS3 query, except those that
148268 ** are part of a sub-tree that is the right-hand-side of a NOT operator.
148269 ** For each phrase node found, the supplied callback function is invoked.
148270 **
148271 ** If the callback function returns anything other than SQLITE_OK, 
148272 ** the iteration is abandoned and the error code returned immediately.
148273 ** Otherwise, SQLITE_OK is returned after a callback has been made for
148274 ** all eligible phrase nodes.
148275 */
148276 static int fts3ExprIterate(
148277   Fts3Expr *pExpr,                /* Expression to iterate phrases of */
148278   int (*x)(Fts3Expr*,int,void*),  /* Callback function to invoke for phrases */
148279   void *pCtx                      /* Second argument to pass to callback */
148280 ){
148281   int iPhrase = 0;                /* Variable used as the phrase counter */
148282   return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
148283 }
148284
148285 /*
148286 ** This is an fts3ExprIterate() callback used while loading the doclists
148287 ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
148288 ** fts3ExprLoadDoclists().
148289 */
148290 static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
148291   int rc = SQLITE_OK;
148292   Fts3Phrase *pPhrase = pExpr->pPhrase;
148293   LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
148294
148295   UNUSED_PARAMETER(iPhrase);
148296
148297   p->nPhrase++;
148298   p->nToken += pPhrase->nToken;
148299
148300   return rc;
148301 }
148302
148303 /*
148304 ** Load the doclists for each phrase in the query associated with FTS3 cursor
148305 ** pCsr. 
148306 **
148307 ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable 
148308 ** phrases in the expression (all phrases except those directly or 
148309 ** indirectly descended from the right-hand-side of a NOT operator). If 
148310 ** pnToken is not NULL, then it is set to the number of tokens in all
148311 ** matchable phrases of the expression.
148312 */
148313 static int fts3ExprLoadDoclists(
148314   Fts3Cursor *pCsr,               /* Fts3 cursor for current query */
148315   int *pnPhrase,                  /* OUT: Number of phrases in query */
148316   int *pnToken                    /* OUT: Number of tokens in query */
148317 ){
148318   int rc;                         /* Return Code */
148319   LoadDoclistCtx sCtx = {0,0,0};  /* Context for fts3ExprIterate() */
148320   sCtx.pCsr = pCsr;
148321   rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
148322   if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
148323   if( pnToken ) *pnToken = sCtx.nToken;
148324   return rc;
148325 }
148326
148327 static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
148328   (*(int *)ctx)++;
148329   UNUSED_PARAMETER(pExpr);
148330   UNUSED_PARAMETER(iPhrase);
148331   return SQLITE_OK;
148332 }
148333 static int fts3ExprPhraseCount(Fts3Expr *pExpr){
148334   int nPhrase = 0;
148335   (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
148336   return nPhrase;
148337 }
148338
148339 /*
148340 ** Advance the position list iterator specified by the first two 
148341 ** arguments so that it points to the first element with a value greater
148342 ** than or equal to parameter iNext.
148343 */
148344 static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
148345   char *pIter = *ppIter;
148346   if( pIter ){
148347     int iIter = *piIter;
148348
148349     while( iIter<iNext ){
148350       if( 0==(*pIter & 0xFE) ){
148351         iIter = -1;
148352         pIter = 0;
148353         break;
148354       }
148355       fts3GetDeltaPosition(&pIter, &iIter);
148356     }
148357
148358     *piIter = iIter;
148359     *ppIter = pIter;
148360   }
148361 }
148362
148363 /*
148364 ** Advance the snippet iterator to the next candidate snippet.
148365 */
148366 static int fts3SnippetNextCandidate(SnippetIter *pIter){
148367   int i;                          /* Loop counter */
148368
148369   if( pIter->iCurrent<0 ){
148370     /* The SnippetIter object has just been initialized. The first snippet
148371     ** candidate always starts at offset 0 (even if this candidate has a
148372     ** score of 0.0).
148373     */
148374     pIter->iCurrent = 0;
148375
148376     /* Advance the 'head' iterator of each phrase to the first offset that
148377     ** is greater than or equal to (iNext+nSnippet).
148378     */
148379     for(i=0; i<pIter->nPhrase; i++){
148380       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
148381       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
148382     }
148383   }else{
148384     int iStart;
148385     int iEnd = 0x7FFFFFFF;
148386
148387     for(i=0; i<pIter->nPhrase; i++){
148388       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
148389       if( pPhrase->pHead && pPhrase->iHead<iEnd ){
148390         iEnd = pPhrase->iHead;
148391       }
148392     }
148393     if( iEnd==0x7FFFFFFF ){
148394       return 1;
148395     }
148396
148397     pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
148398     for(i=0; i<pIter->nPhrase; i++){
148399       SnippetPhrase *pPhrase = &pIter->aPhrase[i];
148400       fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
148401       fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
148402     }
148403   }
148404
148405   return 0;
148406 }
148407
148408 /*
148409 ** Retrieve information about the current candidate snippet of snippet 
148410 ** iterator pIter.
148411 */
148412 static void fts3SnippetDetails(
148413   SnippetIter *pIter,             /* Snippet iterator */
148414   u64 mCovered,                   /* Bitmask of phrases already covered */
148415   int *piToken,                   /* OUT: First token of proposed snippet */
148416   int *piScore,                   /* OUT: "Score" for this snippet */
148417   u64 *pmCover,                   /* OUT: Bitmask of phrases covered */
148418   u64 *pmHighlight                /* OUT: Bitmask of terms to highlight */
148419 ){
148420   int iStart = pIter->iCurrent;   /* First token of snippet */
148421   int iScore = 0;                 /* Score of this snippet */
148422   int i;                          /* Loop counter */
148423   u64 mCover = 0;                 /* Mask of phrases covered by this snippet */
148424   u64 mHighlight = 0;             /* Mask of tokens to highlight in snippet */
148425
148426   for(i=0; i<pIter->nPhrase; i++){
148427     SnippetPhrase *pPhrase = &pIter->aPhrase[i];
148428     if( pPhrase->pTail ){
148429       char *pCsr = pPhrase->pTail;
148430       int iCsr = pPhrase->iTail;
148431
148432       while( iCsr<(iStart+pIter->nSnippet) ){
148433         int j;
148434         u64 mPhrase = (u64)1 << i;
148435         u64 mPos = (u64)1 << (iCsr - iStart);
148436         assert( iCsr>=iStart );
148437         if( (mCover|mCovered)&mPhrase ){
148438           iScore++;
148439         }else{
148440           iScore += 1000;
148441         }
148442         mCover |= mPhrase;
148443
148444         for(j=0; j<pPhrase->nToken; j++){
148445           mHighlight |= (mPos>>j);
148446         }
148447
148448         if( 0==(*pCsr & 0x0FE) ) break;
148449         fts3GetDeltaPosition(&pCsr, &iCsr);
148450       }
148451     }
148452   }
148453
148454   /* Set the output variables before returning. */
148455   *piToken = iStart;
148456   *piScore = iScore;
148457   *pmCover = mCover;
148458   *pmHighlight = mHighlight;
148459 }
148460
148461 /*
148462 ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
148463 ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
148464 */
148465 static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
148466   SnippetIter *p = (SnippetIter *)ctx;
148467   SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
148468   char *pCsr;
148469   int rc;
148470
148471   pPhrase->nToken = pExpr->pPhrase->nToken;
148472   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
148473   assert( rc==SQLITE_OK || pCsr==0 );
148474   if( pCsr ){
148475     int iFirst = 0;
148476     pPhrase->pList = pCsr;
148477     fts3GetDeltaPosition(&pCsr, &iFirst);
148478     assert( iFirst>=0 );
148479     pPhrase->pHead = pCsr;
148480     pPhrase->pTail = pCsr;
148481     pPhrase->iHead = iFirst;
148482     pPhrase->iTail = iFirst;
148483   }else{
148484     assert( rc!=SQLITE_OK || (
148485        pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0 
148486     ));
148487   }
148488
148489   return rc;
148490 }
148491
148492 /*
148493 ** Select the fragment of text consisting of nFragment contiguous tokens 
148494 ** from column iCol that represent the "best" snippet. The best snippet
148495 ** is the snippet with the highest score, where scores are calculated
148496 ** by adding:
148497 **
148498 **   (a) +1 point for each occurrence of a matchable phrase in the snippet.
148499 **
148500 **   (b) +1000 points for the first occurrence of each matchable phrase in 
148501 **       the snippet for which the corresponding mCovered bit is not set.
148502 **
148503 ** The selected snippet parameters are stored in structure *pFragment before
148504 ** returning. The score of the selected snippet is stored in *piScore
148505 ** before returning.
148506 */
148507 static int fts3BestSnippet(
148508   int nSnippet,                   /* Desired snippet length */
148509   Fts3Cursor *pCsr,               /* Cursor to create snippet for */
148510   int iCol,                       /* Index of column to create snippet from */
148511   u64 mCovered,                   /* Mask of phrases already covered */
148512   u64 *pmSeen,                    /* IN/OUT: Mask of phrases seen */
148513   SnippetFragment *pFragment,     /* OUT: Best snippet found */
148514   int *piScore                    /* OUT: Score of snippet pFragment */
148515 ){
148516   int rc;                         /* Return Code */
148517   int nList;                      /* Number of phrases in expression */
148518   SnippetIter sIter;              /* Iterates through snippet candidates */
148519   int nByte;                      /* Number of bytes of space to allocate */
148520   int iBestScore = -1;            /* Best snippet score found so far */
148521   int i;                          /* Loop counter */
148522
148523   memset(&sIter, 0, sizeof(sIter));
148524
148525   /* Iterate through the phrases in the expression to count them. The same
148526   ** callback makes sure the doclists are loaded for each phrase.
148527   */
148528   rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
148529   if( rc!=SQLITE_OK ){
148530     return rc;
148531   }
148532
148533   /* Now that it is known how many phrases there are, allocate and zero
148534   ** the required space using malloc().
148535   */
148536   nByte = sizeof(SnippetPhrase) * nList;
148537   sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
148538   if( !sIter.aPhrase ){
148539     return SQLITE_NOMEM;
148540   }
148541   memset(sIter.aPhrase, 0, nByte);
148542
148543   /* Initialize the contents of the SnippetIter object. Then iterate through
148544   ** the set of phrases in the expression to populate the aPhrase[] array.
148545   */
148546   sIter.pCsr = pCsr;
148547   sIter.iCol = iCol;
148548   sIter.nSnippet = nSnippet;
148549   sIter.nPhrase = nList;
148550   sIter.iCurrent = -1;
148551   rc = fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
148552   if( rc==SQLITE_OK ){
148553
148554     /* Set the *pmSeen output variable. */
148555     for(i=0; i<nList; i++){
148556       if( sIter.aPhrase[i].pHead ){
148557         *pmSeen |= (u64)1 << i;
148558       }
148559     }
148560
148561     /* Loop through all candidate snippets. Store the best snippet in 
148562      ** *pFragment. Store its associated 'score' in iBestScore.
148563      */
148564     pFragment->iCol = iCol;
148565     while( !fts3SnippetNextCandidate(&sIter) ){
148566       int iPos;
148567       int iScore;
148568       u64 mCover;
148569       u64 mHighlite;
148570       fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover,&mHighlite);
148571       assert( iScore>=0 );
148572       if( iScore>iBestScore ){
148573         pFragment->iPos = iPos;
148574         pFragment->hlmask = mHighlite;
148575         pFragment->covered = mCover;
148576         iBestScore = iScore;
148577       }
148578     }
148579
148580     *piScore = iBestScore;
148581   }
148582   sqlite3_free(sIter.aPhrase);
148583   return rc;
148584 }
148585
148586
148587 /*
148588 ** Append a string to the string-buffer passed as the first argument.
148589 **
148590 ** If nAppend is negative, then the length of the string zAppend is
148591 ** determined using strlen().
148592 */
148593 static int fts3StringAppend(
148594   StrBuffer *pStr,                /* Buffer to append to */
148595   const char *zAppend,            /* Pointer to data to append to buffer */
148596   int nAppend                     /* Size of zAppend in bytes (or -1) */
148597 ){
148598   if( nAppend<0 ){
148599     nAppend = (int)strlen(zAppend);
148600   }
148601
148602   /* If there is insufficient space allocated at StrBuffer.z, use realloc()
148603   ** to grow the buffer until so that it is big enough to accomadate the
148604   ** appended data.
148605   */
148606   if( pStr->n+nAppend+1>=pStr->nAlloc ){
148607     int nAlloc = pStr->nAlloc+nAppend+100;
148608     char *zNew = sqlite3_realloc(pStr->z, nAlloc);
148609     if( !zNew ){
148610       return SQLITE_NOMEM;
148611     }
148612     pStr->z = zNew;
148613     pStr->nAlloc = nAlloc;
148614   }
148615   assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
148616
148617   /* Append the data to the string buffer. */
148618   memcpy(&pStr->z[pStr->n], zAppend, nAppend);
148619   pStr->n += nAppend;
148620   pStr->z[pStr->n] = '\0';
148621
148622   return SQLITE_OK;
148623 }
148624
148625 /*
148626 ** The fts3BestSnippet() function often selects snippets that end with a
148627 ** query term. That is, the final term of the snippet is always a term
148628 ** that requires highlighting. For example, if 'X' is a highlighted term
148629 ** and '.' is a non-highlighted term, BestSnippet() may select:
148630 **
148631 **     ........X.....X
148632 **
148633 ** This function "shifts" the beginning of the snippet forward in the 
148634 ** document so that there are approximately the same number of 
148635 ** non-highlighted terms to the right of the final highlighted term as there
148636 ** are to the left of the first highlighted term. For example, to this:
148637 **
148638 **     ....X.....X....
148639 **
148640 ** This is done as part of extracting the snippet text, not when selecting
148641 ** the snippet. Snippet selection is done based on doclists only, so there
148642 ** is no way for fts3BestSnippet() to know whether or not the document 
148643 ** actually contains terms that follow the final highlighted term. 
148644 */
148645 static int fts3SnippetShift(
148646   Fts3Table *pTab,                /* FTS3 table snippet comes from */
148647   int iLangid,                    /* Language id to use in tokenizing */
148648   int nSnippet,                   /* Number of tokens desired for snippet */
148649   const char *zDoc,               /* Document text to extract snippet from */
148650   int nDoc,                       /* Size of buffer zDoc in bytes */
148651   int *piPos,                     /* IN/OUT: First token of snippet */
148652   u64 *pHlmask                    /* IN/OUT: Mask of tokens to highlight */
148653 ){
148654   u64 hlmask = *pHlmask;          /* Local copy of initial highlight-mask */
148655
148656   if( hlmask ){
148657     int nLeft;                    /* Tokens to the left of first highlight */
148658     int nRight;                   /* Tokens to the right of last highlight */
148659     int nDesired;                 /* Ideal number of tokens to shift forward */
148660
148661     for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
148662     for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
148663     nDesired = (nLeft-nRight)/2;
148664
148665     /* Ideally, the start of the snippet should be pushed forward in the
148666     ** document nDesired tokens. This block checks if there are actually
148667     ** nDesired tokens to the right of the snippet. If so, *piPos and
148668     ** *pHlMask are updated to shift the snippet nDesired tokens to the
148669     ** right. Otherwise, the snippet is shifted by the number of tokens
148670     ** available.
148671     */
148672     if( nDesired>0 ){
148673       int nShift;                 /* Number of tokens to shift snippet by */
148674       int iCurrent = 0;           /* Token counter */
148675       int rc;                     /* Return Code */
148676       sqlite3_tokenizer_module *pMod;
148677       sqlite3_tokenizer_cursor *pC;
148678       pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
148679
148680       /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
148681       ** or more tokens in zDoc/nDoc.
148682       */
148683       rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
148684       if( rc!=SQLITE_OK ){
148685         return rc;
148686       }
148687       while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
148688         const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
148689         rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
148690       }
148691       pMod->xClose(pC);
148692       if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
148693
148694       nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
148695       assert( nShift<=nDesired );
148696       if( nShift>0 ){
148697         *piPos += nShift;
148698         *pHlmask = hlmask >> nShift;
148699       }
148700     }
148701   }
148702   return SQLITE_OK;
148703 }
148704
148705 /*
148706 ** Extract the snippet text for fragment pFragment from cursor pCsr and
148707 ** append it to string buffer pOut.
148708 */
148709 static int fts3SnippetText(
148710   Fts3Cursor *pCsr,               /* FTS3 Cursor */
148711   SnippetFragment *pFragment,     /* Snippet to extract */
148712   int iFragment,                  /* Fragment number */
148713   int isLast,                     /* True for final fragment in snippet */
148714   int nSnippet,                   /* Number of tokens in extracted snippet */
148715   const char *zOpen,              /* String inserted before highlighted term */
148716   const char *zClose,             /* String inserted after highlighted term */
148717   const char *zEllipsis,          /* String inserted between snippets */
148718   StrBuffer *pOut                 /* Write output here */
148719 ){
148720   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
148721   int rc;                         /* Return code */
148722   const char *zDoc;               /* Document text to extract snippet from */
148723   int nDoc;                       /* Size of zDoc in bytes */
148724   int iCurrent = 0;               /* Current token number of document */
148725   int iEnd = 0;                   /* Byte offset of end of current token */
148726   int isShiftDone = 0;            /* True after snippet is shifted */
148727   int iPos = pFragment->iPos;     /* First token of snippet */
148728   u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
148729   int iCol = pFragment->iCol+1;   /* Query column to extract text from */
148730   sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
148731   sqlite3_tokenizer_cursor *pC;   /* Tokenizer cursor open on zDoc/nDoc */
148732   
148733   zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
148734   if( zDoc==0 ){
148735     if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
148736       return SQLITE_NOMEM;
148737     }
148738     return SQLITE_OK;
148739   }
148740   nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
148741
148742   /* Open a token cursor on the document. */
148743   pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
148744   rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
148745   if( rc!=SQLITE_OK ){
148746     return rc;
148747   }
148748
148749   while( rc==SQLITE_OK ){
148750     const char *ZDUMMY;           /* Dummy argument used with tokenizer */
148751     int DUMMY1 = -1;              /* Dummy argument used with tokenizer */
148752     int iBegin = 0;               /* Offset in zDoc of start of token */
148753     int iFin = 0;                 /* Offset in zDoc of end of token */
148754     int isHighlight = 0;          /* True for highlighted terms */
148755
148756     /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
148757     ** in the FTS code the variable that the third argument to xNext points to
148758     ** is initialized to zero before the first (*but not necessarily
148759     ** subsequent*) call to xNext(). This is done for a particular application
148760     ** that needs to know whether or not the tokenizer is being used for
148761     ** snippet generation or for some other purpose.
148762     **
148763     ** Extreme care is required when writing code to depend on this
148764     ** initialization. It is not a documented part of the tokenizer interface.
148765     ** If a tokenizer is used directly by any code outside of FTS, this
148766     ** convention might not be respected.  */
148767     rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
148768     if( rc!=SQLITE_OK ){
148769       if( rc==SQLITE_DONE ){
148770         /* Special case - the last token of the snippet is also the last token
148771         ** of the column. Append any punctuation that occurred between the end
148772         ** of the previous token and the end of the document to the output. 
148773         ** Then break out of the loop. */
148774         rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
148775       }
148776       break;
148777     }
148778     if( iCurrent<iPos ){ continue; }
148779
148780     if( !isShiftDone ){
148781       int n = nDoc - iBegin;
148782       rc = fts3SnippetShift(
148783           pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
148784       );
148785       isShiftDone = 1;
148786
148787       /* Now that the shift has been done, check if the initial "..." are
148788       ** required. They are required if (a) this is not the first fragment,
148789       ** or (b) this fragment does not begin at position 0 of its column. 
148790       */
148791       if( rc==SQLITE_OK ){
148792         if( iPos>0 || iFragment>0 ){
148793           rc = fts3StringAppend(pOut, zEllipsis, -1);
148794         }else if( iBegin ){
148795           rc = fts3StringAppend(pOut, zDoc, iBegin);
148796         }
148797       }
148798       if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
148799     }
148800
148801     if( iCurrent>=(iPos+nSnippet) ){
148802       if( isLast ){
148803         rc = fts3StringAppend(pOut, zEllipsis, -1);
148804       }
148805       break;
148806     }
148807
148808     /* Set isHighlight to true if this term should be highlighted. */
148809     isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
148810
148811     if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
148812     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
148813     if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
148814     if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
148815
148816     iEnd = iFin;
148817   }
148818
148819   pMod->xClose(pC);
148820   return rc;
148821 }
148822
148823
148824 /*
148825 ** This function is used to count the entries in a column-list (a 
148826 ** delta-encoded list of term offsets within a single column of a single 
148827 ** row). When this function is called, *ppCollist should point to the
148828 ** beginning of the first varint in the column-list (the varint that
148829 ** contains the position of the first matching term in the column data).
148830 ** Before returning, *ppCollist is set to point to the first byte after
148831 ** the last varint in the column-list (either the 0x00 signifying the end
148832 ** of the position-list, or the 0x01 that precedes the column number of
148833 ** the next column in the position-list).
148834 **
148835 ** The number of elements in the column-list is returned.
148836 */
148837 static int fts3ColumnlistCount(char **ppCollist){
148838   char *pEnd = *ppCollist;
148839   char c = 0;
148840   int nEntry = 0;
148841
148842   /* A column-list is terminated by either a 0x01 or 0x00. */
148843   while( 0xFE & (*pEnd | c) ){
148844     c = *pEnd++ & 0x80;
148845     if( !c ) nEntry++;
148846   }
148847
148848   *ppCollist = pEnd;
148849   return nEntry;
148850 }
148851
148852 /*
148853 ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
148854 ** for a single query. 
148855 **
148856 ** fts3ExprIterate() callback to load the 'global' elements of a
148857 ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements 
148858 ** of the matchinfo array that are constant for all rows returned by the 
148859 ** current query.
148860 **
148861 ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
148862 ** function populates Matchinfo.aMatchinfo[] as follows:
148863 **
148864 **   for(iCol=0; iCol<nCol; iCol++){
148865 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
148866 **     aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
148867 **   }
148868 **
148869 ** where X is the number of matches for phrase iPhrase is column iCol of all
148870 ** rows of the table. Y is the number of rows for which column iCol contains
148871 ** at least one instance of phrase iPhrase.
148872 **
148873 ** If the phrase pExpr consists entirely of deferred tokens, then all X and
148874 ** Y values are set to nDoc, where nDoc is the number of documents in the 
148875 ** file system. This is done because the full-text index doclist is required
148876 ** to calculate these values properly, and the full-text index doclist is
148877 ** not available for deferred tokens.
148878 */
148879 static int fts3ExprGlobalHitsCb(
148880   Fts3Expr *pExpr,                /* Phrase expression node */
148881   int iPhrase,                    /* Phrase number (numbered from zero) */
148882   void *pCtx                      /* Pointer to MatchInfo structure */
148883 ){
148884   MatchInfo *p = (MatchInfo *)pCtx;
148885   return sqlite3Fts3EvalPhraseStats(
148886       p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
148887   );
148888 }
148889
148890 /*
148891 ** fts3ExprIterate() callback used to collect the "local" part of the
148892 ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the 
148893 ** array that are different for each row returned by the query.
148894 */
148895 static int fts3ExprLocalHitsCb(
148896   Fts3Expr *pExpr,                /* Phrase expression node */
148897   int iPhrase,                    /* Phrase number */
148898   void *pCtx                      /* Pointer to MatchInfo structure */
148899 ){
148900   int rc = SQLITE_OK;
148901   MatchInfo *p = (MatchInfo *)pCtx;
148902   int iStart = iPhrase * p->nCol * 3;
148903   int i;
148904
148905   for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
148906     char *pCsr;
148907     rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
148908     if( pCsr ){
148909       p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
148910     }else{
148911       p->aMatchinfo[iStart+i*3] = 0;
148912     }
148913   }
148914
148915   return rc;
148916 }
148917
148918 static int fts3MatchinfoCheck(
148919   Fts3Table *pTab, 
148920   char cArg,
148921   char **pzErr
148922 ){
148923   if( (cArg==FTS3_MATCHINFO_NPHRASE)
148924    || (cArg==FTS3_MATCHINFO_NCOL)
148925    || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
148926    || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
148927    || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
148928    || (cArg==FTS3_MATCHINFO_LCS)
148929    || (cArg==FTS3_MATCHINFO_HITS)
148930   ){
148931     return SQLITE_OK;
148932   }
148933   *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
148934   return SQLITE_ERROR;
148935 }
148936
148937 static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
148938   int nVal;                       /* Number of integers output by cArg */
148939
148940   switch( cArg ){
148941     case FTS3_MATCHINFO_NDOC:
148942     case FTS3_MATCHINFO_NPHRASE: 
148943     case FTS3_MATCHINFO_NCOL: 
148944       nVal = 1;
148945       break;
148946
148947     case FTS3_MATCHINFO_AVGLENGTH:
148948     case FTS3_MATCHINFO_LENGTH:
148949     case FTS3_MATCHINFO_LCS:
148950       nVal = pInfo->nCol;
148951       break;
148952
148953     default:
148954       assert( cArg==FTS3_MATCHINFO_HITS );
148955       nVal = pInfo->nCol * pInfo->nPhrase * 3;
148956       break;
148957   }
148958
148959   return nVal;
148960 }
148961
148962 static int fts3MatchinfoSelectDoctotal(
148963   Fts3Table *pTab,
148964   sqlite3_stmt **ppStmt,
148965   sqlite3_int64 *pnDoc,
148966   const char **paLen
148967 ){
148968   sqlite3_stmt *pStmt;
148969   const char *a;
148970   sqlite3_int64 nDoc;
148971
148972   if( !*ppStmt ){
148973     int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
148974     if( rc!=SQLITE_OK ) return rc;
148975   }
148976   pStmt = *ppStmt;
148977   assert( sqlite3_data_count(pStmt)==1 );
148978
148979   a = sqlite3_column_blob(pStmt, 0);
148980   a += sqlite3Fts3GetVarint(a, &nDoc);
148981   if( nDoc==0 ) return FTS_CORRUPT_VTAB;
148982   *pnDoc = (u32)nDoc;
148983
148984   if( paLen ) *paLen = a;
148985   return SQLITE_OK;
148986 }
148987
148988 /*
148989 ** An instance of the following structure is used to store state while 
148990 ** iterating through a multi-column position-list corresponding to the
148991 ** hits for a single phrase on a single row in order to calculate the
148992 ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
148993 */
148994 typedef struct LcsIterator LcsIterator;
148995 struct LcsIterator {
148996   Fts3Expr *pExpr;                /* Pointer to phrase expression */
148997   int iPosOffset;                 /* Tokens count up to end of this phrase */
148998   char *pRead;                    /* Cursor used to iterate through aDoclist */
148999   int iPos;                       /* Current position */
149000 };
149001
149002 /* 
149003 ** If LcsIterator.iCol is set to the following value, the iterator has
149004 ** finished iterating through all offsets for all columns.
149005 */
149006 #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
149007
149008 static int fts3MatchinfoLcsCb(
149009   Fts3Expr *pExpr,                /* Phrase expression node */
149010   int iPhrase,                    /* Phrase number (numbered from zero) */
149011   void *pCtx                      /* Pointer to MatchInfo structure */
149012 ){
149013   LcsIterator *aIter = (LcsIterator *)pCtx;
149014   aIter[iPhrase].pExpr = pExpr;
149015   return SQLITE_OK;
149016 }
149017
149018 /*
149019 ** Advance the iterator passed as an argument to the next position. Return
149020 ** 1 if the iterator is at EOF or if it now points to the start of the
149021 ** position list for the next column.
149022 */
149023 static int fts3LcsIteratorAdvance(LcsIterator *pIter){
149024   char *pRead = pIter->pRead;
149025   sqlite3_int64 iRead;
149026   int rc = 0;
149027
149028   pRead += sqlite3Fts3GetVarint(pRead, &iRead);
149029   if( iRead==0 || iRead==1 ){
149030     pRead = 0;
149031     rc = 1;
149032   }else{
149033     pIter->iPos += (int)(iRead-2);
149034   }
149035
149036   pIter->pRead = pRead;
149037   return rc;
149038 }
149039   
149040 /*
149041 ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag. 
149042 **
149043 ** If the call is successful, the longest-common-substring lengths for each
149044 ** column are written into the first nCol elements of the pInfo->aMatchinfo[] 
149045 ** array before returning. SQLITE_OK is returned in this case.
149046 **
149047 ** Otherwise, if an error occurs, an SQLite error code is returned and the
149048 ** data written to the first nCol elements of pInfo->aMatchinfo[] is 
149049 ** undefined.
149050 */
149051 static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
149052   LcsIterator *aIter;
149053   int i;
149054   int iCol;
149055   int nToken = 0;
149056
149057   /* Allocate and populate the array of LcsIterator objects. The array
149058   ** contains one element for each matchable phrase in the query.
149059   **/
149060   aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
149061   if( !aIter ) return SQLITE_NOMEM;
149062   memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
149063   (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
149064
149065   for(i=0; i<pInfo->nPhrase; i++){
149066     LcsIterator *pIter = &aIter[i];
149067     nToken -= pIter->pExpr->pPhrase->nToken;
149068     pIter->iPosOffset = nToken;
149069   }
149070
149071   for(iCol=0; iCol<pInfo->nCol; iCol++){
149072     int nLcs = 0;                 /* LCS value for this column */
149073     int nLive = 0;                /* Number of iterators in aIter not at EOF */
149074
149075     for(i=0; i<pInfo->nPhrase; i++){
149076       int rc;
149077       LcsIterator *pIt = &aIter[i];
149078       rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
149079       if( rc!=SQLITE_OK ) return rc;
149080       if( pIt->pRead ){
149081         pIt->iPos = pIt->iPosOffset;
149082         fts3LcsIteratorAdvance(&aIter[i]);
149083         nLive++;
149084       }
149085     }
149086
149087     while( nLive>0 ){
149088       LcsIterator *pAdv = 0;      /* The iterator to advance by one position */
149089       int nThisLcs = 0;           /* LCS for the current iterator positions */
149090
149091       for(i=0; i<pInfo->nPhrase; i++){
149092         LcsIterator *pIter = &aIter[i];
149093         if( pIter->pRead==0 ){
149094           /* This iterator is already at EOF for this column. */
149095           nThisLcs = 0;
149096         }else{
149097           if( pAdv==0 || pIter->iPos<pAdv->iPos ){
149098             pAdv = pIter;
149099           }
149100           if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
149101             nThisLcs++;
149102           }else{
149103             nThisLcs = 1;
149104           }
149105           if( nThisLcs>nLcs ) nLcs = nThisLcs;
149106         }
149107       }
149108       if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
149109     }
149110
149111     pInfo->aMatchinfo[iCol] = nLcs;
149112   }
149113
149114   sqlite3_free(aIter);
149115   return SQLITE_OK;
149116 }
149117
149118 /*
149119 ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
149120 ** be returned by the matchinfo() function. Argument zArg contains the 
149121 ** format string passed as the second argument to matchinfo (or the
149122 ** default value "pcx" if no second argument was specified). The format
149123 ** string has already been validated and the pInfo->aMatchinfo[] array
149124 ** is guaranteed to be large enough for the output.
149125 **
149126 ** If bGlobal is true, then populate all fields of the matchinfo() output.
149127 ** If it is false, then assume that those fields that do not change between
149128 ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
149129 ** have already been populated.
149130 **
149131 ** Return SQLITE_OK if successful, or an SQLite error code if an error 
149132 ** occurs. If a value other than SQLITE_OK is returned, the state the
149133 ** pInfo->aMatchinfo[] buffer is left in is undefined.
149134 */
149135 static int fts3MatchinfoValues(
149136   Fts3Cursor *pCsr,               /* FTS3 cursor object */
149137   int bGlobal,                    /* True to grab the global stats */
149138   MatchInfo *pInfo,               /* Matchinfo context object */
149139   const char *zArg                /* Matchinfo format string */
149140 ){
149141   int rc = SQLITE_OK;
149142   int i;
149143   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
149144   sqlite3_stmt *pSelect = 0;
149145
149146   for(i=0; rc==SQLITE_OK && zArg[i]; i++){
149147
149148     switch( zArg[i] ){
149149       case FTS3_MATCHINFO_NPHRASE:
149150         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
149151         break;
149152
149153       case FTS3_MATCHINFO_NCOL:
149154         if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
149155         break;
149156         
149157       case FTS3_MATCHINFO_NDOC:
149158         if( bGlobal ){
149159           sqlite3_int64 nDoc = 0;
149160           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
149161           pInfo->aMatchinfo[0] = (u32)nDoc;
149162         }
149163         break;
149164
149165       case FTS3_MATCHINFO_AVGLENGTH: 
149166         if( bGlobal ){
149167           sqlite3_int64 nDoc;     /* Number of rows in table */
149168           const char *a;          /* Aggregate column length array */
149169
149170           rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
149171           if( rc==SQLITE_OK ){
149172             int iCol;
149173             for(iCol=0; iCol<pInfo->nCol; iCol++){
149174               u32 iVal;
149175               sqlite3_int64 nToken;
149176               a += sqlite3Fts3GetVarint(a, &nToken);
149177               iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
149178               pInfo->aMatchinfo[iCol] = iVal;
149179             }
149180           }
149181         }
149182         break;
149183
149184       case FTS3_MATCHINFO_LENGTH: {
149185         sqlite3_stmt *pSelectDocsize = 0;
149186         rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
149187         if( rc==SQLITE_OK ){
149188           int iCol;
149189           const char *a = sqlite3_column_blob(pSelectDocsize, 0);
149190           for(iCol=0; iCol<pInfo->nCol; iCol++){
149191             sqlite3_int64 nToken;
149192             a += sqlite3Fts3GetVarint(a, &nToken);
149193             pInfo->aMatchinfo[iCol] = (u32)nToken;
149194           }
149195         }
149196         sqlite3_reset(pSelectDocsize);
149197         break;
149198       }
149199
149200       case FTS3_MATCHINFO_LCS:
149201         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
149202         if( rc==SQLITE_OK ){
149203           rc = fts3MatchinfoLcs(pCsr, pInfo);
149204         }
149205         break;
149206
149207       default: {
149208         Fts3Expr *pExpr;
149209         assert( zArg[i]==FTS3_MATCHINFO_HITS );
149210         pExpr = pCsr->pExpr;
149211         rc = fts3ExprLoadDoclists(pCsr, 0, 0);
149212         if( rc!=SQLITE_OK ) break;
149213         if( bGlobal ){
149214           if( pCsr->pDeferred ){
149215             rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
149216             if( rc!=SQLITE_OK ) break;
149217           }
149218           rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
149219           if( rc!=SQLITE_OK ) break;
149220         }
149221         (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
149222         break;
149223       }
149224     }
149225
149226     pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
149227   }
149228
149229   sqlite3_reset(pSelect);
149230   return rc;
149231 }
149232
149233
149234 /*
149235 ** Populate pCsr->aMatchinfo[] with data for the current row. The 
149236 ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
149237 */
149238 static int fts3GetMatchinfo(
149239   Fts3Cursor *pCsr,               /* FTS3 Cursor object */
149240   const char *zArg                /* Second argument to matchinfo() function */
149241 ){
149242   MatchInfo sInfo;
149243   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
149244   int rc = SQLITE_OK;
149245   int bGlobal = 0;                /* Collect 'global' stats as well as local */
149246
149247   memset(&sInfo, 0, sizeof(MatchInfo));
149248   sInfo.pCursor = pCsr;
149249   sInfo.nCol = pTab->nColumn;
149250
149251   /* If there is cached matchinfo() data, but the format string for the 
149252   ** cache does not match the format string for this request, discard 
149253   ** the cached data. */
149254   if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
149255     assert( pCsr->aMatchinfo );
149256     sqlite3_free(pCsr->aMatchinfo);
149257     pCsr->zMatchinfo = 0;
149258     pCsr->aMatchinfo = 0;
149259   }
149260
149261   /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
149262   ** matchinfo function has been called for this query. In this case 
149263   ** allocate the array used to accumulate the matchinfo data and
149264   ** initialize those elements that are constant for every row.
149265   */
149266   if( pCsr->aMatchinfo==0 ){
149267     int nMatchinfo = 0;           /* Number of u32 elements in match-info */
149268     int nArg;                     /* Bytes in zArg */
149269     int i;                        /* Used to iterate through zArg */
149270
149271     /* Determine the number of phrases in the query */
149272     pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
149273     sInfo.nPhrase = pCsr->nPhrase;
149274
149275     /* Determine the number of integers in the buffer returned by this call. */
149276     for(i=0; zArg[i]; i++){
149277       nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
149278     }
149279
149280     /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
149281     nArg = (int)strlen(zArg);
149282     pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
149283     if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
149284
149285     pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
149286     pCsr->nMatchinfo = nMatchinfo;
149287     memcpy(pCsr->zMatchinfo, zArg, nArg+1);
149288     memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
149289     pCsr->isMatchinfoNeeded = 1;
149290     bGlobal = 1;
149291   }
149292
149293   sInfo.aMatchinfo = pCsr->aMatchinfo;
149294   sInfo.nPhrase = pCsr->nPhrase;
149295   if( pCsr->isMatchinfoNeeded ){
149296     rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
149297     pCsr->isMatchinfoNeeded = 0;
149298   }
149299
149300   return rc;
149301 }
149302
149303 /*
149304 ** Implementation of snippet() function.
149305 */
149306 SQLITE_PRIVATE void sqlite3Fts3Snippet(
149307   sqlite3_context *pCtx,          /* SQLite function call context */
149308   Fts3Cursor *pCsr,               /* Cursor object */
149309   const char *zStart,             /* Snippet start text - "<b>" */
149310   const char *zEnd,               /* Snippet end text - "</b>" */
149311   const char *zEllipsis,          /* Snippet ellipsis text - "<b>...</b>" */
149312   int iCol,                       /* Extract snippet from this column */
149313   int nToken                      /* Approximate number of tokens in snippet */
149314 ){
149315   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
149316   int rc = SQLITE_OK;
149317   int i;
149318   StrBuffer res = {0, 0, 0};
149319
149320   /* The returned text includes up to four fragments of text extracted from
149321   ** the data in the current row. The first iteration of the for(...) loop
149322   ** below attempts to locate a single fragment of text nToken tokens in 
149323   ** size that contains at least one instance of all phrases in the query
149324   ** expression that appear in the current row. If such a fragment of text
149325   ** cannot be found, the second iteration of the loop attempts to locate
149326   ** a pair of fragments, and so on.
149327   */
149328   int nSnippet = 0;               /* Number of fragments in this snippet */
149329   SnippetFragment aSnippet[4];    /* Maximum of 4 fragments per snippet */
149330   int nFToken = -1;               /* Number of tokens in each fragment */
149331
149332   if( !pCsr->pExpr ){
149333     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
149334     return;
149335   }
149336
149337   for(nSnippet=1; 1; nSnippet++){
149338
149339     int iSnip;                    /* Loop counter 0..nSnippet-1 */
149340     u64 mCovered = 0;             /* Bitmask of phrases covered by snippet */
149341     u64 mSeen = 0;                /* Bitmask of phrases seen by BestSnippet() */
149342
149343     if( nToken>=0 ){
149344       nFToken = (nToken+nSnippet-1) / nSnippet;
149345     }else{
149346       nFToken = -1 * nToken;
149347     }
149348
149349     for(iSnip=0; iSnip<nSnippet; iSnip++){
149350       int iBestScore = -1;        /* Best score of columns checked so far */
149351       int iRead;                  /* Used to iterate through columns */
149352       SnippetFragment *pFragment = &aSnippet[iSnip];
149353
149354       memset(pFragment, 0, sizeof(*pFragment));
149355
149356       /* Loop through all columns of the table being considered for snippets.
149357       ** If the iCol argument to this function was negative, this means all
149358       ** columns of the FTS3 table. Otherwise, only column iCol is considered.
149359       */
149360       for(iRead=0; iRead<pTab->nColumn; iRead++){
149361         SnippetFragment sF = {0, 0, 0, 0};
149362         int iS = 0;
149363         if( iCol>=0 && iRead!=iCol ) continue;
149364
149365         /* Find the best snippet of nFToken tokens in column iRead. */
149366         rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
149367         if( rc!=SQLITE_OK ){
149368           goto snippet_out;
149369         }
149370         if( iS>iBestScore ){
149371           *pFragment = sF;
149372           iBestScore = iS;
149373         }
149374       }
149375
149376       mCovered |= pFragment->covered;
149377     }
149378
149379     /* If all query phrases seen by fts3BestSnippet() are present in at least
149380     ** one of the nSnippet snippet fragments, break out of the loop.
149381     */
149382     assert( (mCovered&mSeen)==mCovered );
149383     if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
149384   }
149385
149386   assert( nFToken>0 );
149387
149388   for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
149389     rc = fts3SnippetText(pCsr, &aSnippet[i], 
149390         i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
149391     );
149392   }
149393
149394  snippet_out:
149395   sqlite3Fts3SegmentsClose(pTab);
149396   if( rc!=SQLITE_OK ){
149397     sqlite3_result_error_code(pCtx, rc);
149398     sqlite3_free(res.z);
149399   }else{
149400     sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
149401   }
149402 }
149403
149404
149405 typedef struct TermOffset TermOffset;
149406 typedef struct TermOffsetCtx TermOffsetCtx;
149407
149408 struct TermOffset {
149409   char *pList;                    /* Position-list */
149410   int iPos;                       /* Position just read from pList */
149411   int iOff;                       /* Offset of this term from read positions */
149412 };
149413
149414 struct TermOffsetCtx {
149415   Fts3Cursor *pCsr;
149416   int iCol;                       /* Column of table to populate aTerm for */
149417   int iTerm;
149418   sqlite3_int64 iDocid;
149419   TermOffset *aTerm;
149420 };
149421
149422 /*
149423 ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
149424 */
149425 static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
149426   TermOffsetCtx *p = (TermOffsetCtx *)ctx;
149427   int nTerm;                      /* Number of tokens in phrase */
149428   int iTerm;                      /* For looping through nTerm phrase terms */
149429   char *pList;                    /* Pointer to position list for phrase */
149430   int iPos = 0;                   /* First position in position-list */
149431   int rc;
149432
149433   UNUSED_PARAMETER(iPhrase);
149434   rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
149435   nTerm = pExpr->pPhrase->nToken;
149436   if( pList ){
149437     fts3GetDeltaPosition(&pList, &iPos);
149438     assert( iPos>=0 );
149439   }
149440
149441   for(iTerm=0; iTerm<nTerm; iTerm++){
149442     TermOffset *pT = &p->aTerm[p->iTerm++];
149443     pT->iOff = nTerm-iTerm-1;
149444     pT->pList = pList;
149445     pT->iPos = iPos;
149446   }
149447
149448   return rc;
149449 }
149450
149451 /*
149452 ** Implementation of offsets() function.
149453 */
149454 SQLITE_PRIVATE void sqlite3Fts3Offsets(
149455   sqlite3_context *pCtx,          /* SQLite function call context */
149456   Fts3Cursor *pCsr                /* Cursor object */
149457 ){
149458   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
149459   sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
149460   int rc;                         /* Return Code */
149461   int nToken;                     /* Number of tokens in query */
149462   int iCol;                       /* Column currently being processed */
149463   StrBuffer res = {0, 0, 0};      /* Result string */
149464   TermOffsetCtx sCtx;             /* Context for fts3ExprTermOffsetInit() */
149465
149466   if( !pCsr->pExpr ){
149467     sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
149468     return;
149469   }
149470
149471   memset(&sCtx, 0, sizeof(sCtx));
149472   assert( pCsr->isRequireSeek==0 );
149473
149474   /* Count the number of terms in the query */
149475   rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
149476   if( rc!=SQLITE_OK ) goto offsets_out;
149477
149478   /* Allocate the array of TermOffset iterators. */
149479   sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
149480   if( 0==sCtx.aTerm ){
149481     rc = SQLITE_NOMEM;
149482     goto offsets_out;
149483   }
149484   sCtx.iDocid = pCsr->iPrevId;
149485   sCtx.pCsr = pCsr;
149486
149487   /* Loop through the table columns, appending offset information to 
149488   ** string-buffer res for each column.
149489   */
149490   for(iCol=0; iCol<pTab->nColumn; iCol++){
149491     sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
149492     const char *ZDUMMY;           /* Dummy argument used with xNext() */
149493     int NDUMMY = 0;               /* Dummy argument used with xNext() */
149494     int iStart = 0;
149495     int iEnd = 0;
149496     int iCurrent = 0;
149497     const char *zDoc;
149498     int nDoc;
149499
149500     /* Initialize the contents of sCtx.aTerm[] for column iCol. There is 
149501     ** no way that this operation can fail, so the return code from
149502     ** fts3ExprIterate() can be discarded.
149503     */
149504     sCtx.iCol = iCol;
149505     sCtx.iTerm = 0;
149506     (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
149507
149508     /* Retreive the text stored in column iCol. If an SQL NULL is stored 
149509     ** in column iCol, jump immediately to the next iteration of the loop.
149510     ** If an OOM occurs while retrieving the data (this can happen if SQLite
149511     ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM 
149512     ** to the caller. 
149513     */
149514     zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
149515     nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
149516     if( zDoc==0 ){
149517       if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
149518         continue;
149519       }
149520       rc = SQLITE_NOMEM;
149521       goto offsets_out;
149522     }
149523
149524     /* Initialize a tokenizer iterator to iterate through column iCol. */
149525     rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
149526         zDoc, nDoc, &pC
149527     );
149528     if( rc!=SQLITE_OK ) goto offsets_out;
149529
149530     rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
149531     while( rc==SQLITE_OK ){
149532       int i;                      /* Used to loop through terms */
149533       int iMinPos = 0x7FFFFFFF;   /* Position of next token */
149534       TermOffset *pTerm = 0;      /* TermOffset associated with next token */
149535
149536       for(i=0; i<nToken; i++){
149537         TermOffset *pT = &sCtx.aTerm[i];
149538         if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
149539           iMinPos = pT->iPos-pT->iOff;
149540           pTerm = pT;
149541         }
149542       }
149543
149544       if( !pTerm ){
149545         /* All offsets for this column have been gathered. */
149546         rc = SQLITE_DONE;
149547       }else{
149548         assert( iCurrent<=iMinPos );
149549         if( 0==(0xFE&*pTerm->pList) ){
149550           pTerm->pList = 0;
149551         }else{
149552           fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
149553         }
149554         while( rc==SQLITE_OK && iCurrent<iMinPos ){
149555           rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
149556         }
149557         if( rc==SQLITE_OK ){
149558           char aBuffer[64];
149559           sqlite3_snprintf(sizeof(aBuffer), aBuffer, 
149560               "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
149561           );
149562           rc = fts3StringAppend(&res, aBuffer, -1);
149563         }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
149564           rc = FTS_CORRUPT_VTAB;
149565         }
149566       }
149567     }
149568     if( rc==SQLITE_DONE ){
149569       rc = SQLITE_OK;
149570     }
149571
149572     pMod->xClose(pC);
149573     if( rc!=SQLITE_OK ) goto offsets_out;
149574   }
149575
149576  offsets_out:
149577   sqlite3_free(sCtx.aTerm);
149578   assert( rc!=SQLITE_DONE );
149579   sqlite3Fts3SegmentsClose(pTab);
149580   if( rc!=SQLITE_OK ){
149581     sqlite3_result_error_code(pCtx,  rc);
149582     sqlite3_free(res.z);
149583   }else{
149584     sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
149585   }
149586   return;
149587 }
149588
149589 /*
149590 ** Implementation of matchinfo() function.
149591 */
149592 SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
149593   sqlite3_context *pContext,      /* Function call context */
149594   Fts3Cursor *pCsr,               /* FTS3 table cursor */
149595   const char *zArg                /* Second arg to matchinfo() function */
149596 ){
149597   Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
149598   int rc;
149599   int i;
149600   const char *zFormat;
149601
149602   if( zArg ){
149603     for(i=0; zArg[i]; i++){
149604       char *zErr = 0;
149605       if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
149606         sqlite3_result_error(pContext, zErr, -1);
149607         sqlite3_free(zErr);
149608         return;
149609       }
149610     }
149611     zFormat = zArg;
149612   }else{
149613     zFormat = FTS3_MATCHINFO_DEFAULT;
149614   }
149615
149616   if( !pCsr->pExpr ){
149617     sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
149618     return;
149619   }
149620
149621   /* Retrieve matchinfo() data. */
149622   rc = fts3GetMatchinfo(pCsr, zFormat);
149623   sqlite3Fts3SegmentsClose(pTab);
149624
149625   if( rc!=SQLITE_OK ){
149626     sqlite3_result_error_code(pContext, rc);
149627   }else{
149628     int n = pCsr->nMatchinfo * sizeof(u32);
149629     sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
149630   }
149631 }
149632
149633 #endif
149634
149635 /************** End of fts3_snippet.c ****************************************/
149636 /************** Begin file fts3_unicode.c ************************************/
149637 /*
149638 ** 2012 May 24
149639 **
149640 ** The author disclaims copyright to this source code.  In place of
149641 ** a legal notice, here is a blessing:
149642 **
149643 **    May you do good and not evil.
149644 **    May you find forgiveness for yourself and forgive others.
149645 **    May you share freely, never taking more than you give.
149646 **
149647 ******************************************************************************
149648 **
149649 ** Implementation of the "unicode" full-text-search tokenizer.
149650 */
149651
149652 #ifndef SQLITE_DISABLE_FTS3_UNICODE
149653
149654 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
149655
149656 /* #include <assert.h> */
149657 /* #include <stdlib.h> */
149658 /* #include <stdio.h> */
149659 /* #include <string.h> */
149660
149661
149662 /*
149663 ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
149664 ** from the sqlite3 source file utf.c. If this file is compiled as part
149665 ** of the amalgamation, they are not required.
149666 */
149667 #ifndef SQLITE_AMALGAMATION
149668
149669 static const unsigned char sqlite3Utf8Trans1[] = {
149670   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
149671   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
149672   0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
149673   0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
149674   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
149675   0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
149676   0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
149677   0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
149678 };
149679
149680 #define READ_UTF8(zIn, zTerm, c)                           \
149681   c = *(zIn++);                                            \
149682   if( c>=0xc0 ){                                           \
149683     c = sqlite3Utf8Trans1[c-0xc0];                         \
149684     while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){            \
149685       c = (c<<6) + (0x3f & *(zIn++));                      \
149686     }                                                      \
149687     if( c<0x80                                             \
149688         || (c&0xFFFFF800)==0xD800                          \
149689         || (c&0xFFFFFFFE)==0xFFFE ){  c = 0xFFFD; }        \
149690   }
149691
149692 #define WRITE_UTF8(zOut, c) {                          \
149693   if( c<0x00080 ){                                     \
149694     *zOut++ = (u8)(c&0xFF);                            \
149695   }                                                    \
149696   else if( c<0x00800 ){                                \
149697     *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);                \
149698     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
149699   }                                                    \
149700   else if( c<0x10000 ){                                \
149701     *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);               \
149702     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
149703     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
149704   }else{                                               \
149705     *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);             \
149706     *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);             \
149707     *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);              \
149708     *zOut++ = 0x80 + (u8)(c & 0x3F);                   \
149709   }                                                    \
149710 }
149711
149712 #endif /* ifndef SQLITE_AMALGAMATION */
149713
149714 typedef struct unicode_tokenizer unicode_tokenizer;
149715 typedef struct unicode_cursor unicode_cursor;
149716
149717 struct unicode_tokenizer {
149718   sqlite3_tokenizer base;
149719   int bRemoveDiacritic;
149720   int nException;
149721   int *aiException;
149722 };
149723
149724 struct unicode_cursor {
149725   sqlite3_tokenizer_cursor base;
149726   const unsigned char *aInput;    /* Input text being tokenized */
149727   int nInput;                     /* Size of aInput[] in bytes */
149728   int iOff;                       /* Current offset within aInput[] */
149729   int iToken;                     /* Index of next token to be returned */
149730   char *zToken;                   /* storage for current token */
149731   int nAlloc;                     /* space allocated at zToken */
149732 };
149733
149734
149735 /*
149736 ** Destroy a tokenizer allocated by unicodeCreate().
149737 */
149738 static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
149739   if( pTokenizer ){
149740     unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
149741     sqlite3_free(p->aiException);
149742     sqlite3_free(p);
149743   }
149744   return SQLITE_OK;
149745 }
149746
149747 /*
149748 ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
149749 ** statement has specified that the tokenizer for this table shall consider
149750 ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
149751 ** token characters (if bAlnum==1).
149752 **
149753 ** For each codepoint in the zIn/nIn string, this function checks if the
149754 ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
149755 ** If so, no action is taken. Otherwise, the codepoint is added to the 
149756 ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
149757 ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
149758 ** codepoints in the aiException[] array.
149759 **
149760 ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
149761 ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
149762 ** It is not possible to change the behavior of the tokenizer with respect
149763 ** to these codepoints.
149764 */
149765 static int unicodeAddExceptions(
149766   unicode_tokenizer *p,           /* Tokenizer to add exceptions to */
149767   int bAlnum,                     /* Replace Isalnum() return value with this */
149768   const char *zIn,                /* Array of characters to make exceptions */
149769   int nIn                         /* Length of z in bytes */
149770 ){
149771   const unsigned char *z = (const unsigned char *)zIn;
149772   const unsigned char *zTerm = &z[nIn];
149773   int iCode;
149774   int nEntry = 0;
149775
149776   assert( bAlnum==0 || bAlnum==1 );
149777
149778   while( z<zTerm ){
149779     READ_UTF8(z, zTerm, iCode);
149780     assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
149781     if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum 
149782      && sqlite3FtsUnicodeIsdiacritic(iCode)==0 
149783     ){
149784       nEntry++;
149785     }
149786   }
149787
149788   if( nEntry ){
149789     int *aNew;                    /* New aiException[] array */
149790     int nNew;                     /* Number of valid entries in array aNew[] */
149791
149792     aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
149793     if( aNew==0 ) return SQLITE_NOMEM;
149794     nNew = p->nException;
149795
149796     z = (const unsigned char *)zIn;
149797     while( z<zTerm ){
149798       READ_UTF8(z, zTerm, iCode);
149799       if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum 
149800        && sqlite3FtsUnicodeIsdiacritic(iCode)==0
149801       ){
149802         int i, j;
149803         for(i=0; i<nNew && aNew[i]<iCode; i++);
149804         for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
149805         aNew[i] = iCode;
149806         nNew++;
149807       }
149808     }
149809     p->aiException = aNew;
149810     p->nException = nNew;
149811   }
149812
149813   return SQLITE_OK;
149814 }
149815
149816 /*
149817 ** Return true if the p->aiException[] array contains the value iCode.
149818 */
149819 static int unicodeIsException(unicode_tokenizer *p, int iCode){
149820   if( p->nException>0 ){
149821     int *a = p->aiException;
149822     int iLo = 0;
149823     int iHi = p->nException-1;
149824
149825     while( iHi>=iLo ){
149826       int iTest = (iHi + iLo) / 2;
149827       if( iCode==a[iTest] ){
149828         return 1;
149829       }else if( iCode>a[iTest] ){
149830         iLo = iTest+1;
149831       }else{
149832         iHi = iTest-1;
149833       }
149834     }
149835   }
149836
149837   return 0;
149838 }
149839
149840 /*
149841 ** Return true if, for the purposes of tokenization, codepoint iCode is
149842 ** considered a token character (not a separator).
149843 */
149844 static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
149845   assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
149846   return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
149847 }
149848
149849 /*
149850 ** Create a new tokenizer instance.
149851 */
149852 static int unicodeCreate(
149853   int nArg,                       /* Size of array argv[] */
149854   const char * const *azArg,      /* Tokenizer creation arguments */
149855   sqlite3_tokenizer **pp          /* OUT: New tokenizer handle */
149856 ){
149857   unicode_tokenizer *pNew;        /* New tokenizer object */
149858   int i;
149859   int rc = SQLITE_OK;
149860
149861   pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
149862   if( pNew==NULL ) return SQLITE_NOMEM;
149863   memset(pNew, 0, sizeof(unicode_tokenizer));
149864   pNew->bRemoveDiacritic = 1;
149865
149866   for(i=0; rc==SQLITE_OK && i<nArg; i++){
149867     const char *z = azArg[i];
149868     int n = (int)strlen(z);
149869
149870     if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
149871       pNew->bRemoveDiacritic = 1;
149872     }
149873     else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
149874       pNew->bRemoveDiacritic = 0;
149875     }
149876     else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
149877       rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
149878     }
149879     else if( n>=11 && memcmp("separators=", z, 11)==0 ){
149880       rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
149881     }
149882     else{
149883       /* Unrecognized argument */
149884       rc  = SQLITE_ERROR;
149885     }
149886   }
149887
149888   if( rc!=SQLITE_OK ){
149889     unicodeDestroy((sqlite3_tokenizer *)pNew);
149890     pNew = 0;
149891   }
149892   *pp = (sqlite3_tokenizer *)pNew;
149893   return rc;
149894 }
149895
149896 /*
149897 ** Prepare to begin tokenizing a particular string.  The input
149898 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
149899 ** used to incrementally tokenize this string is returned in 
149900 ** *ppCursor.
149901 */
149902 static int unicodeOpen(
149903   sqlite3_tokenizer *p,           /* The tokenizer */
149904   const char *aInput,             /* Input string */
149905   int nInput,                     /* Size of string aInput in bytes */
149906   sqlite3_tokenizer_cursor **pp   /* OUT: New cursor object */
149907 ){
149908   unicode_cursor *pCsr;
149909
149910   pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
149911   if( pCsr==0 ){
149912     return SQLITE_NOMEM;
149913   }
149914   memset(pCsr, 0, sizeof(unicode_cursor));
149915
149916   pCsr->aInput = (const unsigned char *)aInput;
149917   if( aInput==0 ){
149918     pCsr->nInput = 0;
149919   }else if( nInput<0 ){
149920     pCsr->nInput = (int)strlen(aInput);
149921   }else{
149922     pCsr->nInput = nInput;
149923   }
149924
149925   *pp = &pCsr->base;
149926   UNUSED_PARAMETER(p);
149927   return SQLITE_OK;
149928 }
149929
149930 /*
149931 ** Close a tokenization cursor previously opened by a call to
149932 ** simpleOpen() above.
149933 */
149934 static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
149935   unicode_cursor *pCsr = (unicode_cursor *) pCursor;
149936   sqlite3_free(pCsr->zToken);
149937   sqlite3_free(pCsr);
149938   return SQLITE_OK;
149939 }
149940
149941 /*
149942 ** Extract the next token from a tokenization cursor.  The cursor must
149943 ** have been opened by a prior call to simpleOpen().
149944 */
149945 static int unicodeNext(
149946   sqlite3_tokenizer_cursor *pC,   /* Cursor returned by simpleOpen */
149947   const char **paToken,           /* OUT: Token text */
149948   int *pnToken,                   /* OUT: Number of bytes at *paToken */
149949   int *piStart,                   /* OUT: Starting offset of token */
149950   int *piEnd,                     /* OUT: Ending offset of token */
149951   int *piPos                      /* OUT: Position integer of token */
149952 ){
149953   unicode_cursor *pCsr = (unicode_cursor *)pC;
149954   unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
149955   int iCode = 0;
149956   char *zOut;
149957   const unsigned char *z = &pCsr->aInput[pCsr->iOff];
149958   const unsigned char *zStart = z;
149959   const unsigned char *zEnd;
149960   const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
149961
149962   /* Scan past any delimiter characters before the start of the next token.
149963   ** Return SQLITE_DONE early if this takes us all the way to the end of 
149964   ** the input.  */
149965   while( z<zTerm ){
149966     READ_UTF8(z, zTerm, iCode);
149967     if( unicodeIsAlnum(p, iCode) ) break;
149968     zStart = z;
149969   }
149970   if( zStart>=zTerm ) return SQLITE_DONE;
149971
149972   zOut = pCsr->zToken;
149973   do {
149974     int iOut;
149975
149976     /* Grow the output buffer if required. */
149977     if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
149978       char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
149979       if( !zNew ) return SQLITE_NOMEM;
149980       zOut = &zNew[zOut - pCsr->zToken];
149981       pCsr->zToken = zNew;
149982       pCsr->nAlloc += 64;
149983     }
149984
149985     /* Write the folded case of the last character read to the output */
149986     zEnd = z;
149987     iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
149988     if( iOut ){
149989       WRITE_UTF8(zOut, iOut);
149990     }
149991
149992     /* If the cursor is not at EOF, read the next character */
149993     if( z>=zTerm ) break;
149994     READ_UTF8(z, zTerm, iCode);
149995   }while( unicodeIsAlnum(p, iCode) 
149996        || sqlite3FtsUnicodeIsdiacritic(iCode)
149997   );
149998
149999   /* Set the output variables and return. */
150000   pCsr->iOff = (int)(z - pCsr->aInput);
150001   *paToken = pCsr->zToken;
150002   *pnToken = (int)(zOut - pCsr->zToken);
150003   *piStart = (int)(zStart - pCsr->aInput);
150004   *piEnd = (int)(zEnd - pCsr->aInput);
150005   *piPos = pCsr->iToken++;
150006   return SQLITE_OK;
150007 }
150008
150009 /*
150010 ** Set *ppModule to a pointer to the sqlite3_tokenizer_module 
150011 ** structure for the unicode tokenizer.
150012 */
150013 SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
150014   static const sqlite3_tokenizer_module module = {
150015     0,
150016     unicodeCreate,
150017     unicodeDestroy,
150018     unicodeOpen,
150019     unicodeClose,
150020     unicodeNext,
150021     0,
150022   };
150023   *ppModule = &module;
150024 }
150025
150026 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
150027 #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
150028
150029 /************** End of fts3_unicode.c ****************************************/
150030 /************** Begin file fts3_unicode2.c ***********************************/
150031 /*
150032 ** 2012 May 25
150033 **
150034 ** The author disclaims copyright to this source code.  In place of
150035 ** a legal notice, here is a blessing:
150036 **
150037 **    May you do good and not evil.
150038 **    May you find forgiveness for yourself and forgive others.
150039 **    May you share freely, never taking more than you give.
150040 **
150041 ******************************************************************************
150042 */
150043
150044 /*
150045 ** DO NOT EDIT THIS MACHINE GENERATED FILE.
150046 */
150047
150048 #ifndef SQLITE_DISABLE_FTS3_UNICODE
150049 #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
150050
150051 /* #include <assert.h> */
150052
150053 /*
150054 ** Return true if the argument corresponds to a unicode codepoint
150055 ** classified as either a letter or a number. Otherwise false.
150056 **
150057 ** The results are undefined if the value passed to this function
150058 ** is less than zero.
150059 */
150060 SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
150061   /* Each unsigned integer in the following array corresponds to a contiguous
150062   ** range of unicode codepoints that are not either letters or numbers (i.e.
150063   ** codepoints for which this function should return 0).
150064   **
150065   ** The most significant 22 bits in each 32-bit value contain the first 
150066   ** codepoint in the range. The least significant 10 bits are used to store
150067   ** the size of the range (always at least 1). In other words, the value 
150068   ** ((C<<22) + N) represents a range of N codepoints starting with codepoint 
150069   ** C. It is not possible to represent a range larger than 1023 codepoints 
150070   ** using this format.
150071   */
150072   static const unsigned int aEntry[] = {
150073     0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
150074     0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
150075     0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
150076     0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
150077     0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
150078     0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
150079     0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
150080     0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
150081     0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
150082     0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
150083     0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
150084     0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
150085     0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
150086     0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
150087     0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
150088     0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
150089     0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
150090     0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
150091     0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
150092     0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
150093     0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
150094     0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
150095     0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
150096     0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
150097     0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
150098     0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
150099     0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
150100     0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
150101     0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
150102     0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
150103     0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
150104     0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
150105     0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
150106     0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
150107     0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
150108     0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
150109     0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
150110     0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
150111     0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
150112     0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
150113     0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
150114     0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
150115     0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
150116     0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
150117     0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
150118     0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
150119     0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
150120     0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
150121     0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
150122     0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
150123     0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
150124     0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
150125     0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
150126     0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
150127     0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
150128     0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
150129     0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
150130     0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
150131     0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
150132     0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
150133     0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
150134     0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
150135     0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
150136     0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
150137     0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
150138     0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
150139     0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
150140     0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
150141     0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
150142     0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
150143     0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
150144     0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
150145     0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
150146     0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
150147     0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
150148     0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
150149     0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
150150     0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
150151     0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
150152     0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
150153     0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
150154     0x380400F0,
150155   };
150156   static const unsigned int aAscii[4] = {
150157     0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
150158   };
150159
150160   if( c<128 ){
150161     return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
150162   }else if( c<(1<<22) ){
150163     unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
150164     int iRes = 0;
150165     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
150166     int iLo = 0;
150167     while( iHi>=iLo ){
150168       int iTest = (iHi + iLo) / 2;
150169       if( key >= aEntry[iTest] ){
150170         iRes = iTest;
150171         iLo = iTest+1;
150172       }else{
150173         iHi = iTest-1;
150174       }
150175     }
150176     assert( aEntry[0]<key );
150177     assert( key>=aEntry[iRes] );
150178     return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
150179   }
150180   return 1;
150181 }
150182
150183
150184 /*
150185 ** If the argument is a codepoint corresponding to a lowercase letter
150186 ** in the ASCII range with a diacritic added, return the codepoint
150187 ** of the ASCII letter only. For example, if passed 235 - "LATIN
150188 ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
150189 ** E"). The resuls of passing a codepoint that corresponds to an
150190 ** uppercase letter are undefined.
150191 */
150192 static int remove_diacritic(int c){
150193   unsigned short aDia[] = {
150194         0,  1797,  1848,  1859,  1891,  1928,  1940,  1995, 
150195      2024,  2040,  2060,  2110,  2168,  2206,  2264,  2286, 
150196      2344,  2383,  2472,  2488,  2516,  2596,  2668,  2732, 
150197      2782,  2842,  2894,  2954,  2984,  3000,  3028,  3336, 
150198      3456,  3696,  3712,  3728,  3744,  3896,  3912,  3928, 
150199      3968,  4008,  4040,  4106,  4138,  4170,  4202,  4234, 
150200      4266,  4296,  4312,  4344,  4408,  4424,  4472,  4504, 
150201      6148,  6198,  6264,  6280,  6360,  6429,  6505,  6529, 
150202     61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726, 
150203     61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122, 
150204     62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536, 
150205     62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730, 
150206     62924, 63050, 63082, 63274, 63390, 
150207   };
150208   char aChar[] = {
150209     '\0', 'a',  'c',  'e',  'i',  'n',  'o',  'u',  'y',  'y',  'a',  'c',  
150210     'd',  'e',  'e',  'g',  'h',  'i',  'j',  'k',  'l',  'n',  'o',  'r',  
150211     's',  't',  'u',  'u',  'w',  'y',  'z',  'o',  'u',  'a',  'i',  'o',  
150212     'u',  'g',  'k',  'o',  'j',  'g',  'n',  'a',  'e',  'i',  'o',  'r',  
150213     'u',  's',  't',  'h',  'a',  'e',  'o',  'y',  '\0', '\0', '\0', '\0', 
150214     '\0', '\0', '\0', '\0', 'a',  'b',  'd',  'd',  'e',  'f',  'g',  'h',  
150215     'h',  'i',  'k',  'l',  'l',  'm',  'n',  'p',  'r',  'r',  's',  't',  
150216     'u',  'v',  'w',  'w',  'x',  'y',  'z',  'h',  't',  'w',  'y',  'a',  
150217     'e',  'i',  'o',  'u',  'y',  
150218   };
150219
150220   unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
150221   int iRes = 0;
150222   int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
150223   int iLo = 0;
150224   while( iHi>=iLo ){
150225     int iTest = (iHi + iLo) / 2;
150226     if( key >= aDia[iTest] ){
150227       iRes = iTest;
150228       iLo = iTest+1;
150229     }else{
150230       iHi = iTest-1;
150231     }
150232   }
150233   assert( key>=aDia[iRes] );
150234   return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
150235 }
150236
150237
150238 /*
150239 ** Return true if the argument interpreted as a unicode codepoint
150240 ** is a diacritical modifier character.
150241 */
150242 SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
150243   unsigned int mask0 = 0x08029FDF;
150244   unsigned int mask1 = 0x000361F8;
150245   if( c<768 || c>817 ) return 0;
150246   return (c < 768+32) ?
150247       (mask0 & (1 << (c-768))) :
150248       (mask1 & (1 << (c-768-32)));
150249 }
150250
150251
150252 /*
150253 ** Interpret the argument as a unicode codepoint. If the codepoint
150254 ** is an upper case character that has a lower case equivalent,
150255 ** return the codepoint corresponding to the lower case version.
150256 ** Otherwise, return a copy of the argument.
150257 **
150258 ** The results are undefined if the value passed to this function
150259 ** is less than zero.
150260 */
150261 SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
150262   /* Each entry in the following array defines a rule for folding a range
150263   ** of codepoints to lower case. The rule applies to a range of nRange
150264   ** codepoints starting at codepoint iCode.
150265   **
150266   ** If the least significant bit in flags is clear, then the rule applies
150267   ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
150268   ** need to be folded). Or, if it is set, then the rule only applies to
150269   ** every second codepoint in the range, starting with codepoint C.
150270   **
150271   ** The 7 most significant bits in flags are an index into the aiOff[]
150272   ** array. If a specific codepoint C does require folding, then its lower
150273   ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
150274   **
150275   ** The contents of this array are generated by parsing the CaseFolding.txt
150276   ** file distributed as part of the "Unicode Character Database". See
150277   ** http://www.unicode.org for details.
150278   */
150279   static const struct TableEntry {
150280     unsigned short iCode;
150281     unsigned char flags;
150282     unsigned char nRange;
150283   } aEntry[] = {
150284     {65, 14, 26},          {181, 64, 1},          {192, 14, 23},
150285     {216, 14, 7},          {256, 1, 48},          {306, 1, 6},
150286     {313, 1, 16},          {330, 1, 46},          {376, 116, 1},
150287     {377, 1, 6},           {383, 104, 1},         {385, 50, 1},
150288     {386, 1, 4},           {390, 44, 1},          {391, 0, 1},
150289     {393, 42, 2},          {395, 0, 1},           {398, 32, 1},
150290     {399, 38, 1},          {400, 40, 1},          {401, 0, 1},
150291     {403, 42, 1},          {404, 46, 1},          {406, 52, 1},
150292     {407, 48, 1},          {408, 0, 1},           {412, 52, 1},
150293     {413, 54, 1},          {415, 56, 1},          {416, 1, 6},
150294     {422, 60, 1},          {423, 0, 1},           {425, 60, 1},
150295     {428, 0, 1},           {430, 60, 1},          {431, 0, 1},
150296     {433, 58, 2},          {435, 1, 4},           {439, 62, 1},
150297     {440, 0, 1},           {444, 0, 1},           {452, 2, 1},
150298     {453, 0, 1},           {455, 2, 1},           {456, 0, 1},
150299     {458, 2, 1},           {459, 1, 18},          {478, 1, 18},
150300     {497, 2, 1},           {498, 1, 4},           {502, 122, 1},
150301     {503, 134, 1},         {504, 1, 40},          {544, 110, 1},
150302     {546, 1, 18},          {570, 70, 1},          {571, 0, 1},
150303     {573, 108, 1},         {574, 68, 1},          {577, 0, 1},
150304     {579, 106, 1},         {580, 28, 1},          {581, 30, 1},
150305     {582, 1, 10},          {837, 36, 1},          {880, 1, 4},
150306     {886, 0, 1},           {902, 18, 1},          {904, 16, 3},
150307     {908, 26, 1},          {910, 24, 2},          {913, 14, 17},
150308     {931, 14, 9},          {962, 0, 1},           {975, 4, 1},
150309     {976, 140, 1},         {977, 142, 1},         {981, 146, 1},
150310     {982, 144, 1},         {984, 1, 24},          {1008, 136, 1},
150311     {1009, 138, 1},        {1012, 130, 1},        {1013, 128, 1},
150312     {1015, 0, 1},          {1017, 152, 1},        {1018, 0, 1},
150313     {1021, 110, 3},        {1024, 34, 16},        {1040, 14, 32},
150314     {1120, 1, 34},         {1162, 1, 54},         {1216, 6, 1},
150315     {1217, 1, 14},         {1232, 1, 88},         {1329, 22, 38},
150316     {4256, 66, 38},        {4295, 66, 1},         {4301, 66, 1},
150317     {7680, 1, 150},        {7835, 132, 1},        {7838, 96, 1},
150318     {7840, 1, 96},         {7944, 150, 8},        {7960, 150, 6},
150319     {7976, 150, 8},        {7992, 150, 8},        {8008, 150, 6},
150320     {8025, 151, 8},        {8040, 150, 8},        {8072, 150, 8},
150321     {8088, 150, 8},        {8104, 150, 8},        {8120, 150, 2},
150322     {8122, 126, 2},        {8124, 148, 1},        {8126, 100, 1},
150323     {8136, 124, 4},        {8140, 148, 1},        {8152, 150, 2},
150324     {8154, 120, 2},        {8168, 150, 2},        {8170, 118, 2},
150325     {8172, 152, 1},        {8184, 112, 2},        {8186, 114, 2},
150326     {8188, 148, 1},        {8486, 98, 1},         {8490, 92, 1},
150327     {8491, 94, 1},         {8498, 12, 1},         {8544, 8, 16},
150328     {8579, 0, 1},          {9398, 10, 26},        {11264, 22, 47},
150329     {11360, 0, 1},         {11362, 88, 1},        {11363, 102, 1},
150330     {11364, 90, 1},        {11367, 1, 6},         {11373, 84, 1},
150331     {11374, 86, 1},        {11375, 80, 1},        {11376, 82, 1},
150332     {11378, 0, 1},         {11381, 0, 1},         {11390, 78, 2},
150333     {11392, 1, 100},       {11499, 1, 4},         {11506, 0, 1},
150334     {42560, 1, 46},        {42624, 1, 24},        {42786, 1, 14},
150335     {42802, 1, 62},        {42873, 1, 4},         {42877, 76, 1},
150336     {42878, 1, 10},        {42891, 0, 1},         {42893, 74, 1},
150337     {42896, 1, 4},         {42912, 1, 10},        {42922, 72, 1},
150338     {65313, 14, 26},       
150339   };
150340   static const unsigned short aiOff[] = {
150341    1,     2,     8,     15,    16,    26,    28,    32,    
150342    37,    38,    40,    48,    63,    64,    69,    71,    
150343    79,    80,    116,   202,   203,   205,   206,   207,   
150344    209,   210,   211,   213,   214,   217,   218,   219,   
150345    775,   7264,  10792, 10795, 23228, 23256, 30204, 54721, 
150346    54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274, 
150347    57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406, 
150348    65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462, 
150349    65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511, 
150350    65514, 65521, 65527, 65528, 65529, 
150351   };
150352
150353   int ret = c;
150354
150355   assert( c>=0 );
150356   assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
150357
150358   if( c<128 ){
150359     if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
150360   }else if( c<65536 ){
150361     int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
150362     int iLo = 0;
150363     int iRes = -1;
150364
150365     while( iHi>=iLo ){
150366       int iTest = (iHi + iLo) / 2;
150367       int cmp = (c - aEntry[iTest].iCode);
150368       if( cmp>=0 ){
150369         iRes = iTest;
150370         iLo = iTest+1;
150371       }else{
150372         iHi = iTest-1;
150373       }
150374     }
150375     assert( iRes<0 || c>=aEntry[iRes].iCode );
150376
150377     if( iRes>=0 ){
150378       const struct TableEntry *p = &aEntry[iRes];
150379       if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
150380         ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
150381         assert( ret>0 );
150382       }
150383     }
150384
150385     if( bRemoveDiacritic ) ret = remove_diacritic(ret);
150386   }
150387   
150388   else if( c>=66560 && c<66600 ){
150389     ret = c + 40;
150390   }
150391
150392   return ret;
150393 }
150394 #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
150395 #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
150396
150397 /************** End of fts3_unicode2.c ***************************************/
150398 /************** Begin file rtree.c *******************************************/
150399 /*
150400 ** 2001 September 15
150401 **
150402 ** The author disclaims copyright to this source code.  In place of
150403 ** a legal notice, here is a blessing:
150404 **
150405 **    May you do good and not evil.
150406 **    May you find forgiveness for yourself and forgive others.
150407 **    May you share freely, never taking more than you give.
150408 **
150409 *************************************************************************
150410 ** This file contains code for implementations of the r-tree and r*-tree
150411 ** algorithms packaged as an SQLite virtual table module.
150412 */
150413
150414 /*
150415 ** Database Format of R-Tree Tables
150416 ** --------------------------------
150417 **
150418 ** The data structure for a single virtual r-tree table is stored in three 
150419 ** native SQLite tables declared as follows. In each case, the '%' character
150420 ** in the table name is replaced with the user-supplied name of the r-tree
150421 ** table.
150422 **
150423 **   CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
150424 **   CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
150425 **   CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
150426 **
150427 ** The data for each node of the r-tree structure is stored in the %_node
150428 ** table. For each node that is not the root node of the r-tree, there is
150429 ** an entry in the %_parent table associating the node with its parent.
150430 ** And for each row of data in the table, there is an entry in the %_rowid
150431 ** table that maps from the entries rowid to the id of the node that it
150432 ** is stored on.
150433 **
150434 ** The root node of an r-tree always exists, even if the r-tree table is
150435 ** empty. The nodeno of the root node is always 1. All other nodes in the
150436 ** table must be the same size as the root node. The content of each node
150437 ** is formatted as follows:
150438 **
150439 **   1. If the node is the root node (node 1), then the first 2 bytes
150440 **      of the node contain the tree depth as a big-endian integer.
150441 **      For non-root nodes, the first 2 bytes are left unused.
150442 **
150443 **   2. The next 2 bytes contain the number of entries currently 
150444 **      stored in the node.
150445 **
150446 **   3. The remainder of the node contains the node entries. Each entry
150447 **      consists of a single 8-byte integer followed by an even number
150448 **      of 4-byte coordinates. For leaf nodes the integer is the rowid
150449 **      of a record. For internal nodes it is the node number of a
150450 **      child page.
150451 */
150452
150453 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
150454
150455 #ifndef SQLITE_CORE
150456   SQLITE_EXTENSION_INIT1
150457 #else
150458 #endif
150459
150460 /* #include <string.h> */
150461 /* #include <assert.h> */
150462 /* #include <stdio.h> */
150463
150464 #ifndef SQLITE_AMALGAMATION
150465 #include "sqlite3rtree.h"
150466 typedef sqlite3_int64 i64;
150467 typedef unsigned char u8;
150468 typedef unsigned short u16;
150469 typedef unsigned int u32;
150470 #endif
150471
150472 /*  The following macro is used to suppress compiler warnings.
150473 */
150474 #ifndef UNUSED_PARAMETER
150475 # define UNUSED_PARAMETER(x) (void)(x)
150476 #endif
150477
150478 typedef struct Rtree Rtree;
150479 typedef struct RtreeCursor RtreeCursor;
150480 typedef struct RtreeNode RtreeNode;
150481 typedef struct RtreeCell RtreeCell;
150482 typedef struct RtreeConstraint RtreeConstraint;
150483 typedef struct RtreeMatchArg RtreeMatchArg;
150484 typedef struct RtreeGeomCallback RtreeGeomCallback;
150485 typedef union RtreeCoord RtreeCoord;
150486 typedef struct RtreeSearchPoint RtreeSearchPoint;
150487
150488 /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
150489 #define RTREE_MAX_DIMENSIONS 5
150490
150491 /* Size of hash table Rtree.aHash. This hash table is not expected to
150492 ** ever contain very many entries, so a fixed number of buckets is 
150493 ** used.
150494 */
150495 #define HASHSIZE 97
150496
150497 /* The xBestIndex method of this virtual table requires an estimate of
150498 ** the number of rows in the virtual table to calculate the costs of
150499 ** various strategies. If possible, this estimate is loaded from the
150500 ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
150501 ** Otherwise, if no sqlite_stat1 entry is available, use 
150502 ** RTREE_DEFAULT_ROWEST.
150503 */
150504 #define RTREE_DEFAULT_ROWEST 1048576
150505 #define RTREE_MIN_ROWEST         100
150506
150507 /* 
150508 ** An rtree virtual-table object.
150509 */
150510 struct Rtree {
150511   sqlite3_vtab base;          /* Base class.  Must be first */
150512   sqlite3 *db;                /* Host database connection */
150513   int iNodeSize;              /* Size in bytes of each node in the node table */
150514   u8 nDim;                    /* Number of dimensions */
150515   u8 eCoordType;              /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
150516   u8 nBytesPerCell;           /* Bytes consumed per cell */
150517   int iDepth;                 /* Current depth of the r-tree structure */
150518   char *zDb;                  /* Name of database containing r-tree table */
150519   char *zName;                /* Name of r-tree table */ 
150520   int nBusy;                  /* Current number of users of this structure */
150521   i64 nRowEst;                /* Estimated number of rows in this table */
150522
150523   /* List of nodes removed during a CondenseTree operation. List is
150524   ** linked together via the pointer normally used for hash chains -
150525   ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree 
150526   ** headed by the node (leaf nodes have RtreeNode.iNode==0).
150527   */
150528   RtreeNode *pDeleted;
150529   int iReinsertHeight;        /* Height of sub-trees Reinsert() has run on */
150530
150531   /* Statements to read/write/delete a record from xxx_node */
150532   sqlite3_stmt *pReadNode;
150533   sqlite3_stmt *pWriteNode;
150534   sqlite3_stmt *pDeleteNode;
150535
150536   /* Statements to read/write/delete a record from xxx_rowid */
150537   sqlite3_stmt *pReadRowid;
150538   sqlite3_stmt *pWriteRowid;
150539   sqlite3_stmt *pDeleteRowid;
150540
150541   /* Statements to read/write/delete a record from xxx_parent */
150542   sqlite3_stmt *pReadParent;
150543   sqlite3_stmt *pWriteParent;
150544   sqlite3_stmt *pDeleteParent;
150545
150546   RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */ 
150547 };
150548
150549 /* Possible values for Rtree.eCoordType: */
150550 #define RTREE_COORD_REAL32 0
150551 #define RTREE_COORD_INT32  1
150552
150553 /*
150554 ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
150555 ** only deal with integer coordinates.  No floating point operations
150556 ** will be done.
150557 */
150558 #ifdef SQLITE_RTREE_INT_ONLY
150559   typedef sqlite3_int64 RtreeDValue;       /* High accuracy coordinate */
150560   typedef int RtreeValue;                  /* Low accuracy coordinate */
150561 # define RTREE_ZERO 0
150562 #else
150563   typedef double RtreeDValue;              /* High accuracy coordinate */
150564   typedef float RtreeValue;                /* Low accuracy coordinate */
150565 # define RTREE_ZERO 0.0
150566 #endif
150567
150568 /*
150569 ** When doing a search of an r-tree, instances of the following structure
150570 ** record intermediate results from the tree walk.
150571 **
150572 ** The id is always a node-id.  For iLevel>=1 the id is the node-id of
150573 ** the node that the RtreeSearchPoint represents.  When iLevel==0, however,
150574 ** the id is of the parent node and the cell that RtreeSearchPoint
150575 ** represents is the iCell-th entry in the parent node.
150576 */
150577 struct RtreeSearchPoint {
150578   RtreeDValue rScore;    /* The score for this node.  Smallest goes first. */
150579   sqlite3_int64 id;      /* Node ID */
150580   u8 iLevel;             /* 0=entries.  1=leaf node.  2+ for higher */
150581   u8 eWithin;            /* PARTLY_WITHIN or FULLY_WITHIN */
150582   u8 iCell;              /* Cell index within the node */
150583 };
150584
150585 /*
150586 ** The minimum number of cells allowed for a node is a third of the 
150587 ** maximum. In Gutman's notation:
150588 **
150589 **     m = M/3
150590 **
150591 ** If an R*-tree "Reinsert" operation is required, the same number of
150592 ** cells are removed from the overfull node and reinserted into the tree.
150593 */
150594 #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
150595 #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
150596 #define RTREE_MAXCELLS 51
150597
150598 /*
150599 ** The smallest possible node-size is (512-64)==448 bytes. And the largest
150600 ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
150601 ** Therefore all non-root nodes must contain at least 3 entries. Since 
150602 ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
150603 ** 40 or less.
150604 */
150605 #define RTREE_MAX_DEPTH 40
150606
150607
150608 /*
150609 ** Number of entries in the cursor RtreeNode cache.  The first entry is
150610 ** used to cache the RtreeNode for RtreeCursor.sPoint.  The remaining
150611 ** entries cache the RtreeNode for the first elements of the priority queue.
150612 */
150613 #define RTREE_CACHE_SZ  5
150614
150615 /* 
150616 ** An rtree cursor object.
150617 */
150618 struct RtreeCursor {
150619   sqlite3_vtab_cursor base;         /* Base class.  Must be first */
150620   u8 atEOF;                         /* True if at end of search */
150621   u8 bPoint;                        /* True if sPoint is valid */
150622   int iStrategy;                    /* Copy of idxNum search parameter */
150623   int nConstraint;                  /* Number of entries in aConstraint */
150624   RtreeConstraint *aConstraint;     /* Search constraints. */
150625   int nPointAlloc;                  /* Number of slots allocated for aPoint[] */
150626   int nPoint;                       /* Number of slots used in aPoint[] */
150627   int mxLevel;                      /* iLevel value for root of the tree */
150628   RtreeSearchPoint *aPoint;         /* Priority queue for search points */
150629   RtreeSearchPoint sPoint;          /* Cached next search point */
150630   RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
150631   u32 anQueue[RTREE_MAX_DEPTH+1];   /* Number of queued entries by iLevel */
150632 };
150633
150634 /* Return the Rtree of a RtreeCursor */
150635 #define RTREE_OF_CURSOR(X)   ((Rtree*)((X)->base.pVtab))
150636
150637 /*
150638 ** A coordinate can be either a floating point number or a integer.  All
150639 ** coordinates within a single R-Tree are always of the same time.
150640 */
150641 union RtreeCoord {
150642   RtreeValue f;      /* Floating point value */
150643   int i;             /* Integer value */
150644   u32 u;             /* Unsigned for byte-order conversions */
150645 };
150646
150647 /*
150648 ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
150649 ** formatted as a RtreeDValue (double or int64). This macro assumes that local
150650 ** variable pRtree points to the Rtree structure associated with the
150651 ** RtreeCoord.
150652 */
150653 #ifdef SQLITE_RTREE_INT_ONLY
150654 # define DCOORD(coord) ((RtreeDValue)coord.i)
150655 #else
150656 # define DCOORD(coord) (                           \
150657     (pRtree->eCoordType==RTREE_COORD_REAL32) ?      \
150658       ((double)coord.f) :                           \
150659       ((double)coord.i)                             \
150660   )
150661 #endif
150662
150663 /*
150664 ** A search constraint.
150665 */
150666 struct RtreeConstraint {
150667   int iCoord;                     /* Index of constrained coordinate */
150668   int op;                         /* Constraining operation */
150669   union {
150670     RtreeDValue rValue;             /* Constraint value. */
150671     int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
150672     int (*xQueryFunc)(sqlite3_rtree_query_info*);
150673   } u;
150674   sqlite3_rtree_query_info *pInfo;  /* xGeom and xQueryFunc argument */
150675 };
150676
150677 /* Possible values for RtreeConstraint.op */
150678 #define RTREE_EQ    0x41  /* A */
150679 #define RTREE_LE    0x42  /* B */
150680 #define RTREE_LT    0x43  /* C */
150681 #define RTREE_GE    0x44  /* D */
150682 #define RTREE_GT    0x45  /* E */
150683 #define RTREE_MATCH 0x46  /* F: Old-style sqlite3_rtree_geometry_callback() */
150684 #define RTREE_QUERY 0x47  /* G: New-style sqlite3_rtree_query_callback() */
150685
150686
150687 /* 
150688 ** An rtree structure node.
150689 */
150690 struct RtreeNode {
150691   RtreeNode *pParent;         /* Parent node */
150692   i64 iNode;                  /* The node number */
150693   int nRef;                   /* Number of references to this node */
150694   int isDirty;                /* True if the node needs to be written to disk */
150695   u8 *zData;                  /* Content of the node, as should be on disk */
150696   RtreeNode *pNext;           /* Next node in this hash collision chain */
150697 };
150698
150699 /* Return the number of cells in a node  */
150700 #define NCELL(pNode) readInt16(&(pNode)->zData[2])
150701
150702 /* 
150703 ** A single cell from a node, deserialized
150704 */
150705 struct RtreeCell {
150706   i64 iRowid;                                 /* Node or entry ID */
150707   RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2];  /* Bounding box coordinates */
150708 };
150709
150710
150711 /*
150712 ** This object becomes the sqlite3_user_data() for the SQL functions
150713 ** that are created by sqlite3_rtree_geometry_callback() and
150714 ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
150715 ** operators in order to constrain a search.
150716 **
150717 ** xGeom and xQueryFunc are the callback functions.  Exactly one of 
150718 ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
150719 ** SQL function was created using sqlite3_rtree_geometry_callback() or
150720 ** sqlite3_rtree_query_callback().
150721 ** 
150722 ** This object is deleted automatically by the destructor mechanism in
150723 ** sqlite3_create_function_v2().
150724 */
150725 struct RtreeGeomCallback {
150726   int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
150727   int (*xQueryFunc)(sqlite3_rtree_query_info*);
150728   void (*xDestructor)(void*);
150729   void *pContext;
150730 };
150731
150732
150733 /*
150734 ** Value for the first field of every RtreeMatchArg object. The MATCH
150735 ** operator tests that the first field of a blob operand matches this
150736 ** value to avoid operating on invalid blobs (which could cause a segfault).
150737 */
150738 #define RTREE_GEOMETRY_MAGIC 0x891245AB
150739
150740 /*
150741 ** An instance of this structure (in the form of a BLOB) is returned by
150742 ** the SQL functions that sqlite3_rtree_geometry_callback() and
150743 ** sqlite3_rtree_query_callback() create, and is read as the right-hand
150744 ** operand to the MATCH operator of an R-Tree.
150745 */
150746 struct RtreeMatchArg {
150747   u32 magic;                  /* Always RTREE_GEOMETRY_MAGIC */
150748   RtreeGeomCallback cb;       /* Info about the callback functions */
150749   int nParam;                 /* Number of parameters to the SQL function */
150750   RtreeDValue aParam[1];      /* Values for parameters to the SQL function */
150751 };
150752
150753 #ifndef MAX
150754 # define MAX(x,y) ((x) < (y) ? (y) : (x))
150755 #endif
150756 #ifndef MIN
150757 # define MIN(x,y) ((x) > (y) ? (y) : (x))
150758 #endif
150759
150760 /*
150761 ** Functions to deserialize a 16 bit integer, 32 bit real number and
150762 ** 64 bit integer. The deserialized value is returned.
150763 */
150764 static int readInt16(u8 *p){
150765   return (p[0]<<8) + p[1];
150766 }
150767 static void readCoord(u8 *p, RtreeCoord *pCoord){
150768   pCoord->u = (
150769     (((u32)p[0]) << 24) + 
150770     (((u32)p[1]) << 16) + 
150771     (((u32)p[2]) <<  8) + 
150772     (((u32)p[3]) <<  0)
150773   );
150774 }
150775 static i64 readInt64(u8 *p){
150776   return (
150777     (((i64)p[0]) << 56) + 
150778     (((i64)p[1]) << 48) + 
150779     (((i64)p[2]) << 40) + 
150780     (((i64)p[3]) << 32) + 
150781     (((i64)p[4]) << 24) + 
150782     (((i64)p[5]) << 16) + 
150783     (((i64)p[6]) <<  8) + 
150784     (((i64)p[7]) <<  0)
150785   );
150786 }
150787
150788 /*
150789 ** Functions to serialize a 16 bit integer, 32 bit real number and
150790 ** 64 bit integer. The value returned is the number of bytes written
150791 ** to the argument buffer (always 2, 4 and 8 respectively).
150792 */
150793 static int writeInt16(u8 *p, int i){
150794   p[0] = (i>> 8)&0xFF;
150795   p[1] = (i>> 0)&0xFF;
150796   return 2;
150797 }
150798 static int writeCoord(u8 *p, RtreeCoord *pCoord){
150799   u32 i;
150800   assert( sizeof(RtreeCoord)==4 );
150801   assert( sizeof(u32)==4 );
150802   i = pCoord->u;
150803   p[0] = (i>>24)&0xFF;
150804   p[1] = (i>>16)&0xFF;
150805   p[2] = (i>> 8)&0xFF;
150806   p[3] = (i>> 0)&0xFF;
150807   return 4;
150808 }
150809 static int writeInt64(u8 *p, i64 i){
150810   p[0] = (i>>56)&0xFF;
150811   p[1] = (i>>48)&0xFF;
150812   p[2] = (i>>40)&0xFF;
150813   p[3] = (i>>32)&0xFF;
150814   p[4] = (i>>24)&0xFF;
150815   p[5] = (i>>16)&0xFF;
150816   p[6] = (i>> 8)&0xFF;
150817   p[7] = (i>> 0)&0xFF;
150818   return 8;
150819 }
150820
150821 /*
150822 ** Increment the reference count of node p.
150823 */
150824 static void nodeReference(RtreeNode *p){
150825   if( p ){
150826     p->nRef++;
150827   }
150828 }
150829
150830 /*
150831 ** Clear the content of node p (set all bytes to 0x00).
150832 */
150833 static void nodeZero(Rtree *pRtree, RtreeNode *p){
150834   memset(&p->zData[2], 0, pRtree->iNodeSize-2);
150835   p->isDirty = 1;
150836 }
150837
150838 /*
150839 ** Given a node number iNode, return the corresponding key to use
150840 ** in the Rtree.aHash table.
150841 */
150842 static int nodeHash(i64 iNode){
150843   return iNode % HASHSIZE;
150844 }
150845
150846 /*
150847 ** Search the node hash table for node iNode. If found, return a pointer
150848 ** to it. Otherwise, return 0.
150849 */
150850 static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
150851   RtreeNode *p;
150852   for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
150853   return p;
150854 }
150855
150856 /*
150857 ** Add node pNode to the node hash table.
150858 */
150859 static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
150860   int iHash;
150861   assert( pNode->pNext==0 );
150862   iHash = nodeHash(pNode->iNode);
150863   pNode->pNext = pRtree->aHash[iHash];
150864   pRtree->aHash[iHash] = pNode;
150865 }
150866
150867 /*
150868 ** Remove node pNode from the node hash table.
150869 */
150870 static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
150871   RtreeNode **pp;
150872   if( pNode->iNode!=0 ){
150873     pp = &pRtree->aHash[nodeHash(pNode->iNode)];
150874     for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
150875     *pp = pNode->pNext;
150876     pNode->pNext = 0;
150877   }
150878 }
150879
150880 /*
150881 ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
150882 ** indicating that node has not yet been assigned a node number. It is
150883 ** assigned a node number when nodeWrite() is called to write the
150884 ** node contents out to the database.
150885 */
150886 static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
150887   RtreeNode *pNode;
150888   pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
150889   if( pNode ){
150890     memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
150891     pNode->zData = (u8 *)&pNode[1];
150892     pNode->nRef = 1;
150893     pNode->pParent = pParent;
150894     pNode->isDirty = 1;
150895     nodeReference(pParent);
150896   }
150897   return pNode;
150898 }
150899
150900 /*
150901 ** Obtain a reference to an r-tree node.
150902 */
150903 static int nodeAcquire(
150904   Rtree *pRtree,             /* R-tree structure */
150905   i64 iNode,                 /* Node number to load */
150906   RtreeNode *pParent,        /* Either the parent node or NULL */
150907   RtreeNode **ppNode         /* OUT: Acquired node */
150908 ){
150909   int rc;
150910   int rc2 = SQLITE_OK;
150911   RtreeNode *pNode;
150912
150913   /* Check if the requested node is already in the hash table. If so,
150914   ** increase its reference count and return it.
150915   */
150916   if( (pNode = nodeHashLookup(pRtree, iNode)) ){
150917     assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
150918     if( pParent && !pNode->pParent ){
150919       nodeReference(pParent);
150920       pNode->pParent = pParent;
150921     }
150922     pNode->nRef++;
150923     *ppNode = pNode;
150924     return SQLITE_OK;
150925   }
150926
150927   sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
150928   rc = sqlite3_step(pRtree->pReadNode);
150929   if( rc==SQLITE_ROW ){
150930     const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
150931     if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
150932       pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
150933       if( !pNode ){
150934         rc2 = SQLITE_NOMEM;
150935       }else{
150936         pNode->pParent = pParent;
150937         pNode->zData = (u8 *)&pNode[1];
150938         pNode->nRef = 1;
150939         pNode->iNode = iNode;
150940         pNode->isDirty = 0;
150941         pNode->pNext = 0;
150942         memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
150943         nodeReference(pParent);
150944       }
150945     }
150946   }
150947   rc = sqlite3_reset(pRtree->pReadNode);
150948   if( rc==SQLITE_OK ) rc = rc2;
150949
150950   /* If the root node was just loaded, set pRtree->iDepth to the height
150951   ** of the r-tree structure. A height of zero means all data is stored on
150952   ** the root node. A height of one means the children of the root node
150953   ** are the leaves, and so on. If the depth as specified on the root node
150954   ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
150955   */
150956   if( pNode && iNode==1 ){
150957     pRtree->iDepth = readInt16(pNode->zData);
150958     if( pRtree->iDepth>RTREE_MAX_DEPTH ){
150959       rc = SQLITE_CORRUPT_VTAB;
150960     }
150961   }
150962
150963   /* If no error has occurred so far, check if the "number of entries"
150964   ** field on the node is too large. If so, set the return code to 
150965   ** SQLITE_CORRUPT_VTAB.
150966   */
150967   if( pNode && rc==SQLITE_OK ){
150968     if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
150969       rc = SQLITE_CORRUPT_VTAB;
150970     }
150971   }
150972
150973   if( rc==SQLITE_OK ){
150974     if( pNode!=0 ){
150975       nodeHashInsert(pRtree, pNode);
150976     }else{
150977       rc = SQLITE_CORRUPT_VTAB;
150978     }
150979     *ppNode = pNode;
150980   }else{
150981     sqlite3_free(pNode);
150982     *ppNode = 0;
150983   }
150984
150985   return rc;
150986 }
150987
150988 /*
150989 ** Overwrite cell iCell of node pNode with the contents of pCell.
150990 */
150991 static void nodeOverwriteCell(
150992   Rtree *pRtree,             /* The overall R-Tree */
150993   RtreeNode *pNode,          /* The node into which the cell is to be written */
150994   RtreeCell *pCell,          /* The cell to write */
150995   int iCell                  /* Index into pNode into which pCell is written */
150996 ){
150997   int ii;
150998   u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
150999   p += writeInt64(p, pCell->iRowid);
151000   for(ii=0; ii<(pRtree->nDim*2); ii++){
151001     p += writeCoord(p, &pCell->aCoord[ii]);
151002   }
151003   pNode->isDirty = 1;
151004 }
151005
151006 /*
151007 ** Remove the cell with index iCell from node pNode.
151008 */
151009 static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
151010   u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
151011   u8 *pSrc = &pDst[pRtree->nBytesPerCell];
151012   int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
151013   memmove(pDst, pSrc, nByte);
151014   writeInt16(&pNode->zData[2], NCELL(pNode)-1);
151015   pNode->isDirty = 1;
151016 }
151017
151018 /*
151019 ** Insert the contents of cell pCell into node pNode. If the insert
151020 ** is successful, return SQLITE_OK.
151021 **
151022 ** If there is not enough free space in pNode, return SQLITE_FULL.
151023 */
151024 static int nodeInsertCell(
151025   Rtree *pRtree,                /* The overall R-Tree */
151026   RtreeNode *pNode,             /* Write new cell into this node */
151027   RtreeCell *pCell              /* The cell to be inserted */
151028 ){
151029   int nCell;                    /* Current number of cells in pNode */
151030   int nMaxCell;                 /* Maximum number of cells for pNode */
151031
151032   nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
151033   nCell = NCELL(pNode);
151034
151035   assert( nCell<=nMaxCell );
151036   if( nCell<nMaxCell ){
151037     nodeOverwriteCell(pRtree, pNode, pCell, nCell);
151038     writeInt16(&pNode->zData[2], nCell+1);
151039     pNode->isDirty = 1;
151040   }
151041
151042   return (nCell==nMaxCell);
151043 }
151044
151045 /*
151046 ** If the node is dirty, write it out to the database.
151047 */
151048 static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
151049   int rc = SQLITE_OK;
151050   if( pNode->isDirty ){
151051     sqlite3_stmt *p = pRtree->pWriteNode;
151052     if( pNode->iNode ){
151053       sqlite3_bind_int64(p, 1, pNode->iNode);
151054     }else{
151055       sqlite3_bind_null(p, 1);
151056     }
151057     sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
151058     sqlite3_step(p);
151059     pNode->isDirty = 0;
151060     rc = sqlite3_reset(p);
151061     if( pNode->iNode==0 && rc==SQLITE_OK ){
151062       pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
151063       nodeHashInsert(pRtree, pNode);
151064     }
151065   }
151066   return rc;
151067 }
151068
151069 /*
151070 ** Release a reference to a node. If the node is dirty and the reference
151071 ** count drops to zero, the node data is written to the database.
151072 */
151073 static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
151074   int rc = SQLITE_OK;
151075   if( pNode ){
151076     assert( pNode->nRef>0 );
151077     pNode->nRef--;
151078     if( pNode->nRef==0 ){
151079       if( pNode->iNode==1 ){
151080         pRtree->iDepth = -1;
151081       }
151082       if( pNode->pParent ){
151083         rc = nodeRelease(pRtree, pNode->pParent);
151084       }
151085       if( rc==SQLITE_OK ){
151086         rc = nodeWrite(pRtree, pNode);
151087       }
151088       nodeHashDelete(pRtree, pNode);
151089       sqlite3_free(pNode);
151090     }
151091   }
151092   return rc;
151093 }
151094
151095 /*
151096 ** Return the 64-bit integer value associated with cell iCell of
151097 ** node pNode. If pNode is a leaf node, this is a rowid. If it is
151098 ** an internal node, then the 64-bit integer is a child page number.
151099 */
151100 static i64 nodeGetRowid(
151101   Rtree *pRtree,       /* The overall R-Tree */
151102   RtreeNode *pNode,    /* The node from which to extract the ID */
151103   int iCell            /* The cell index from which to extract the ID */
151104 ){
151105   assert( iCell<NCELL(pNode) );
151106   return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
151107 }
151108
151109 /*
151110 ** Return coordinate iCoord from cell iCell in node pNode.
151111 */
151112 static void nodeGetCoord(
151113   Rtree *pRtree,               /* The overall R-Tree */
151114   RtreeNode *pNode,            /* The node from which to extract a coordinate */
151115   int iCell,                   /* The index of the cell within the node */
151116   int iCoord,                  /* Which coordinate to extract */
151117   RtreeCoord *pCoord           /* OUT: Space to write result to */
151118 ){
151119   readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
151120 }
151121
151122 /*
151123 ** Deserialize cell iCell of node pNode. Populate the structure pointed
151124 ** to by pCell with the results.
151125 */
151126 static void nodeGetCell(
151127   Rtree *pRtree,               /* The overall R-Tree */
151128   RtreeNode *pNode,            /* The node containing the cell to be read */
151129   int iCell,                   /* Index of the cell within the node */
151130   RtreeCell *pCell             /* OUT: Write the cell contents here */
151131 ){
151132   u8 *pData;
151133   RtreeCoord *pCoord;
151134   int ii;
151135   pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
151136   pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
151137   pCoord = pCell->aCoord;
151138   for(ii=0; ii<pRtree->nDim*2; ii++){
151139     readCoord(&pData[ii*4], &pCoord[ii]);
151140   }
151141 }
151142
151143
151144 /* Forward declaration for the function that does the work of
151145 ** the virtual table module xCreate() and xConnect() methods.
151146 */
151147 static int rtreeInit(
151148   sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
151149 );
151150
151151 /* 
151152 ** Rtree virtual table module xCreate method.
151153 */
151154 static int rtreeCreate(
151155   sqlite3 *db,
151156   void *pAux,
151157   int argc, const char *const*argv,
151158   sqlite3_vtab **ppVtab,
151159   char **pzErr
151160 ){
151161   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
151162 }
151163
151164 /* 
151165 ** Rtree virtual table module xConnect method.
151166 */
151167 static int rtreeConnect(
151168   sqlite3 *db,
151169   void *pAux,
151170   int argc, const char *const*argv,
151171   sqlite3_vtab **ppVtab,
151172   char **pzErr
151173 ){
151174   return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
151175 }
151176
151177 /*
151178 ** Increment the r-tree reference count.
151179 */
151180 static void rtreeReference(Rtree *pRtree){
151181   pRtree->nBusy++;
151182 }
151183
151184 /*
151185 ** Decrement the r-tree reference count. When the reference count reaches
151186 ** zero the structure is deleted.
151187 */
151188 static void rtreeRelease(Rtree *pRtree){
151189   pRtree->nBusy--;
151190   if( pRtree->nBusy==0 ){
151191     sqlite3_finalize(pRtree->pReadNode);
151192     sqlite3_finalize(pRtree->pWriteNode);
151193     sqlite3_finalize(pRtree->pDeleteNode);
151194     sqlite3_finalize(pRtree->pReadRowid);
151195     sqlite3_finalize(pRtree->pWriteRowid);
151196     sqlite3_finalize(pRtree->pDeleteRowid);
151197     sqlite3_finalize(pRtree->pReadParent);
151198     sqlite3_finalize(pRtree->pWriteParent);
151199     sqlite3_finalize(pRtree->pDeleteParent);
151200     sqlite3_free(pRtree);
151201   }
151202 }
151203
151204 /* 
151205 ** Rtree virtual table module xDisconnect method.
151206 */
151207 static int rtreeDisconnect(sqlite3_vtab *pVtab){
151208   rtreeRelease((Rtree *)pVtab);
151209   return SQLITE_OK;
151210 }
151211
151212 /* 
151213 ** Rtree virtual table module xDestroy method.
151214 */
151215 static int rtreeDestroy(sqlite3_vtab *pVtab){
151216   Rtree *pRtree = (Rtree *)pVtab;
151217   int rc;
151218   char *zCreate = sqlite3_mprintf(
151219     "DROP TABLE '%q'.'%q_node';"
151220     "DROP TABLE '%q'.'%q_rowid';"
151221     "DROP TABLE '%q'.'%q_parent';",
151222     pRtree->zDb, pRtree->zName, 
151223     pRtree->zDb, pRtree->zName,
151224     pRtree->zDb, pRtree->zName
151225   );
151226   if( !zCreate ){
151227     rc = SQLITE_NOMEM;
151228   }else{
151229     rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
151230     sqlite3_free(zCreate);
151231   }
151232   if( rc==SQLITE_OK ){
151233     rtreeRelease(pRtree);
151234   }
151235
151236   return rc;
151237 }
151238
151239 /* 
151240 ** Rtree virtual table module xOpen method.
151241 */
151242 static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
151243   int rc = SQLITE_NOMEM;
151244   RtreeCursor *pCsr;
151245
151246   pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
151247   if( pCsr ){
151248     memset(pCsr, 0, sizeof(RtreeCursor));
151249     pCsr->base.pVtab = pVTab;
151250     rc = SQLITE_OK;
151251   }
151252   *ppCursor = (sqlite3_vtab_cursor *)pCsr;
151253
151254   return rc;
151255 }
151256
151257
151258 /*
151259 ** Free the RtreeCursor.aConstraint[] array and its contents.
151260 */
151261 static void freeCursorConstraints(RtreeCursor *pCsr){
151262   if( pCsr->aConstraint ){
151263     int i;                        /* Used to iterate through constraint array */
151264     for(i=0; i<pCsr->nConstraint; i++){
151265       sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
151266       if( pInfo ){
151267         if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
151268         sqlite3_free(pInfo);
151269       }
151270     }
151271     sqlite3_free(pCsr->aConstraint);
151272     pCsr->aConstraint = 0;
151273   }
151274 }
151275
151276 /* 
151277 ** Rtree virtual table module xClose method.
151278 */
151279 static int rtreeClose(sqlite3_vtab_cursor *cur){
151280   Rtree *pRtree = (Rtree *)(cur->pVtab);
151281   int ii;
151282   RtreeCursor *pCsr = (RtreeCursor *)cur;
151283   freeCursorConstraints(pCsr);
151284   sqlite3_free(pCsr->aPoint);
151285   for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
151286   sqlite3_free(pCsr);
151287   return SQLITE_OK;
151288 }
151289
151290 /*
151291 ** Rtree virtual table module xEof method.
151292 **
151293 ** Return non-zero if the cursor does not currently point to a valid 
151294 ** record (i.e if the scan has finished), or zero otherwise.
151295 */
151296 static int rtreeEof(sqlite3_vtab_cursor *cur){
151297   RtreeCursor *pCsr = (RtreeCursor *)cur;
151298   return pCsr->atEOF;
151299 }
151300
151301 /*
151302 ** Convert raw bits from the on-disk RTree record into a coordinate value.
151303 ** The on-disk format is big-endian and needs to be converted for little-
151304 ** endian platforms.  The on-disk record stores integer coordinates if
151305 ** eInt is true and it stores 32-bit floating point records if eInt is
151306 ** false.  a[] is the four bytes of the on-disk record to be decoded.
151307 ** Store the results in "r".
151308 **
151309 ** There are three versions of this macro, one each for little-endian and
151310 ** big-endian processors and a third generic implementation.  The endian-
151311 ** specific implementations are much faster and are preferred if the
151312 ** processor endianness is known at compile-time.  The SQLITE_BYTEORDER
151313 ** macro is part of sqliteInt.h and hence the endian-specific
151314 ** implementation will only be used if this module is compiled as part
151315 ** of the amalgamation.
151316 */
151317 #if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234
151318 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
151319     RtreeCoord c;    /* Coordinate decoded */                   \
151320     memcpy(&c.u,a,4);                                           \
151321     c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)|                   \
151322           ((c.u&0xff)<<24)|((c.u&0xff00)<<8);                   \
151323     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
151324 }
151325 #elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321
151326 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
151327     RtreeCoord c;    /* Coordinate decoded */                   \
151328     memcpy(&c.u,a,4);                                           \
151329     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
151330 }
151331 #else
151332 #define RTREE_DECODE_COORD(eInt, a, r) {                        \
151333     RtreeCoord c;    /* Coordinate decoded */                   \
151334     c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16)                     \
151335            +((u32)a[2]<<8) + a[3];                              \
151336     r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
151337 }
151338 #endif
151339
151340 /*
151341 ** Check the RTree node or entry given by pCellData and p against the MATCH
151342 ** constraint pConstraint.  
151343 */
151344 static int rtreeCallbackConstraint(
151345   RtreeConstraint *pConstraint,  /* The constraint to test */
151346   int eInt,                      /* True if RTree holding integer coordinates */
151347   u8 *pCellData,                 /* Raw cell content */
151348   RtreeSearchPoint *pSearch,     /* Container of this cell */
151349   sqlite3_rtree_dbl *prScore,    /* OUT: score for the cell */
151350   int *peWithin                  /* OUT: visibility of the cell */
151351 ){
151352   int i;                                                /* Loop counter */
151353   sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
151354   int nCoord = pInfo->nCoord;                           /* No. of coordinates */
151355   int rc;                                             /* Callback return code */
151356   sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2];   /* Decoded coordinates */
151357
151358   assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
151359   assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
151360
151361   if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
151362     pInfo->iRowid = readInt64(pCellData);
151363   }
151364   pCellData += 8;
151365   for(i=0; i<nCoord; i++, pCellData += 4){
151366     RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]);
151367   }
151368   if( pConstraint->op==RTREE_MATCH ){
151369     rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
151370                               nCoord, aCoord, &i);
151371     if( i==0 ) *peWithin = NOT_WITHIN;
151372     *prScore = RTREE_ZERO;
151373   }else{
151374     pInfo->aCoord = aCoord;
151375     pInfo->iLevel = pSearch->iLevel - 1;
151376     pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
151377     pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
151378     rc = pConstraint->u.xQueryFunc(pInfo);
151379     if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
151380     if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
151381       *prScore = pInfo->rScore;
151382     }
151383   }
151384   return rc;
151385 }
151386
151387 /* 
151388 ** Check the internal RTree node given by pCellData against constraint p.
151389 ** If this constraint cannot be satisfied by any child within the node,
151390 ** set *peWithin to NOT_WITHIN.
151391 */
151392 static void rtreeNonleafConstraint(
151393   RtreeConstraint *p,        /* The constraint to test */
151394   int eInt,                  /* True if RTree holds integer coordinates */
151395   u8 *pCellData,             /* Raw cell content as appears on disk */
151396   int *peWithin              /* Adjust downward, as appropriate */
151397 ){
151398   sqlite3_rtree_dbl val;     /* Coordinate value convert to a double */
151399
151400   /* p->iCoord might point to either a lower or upper bound coordinate
151401   ** in a coordinate pair.  But make pCellData point to the lower bound.
151402   */
151403   pCellData += 8 + 4*(p->iCoord&0xfe);
151404
151405   assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
151406       || p->op==RTREE_GT || p->op==RTREE_EQ );
151407   switch( p->op ){
151408     case RTREE_LE:
151409     case RTREE_LT:
151410     case RTREE_EQ:
151411       RTREE_DECODE_COORD(eInt, pCellData, val);
151412       /* val now holds the lower bound of the coordinate pair */
151413       if( p->u.rValue>=val ) return;
151414       if( p->op!=RTREE_EQ ) break;  /* RTREE_LE and RTREE_LT end here */
151415       /* Fall through for the RTREE_EQ case */
151416
151417     default: /* RTREE_GT or RTREE_GE,  or fallthrough of RTREE_EQ */
151418       pCellData += 4;
151419       RTREE_DECODE_COORD(eInt, pCellData, val);
151420       /* val now holds the upper bound of the coordinate pair */
151421       if( p->u.rValue<=val ) return;
151422   }
151423   *peWithin = NOT_WITHIN;
151424 }
151425
151426 /*
151427 ** Check the leaf RTree cell given by pCellData against constraint p.
151428 ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
151429 ** If the constraint is satisfied, leave *peWithin unchanged.
151430 **
151431 ** The constraint is of the form:  xN op $val
151432 **
151433 ** The op is given by p->op.  The xN is p->iCoord-th coordinate in
151434 ** pCellData.  $val is given by p->u.rValue.
151435 */
151436 static void rtreeLeafConstraint(
151437   RtreeConstraint *p,        /* The constraint to test */
151438   int eInt,                  /* True if RTree holds integer coordinates */
151439   u8 *pCellData,             /* Raw cell content as appears on disk */
151440   int *peWithin              /* Adjust downward, as appropriate */
151441 ){
151442   RtreeDValue xN;      /* Coordinate value converted to a double */
151443
151444   assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE 
151445       || p->op==RTREE_GT || p->op==RTREE_EQ );
151446   pCellData += 8 + p->iCoord*4;
151447   RTREE_DECODE_COORD(eInt, pCellData, xN);
151448   switch( p->op ){
151449     case RTREE_LE: if( xN <= p->u.rValue ) return;  break;
151450     case RTREE_LT: if( xN <  p->u.rValue ) return;  break;
151451     case RTREE_GE: if( xN >= p->u.rValue ) return;  break;
151452     case RTREE_GT: if( xN >  p->u.rValue ) return;  break;
151453     default:       if( xN == p->u.rValue ) return;  break;
151454   }
151455   *peWithin = NOT_WITHIN;
151456 }
151457
151458 /*
151459 ** One of the cells in node pNode is guaranteed to have a 64-bit 
151460 ** integer value equal to iRowid. Return the index of this cell.
151461 */
151462 static int nodeRowidIndex(
151463   Rtree *pRtree, 
151464   RtreeNode *pNode, 
151465   i64 iRowid,
151466   int *piIndex
151467 ){
151468   int ii;
151469   int nCell = NCELL(pNode);
151470   assert( nCell<200 );
151471   for(ii=0; ii<nCell; ii++){
151472     if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
151473       *piIndex = ii;
151474       return SQLITE_OK;
151475     }
151476   }
151477   return SQLITE_CORRUPT_VTAB;
151478 }
151479
151480 /*
151481 ** Return the index of the cell containing a pointer to node pNode
151482 ** in its parent. If pNode is the root node, return -1.
151483 */
151484 static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
151485   RtreeNode *pParent = pNode->pParent;
151486   if( pParent ){
151487     return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
151488   }
151489   *piIndex = -1;
151490   return SQLITE_OK;
151491 }
151492
151493 /*
151494 ** Compare two search points.  Return negative, zero, or positive if the first
151495 ** is less than, equal to, or greater than the second.
151496 **
151497 ** The rScore is the primary key.  Smaller rScore values come first.
151498 ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
151499 ** iLevel values coming first.  In this way, if rScore is the same for all
151500 ** SearchPoints, then iLevel becomes the deciding factor and the result
151501 ** is a depth-first search, which is the desired default behavior.
151502 */
151503 static int rtreeSearchPointCompare(
151504   const RtreeSearchPoint *pA,
151505   const RtreeSearchPoint *pB
151506 ){
151507   if( pA->rScore<pB->rScore ) return -1;
151508   if( pA->rScore>pB->rScore ) return +1;
151509   if( pA->iLevel<pB->iLevel ) return -1;
151510   if( pA->iLevel>pB->iLevel ) return +1;
151511   return 0;
151512 }
151513
151514 /*
151515 ** Interchange to search points in a cursor.
151516 */
151517 static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
151518   RtreeSearchPoint t = p->aPoint[i];
151519   assert( i<j );
151520   p->aPoint[i] = p->aPoint[j];
151521   p->aPoint[j] = t;
151522   i++; j++;
151523   if( i<RTREE_CACHE_SZ ){
151524     if( j>=RTREE_CACHE_SZ ){
151525       nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
151526       p->aNode[i] = 0;
151527     }else{
151528       RtreeNode *pTemp = p->aNode[i];
151529       p->aNode[i] = p->aNode[j];
151530       p->aNode[j] = pTemp;
151531     }
151532   }
151533 }
151534
151535 /*
151536 ** Return the search point with the lowest current score.
151537 */
151538 static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
151539   return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
151540 }
151541
151542 /*
151543 ** Get the RtreeNode for the search point with the lowest score.
151544 */
151545 static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
151546   sqlite3_int64 id;
151547   int ii = 1 - pCur->bPoint;
151548   assert( ii==0 || ii==1 );
151549   assert( pCur->bPoint || pCur->nPoint );
151550   if( pCur->aNode[ii]==0 ){
151551     assert( pRC!=0 );
151552     id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
151553     *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
151554   }
151555   return pCur->aNode[ii];
151556 }
151557
151558 /*
151559 ** Push a new element onto the priority queue
151560 */
151561 static RtreeSearchPoint *rtreeEnqueue(
151562   RtreeCursor *pCur,    /* The cursor */
151563   RtreeDValue rScore,   /* Score for the new search point */
151564   u8 iLevel             /* Level for the new search point */
151565 ){
151566   int i, j;
151567   RtreeSearchPoint *pNew;
151568   if( pCur->nPoint>=pCur->nPointAlloc ){
151569     int nNew = pCur->nPointAlloc*2 + 8;
151570     pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
151571     if( pNew==0 ) return 0;
151572     pCur->aPoint = pNew;
151573     pCur->nPointAlloc = nNew;
151574   }
151575   i = pCur->nPoint++;
151576   pNew = pCur->aPoint + i;
151577   pNew->rScore = rScore;
151578   pNew->iLevel = iLevel;
151579   assert( iLevel<=RTREE_MAX_DEPTH );
151580   while( i>0 ){
151581     RtreeSearchPoint *pParent;
151582     j = (i-1)/2;
151583     pParent = pCur->aPoint + j;
151584     if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
151585     rtreeSearchPointSwap(pCur, j, i);
151586     i = j;
151587     pNew = pParent;
151588   }
151589   return pNew;
151590 }
151591
151592 /*
151593 ** Allocate a new RtreeSearchPoint and return a pointer to it.  Return
151594 ** NULL if malloc fails.
151595 */
151596 static RtreeSearchPoint *rtreeSearchPointNew(
151597   RtreeCursor *pCur,    /* The cursor */
151598   RtreeDValue rScore,   /* Score for the new search point */
151599   u8 iLevel             /* Level for the new search point */
151600 ){
151601   RtreeSearchPoint *pNew, *pFirst;
151602   pFirst = rtreeSearchPointFirst(pCur);
151603   pCur->anQueue[iLevel]++;
151604   if( pFirst==0
151605    || pFirst->rScore>rScore 
151606    || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
151607   ){
151608     if( pCur->bPoint ){
151609       int ii;
151610       pNew = rtreeEnqueue(pCur, rScore, iLevel);
151611       if( pNew==0 ) return 0;
151612       ii = (int)(pNew - pCur->aPoint) + 1;
151613       if( ii<RTREE_CACHE_SZ ){
151614         assert( pCur->aNode[ii]==0 );
151615         pCur->aNode[ii] = pCur->aNode[0];
151616        }else{
151617         nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
151618       }
151619       pCur->aNode[0] = 0;
151620       *pNew = pCur->sPoint;
151621     }
151622     pCur->sPoint.rScore = rScore;
151623     pCur->sPoint.iLevel = iLevel;
151624     pCur->bPoint = 1;
151625     return &pCur->sPoint;
151626   }else{
151627     return rtreeEnqueue(pCur, rScore, iLevel);
151628   }
151629 }
151630
151631 #if 0
151632 /* Tracing routines for the RtreeSearchPoint queue */
151633 static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
151634   if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
151635   printf(" %d.%05lld.%02d %g %d",
151636     p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
151637   );
151638   idx++;
151639   if( idx<RTREE_CACHE_SZ ){
151640     printf(" %p\n", pCur->aNode[idx]);
151641   }else{
151642     printf("\n");
151643   }
151644 }
151645 static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
151646   int ii;
151647   printf("=== %9s ", zPrefix);
151648   if( pCur->bPoint ){
151649     tracePoint(&pCur->sPoint, -1, pCur);
151650   }
151651   for(ii=0; ii<pCur->nPoint; ii++){
151652     if( ii>0 || pCur->bPoint ) printf("              ");
151653     tracePoint(&pCur->aPoint[ii], ii, pCur);
151654   }
151655 }
151656 # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
151657 #else
151658 # define RTREE_QUEUE_TRACE(A,B)   /* no-op */
151659 #endif
151660
151661 /* Remove the search point with the lowest current score.
151662 */
151663 static void rtreeSearchPointPop(RtreeCursor *p){
151664   int i, j, k, n;
151665   i = 1 - p->bPoint;
151666   assert( i==0 || i==1 );
151667   if( p->aNode[i] ){
151668     nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
151669     p->aNode[i] = 0;
151670   }
151671   if( p->bPoint ){
151672     p->anQueue[p->sPoint.iLevel]--;
151673     p->bPoint = 0;
151674   }else if( p->nPoint ){
151675     p->anQueue[p->aPoint[0].iLevel]--;
151676     n = --p->nPoint;
151677     p->aPoint[0] = p->aPoint[n];
151678     if( n<RTREE_CACHE_SZ-1 ){
151679       p->aNode[1] = p->aNode[n+1];
151680       p->aNode[n+1] = 0;
151681     }
151682     i = 0;
151683     while( (j = i*2+1)<n ){
151684       k = j+1;
151685       if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
151686         if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
151687           rtreeSearchPointSwap(p, i, k);
151688           i = k;
151689         }else{
151690           break;
151691         }
151692       }else{
151693         if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
151694           rtreeSearchPointSwap(p, i, j);
151695           i = j;
151696         }else{
151697           break;
151698         }
151699       }
151700     }
151701   }
151702 }
151703
151704
151705 /*
151706 ** Continue the search on cursor pCur until the front of the queue
151707 ** contains an entry suitable for returning as a result-set row,
151708 ** or until the RtreeSearchPoint queue is empty, indicating that the
151709 ** query has completed.
151710 */
151711 static int rtreeStepToLeaf(RtreeCursor *pCur){
151712   RtreeSearchPoint *p;
151713   Rtree *pRtree = RTREE_OF_CURSOR(pCur);
151714   RtreeNode *pNode;
151715   int eWithin;
151716   int rc = SQLITE_OK;
151717   int nCell;
151718   int nConstraint = pCur->nConstraint;
151719   int ii;
151720   int eInt;
151721   RtreeSearchPoint x;
151722
151723   eInt = pRtree->eCoordType==RTREE_COORD_INT32;
151724   while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
151725     pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
151726     if( rc ) return rc;
151727     nCell = NCELL(pNode);
151728     assert( nCell<200 );
151729     while( p->iCell<nCell ){
151730       sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
151731       u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
151732       eWithin = FULLY_WITHIN;
151733       for(ii=0; ii<nConstraint; ii++){
151734         RtreeConstraint *pConstraint = pCur->aConstraint + ii;
151735         if( pConstraint->op>=RTREE_MATCH ){
151736           rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
151737                                        &rScore, &eWithin);
151738           if( rc ) return rc;
151739         }else if( p->iLevel==1 ){
151740           rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
151741         }else{
151742           rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
151743         }
151744         if( eWithin==NOT_WITHIN ) break;
151745       }
151746       p->iCell++;
151747       if( eWithin==NOT_WITHIN ) continue;
151748       x.iLevel = p->iLevel - 1;
151749       if( x.iLevel ){
151750         x.id = readInt64(pCellData);
151751         x.iCell = 0;
151752       }else{
151753         x.id = p->id;
151754         x.iCell = p->iCell - 1;
151755       }
151756       if( p->iCell>=nCell ){
151757         RTREE_QUEUE_TRACE(pCur, "POP-S:");
151758         rtreeSearchPointPop(pCur);
151759       }
151760       if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
151761       p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
151762       if( p==0 ) return SQLITE_NOMEM;
151763       p->eWithin = eWithin;
151764       p->id = x.id;
151765       p->iCell = x.iCell;
151766       RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
151767       break;
151768     }
151769     if( p->iCell>=nCell ){
151770       RTREE_QUEUE_TRACE(pCur, "POP-Se:");
151771       rtreeSearchPointPop(pCur);
151772     }
151773   }
151774   pCur->atEOF = p==0;
151775   return SQLITE_OK;
151776 }
151777
151778 /* 
151779 ** Rtree virtual table module xNext method.
151780 */
151781 static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
151782   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
151783   int rc = SQLITE_OK;
151784
151785   /* Move to the next entry that matches the configured constraints. */
151786   RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
151787   rtreeSearchPointPop(pCsr);
151788   rc = rtreeStepToLeaf(pCsr);
151789   return rc;
151790 }
151791
151792 /* 
151793 ** Rtree virtual table module xRowid method.
151794 */
151795 static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
151796   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
151797   RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
151798   int rc = SQLITE_OK;
151799   RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
151800   if( rc==SQLITE_OK && p ){
151801     *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
151802   }
151803   return rc;
151804 }
151805
151806 /* 
151807 ** Rtree virtual table module xColumn method.
151808 */
151809 static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
151810   Rtree *pRtree = (Rtree *)cur->pVtab;
151811   RtreeCursor *pCsr = (RtreeCursor *)cur;
151812   RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
151813   RtreeCoord c;
151814   int rc = SQLITE_OK;
151815   RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
151816
151817   if( rc ) return rc;
151818   if( p==0 ) return SQLITE_OK;
151819   if( i==0 ){
151820     sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
151821   }else{
151822     if( rc ) return rc;
151823     nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
151824 #ifndef SQLITE_RTREE_INT_ONLY
151825     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
151826       sqlite3_result_double(ctx, c.f);
151827     }else
151828 #endif
151829     {
151830       assert( pRtree->eCoordType==RTREE_COORD_INT32 );
151831       sqlite3_result_int(ctx, c.i);
151832     }
151833   }
151834   return SQLITE_OK;
151835 }
151836
151837 /* 
151838 ** Use nodeAcquire() to obtain the leaf node containing the record with 
151839 ** rowid iRowid. If successful, set *ppLeaf to point to the node and
151840 ** return SQLITE_OK. If there is no such record in the table, set
151841 ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
151842 ** to zero and return an SQLite error code.
151843 */
151844 static int findLeafNode(
151845   Rtree *pRtree,              /* RTree to search */
151846   i64 iRowid,                 /* The rowid searching for */
151847   RtreeNode **ppLeaf,         /* Write the node here */
151848   sqlite3_int64 *piNode       /* Write the node-id here */
151849 ){
151850   int rc;
151851   *ppLeaf = 0;
151852   sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
151853   if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
151854     i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
151855     if( piNode ) *piNode = iNode;
151856     rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
151857     sqlite3_reset(pRtree->pReadRowid);
151858   }else{
151859     rc = sqlite3_reset(pRtree->pReadRowid);
151860   }
151861   return rc;
151862 }
151863
151864 /*
151865 ** This function is called to configure the RtreeConstraint object passed
151866 ** as the second argument for a MATCH constraint. The value passed as the
151867 ** first argument to this function is the right-hand operand to the MATCH
151868 ** operator.
151869 */
151870 static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
151871   RtreeMatchArg *pBlob;              /* BLOB returned by geometry function */
151872   sqlite3_rtree_query_info *pInfo;   /* Callback information */
151873   int nBlob;                         /* Size of the geometry function blob */
151874   int nExpected;                     /* Expected size of the BLOB */
151875
151876   /* Check that value is actually a blob. */
151877   if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
151878
151879   /* Check that the blob is roughly the right size. */
151880   nBlob = sqlite3_value_bytes(pValue);
151881   if( nBlob<(int)sizeof(RtreeMatchArg) 
151882    || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
151883   ){
151884     return SQLITE_ERROR;
151885   }
151886
151887   pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
151888   if( !pInfo ) return SQLITE_NOMEM;
151889   memset(pInfo, 0, sizeof(*pInfo));
151890   pBlob = (RtreeMatchArg*)&pInfo[1];
151891
151892   memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
151893   nExpected = (int)(sizeof(RtreeMatchArg) +
151894                     (pBlob->nParam-1)*sizeof(RtreeDValue));
151895   if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
151896     sqlite3_free(pInfo);
151897     return SQLITE_ERROR;
151898   }
151899   pInfo->pContext = pBlob->cb.pContext;
151900   pInfo->nParam = pBlob->nParam;
151901   pInfo->aParam = pBlob->aParam;
151902
151903   if( pBlob->cb.xGeom ){
151904     pCons->u.xGeom = pBlob->cb.xGeom;
151905   }else{
151906     pCons->op = RTREE_QUERY;
151907     pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
151908   }
151909   pCons->pInfo = pInfo;
151910   return SQLITE_OK;
151911 }
151912
151913 /* 
151914 ** Rtree virtual table module xFilter method.
151915 */
151916 static int rtreeFilter(
151917   sqlite3_vtab_cursor *pVtabCursor, 
151918   int idxNum, const char *idxStr,
151919   int argc, sqlite3_value **argv
151920 ){
151921   Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
151922   RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
151923   RtreeNode *pRoot = 0;
151924   int ii;
151925   int rc = SQLITE_OK;
151926   int iCell = 0;
151927
151928   rtreeReference(pRtree);
151929
151930   /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
151931   freeCursorConstraints(pCsr);
151932   sqlite3_free(pCsr->aPoint);
151933   memset(pCsr, 0, sizeof(RtreeCursor));
151934   pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
151935
151936   pCsr->iStrategy = idxNum;
151937   if( idxNum==1 ){
151938     /* Special case - lookup by rowid. */
151939     RtreeNode *pLeaf;        /* Leaf on which the required cell resides */
151940     RtreeSearchPoint *p;     /* Search point for the the leaf */
151941     i64 iRowid = sqlite3_value_int64(argv[0]);
151942     i64 iNode = 0;
151943     rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
151944     if( rc==SQLITE_OK && pLeaf!=0 ){
151945       p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
151946       assert( p!=0 );  /* Always returns pCsr->sPoint */
151947       pCsr->aNode[0] = pLeaf;
151948       p->id = iNode;
151949       p->eWithin = PARTLY_WITHIN;
151950       rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
151951       p->iCell = iCell;
151952       RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
151953     }else{
151954       pCsr->atEOF = 1;
151955     }
151956   }else{
151957     /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array 
151958     ** with the configured constraints. 
151959     */
151960     rc = nodeAcquire(pRtree, 1, 0, &pRoot);
151961     if( rc==SQLITE_OK && argc>0 ){
151962       pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
151963       pCsr->nConstraint = argc;
151964       if( !pCsr->aConstraint ){
151965         rc = SQLITE_NOMEM;
151966       }else{
151967         memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
151968         memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
151969         assert( (idxStr==0 && argc==0)
151970                 || (idxStr && (int)strlen(idxStr)==argc*2) );
151971         for(ii=0; ii<argc; ii++){
151972           RtreeConstraint *p = &pCsr->aConstraint[ii];
151973           p->op = idxStr[ii*2];
151974           p->iCoord = idxStr[ii*2+1]-'0';
151975           if( p->op>=RTREE_MATCH ){
151976             /* A MATCH operator. The right-hand-side must be a blob that
151977             ** can be cast into an RtreeMatchArg object. One created using
151978             ** an sqlite3_rtree_geometry_callback() SQL user function.
151979             */
151980             rc = deserializeGeometry(argv[ii], p);
151981             if( rc!=SQLITE_OK ){
151982               break;
151983             }
151984             p->pInfo->nCoord = pRtree->nDim*2;
151985             p->pInfo->anQueue = pCsr->anQueue;
151986             p->pInfo->mxLevel = pRtree->iDepth + 1;
151987           }else{
151988 #ifdef SQLITE_RTREE_INT_ONLY
151989             p->u.rValue = sqlite3_value_int64(argv[ii]);
151990 #else
151991             p->u.rValue = sqlite3_value_double(argv[ii]);
151992 #endif
151993           }
151994         }
151995       }
151996     }
151997     if( rc==SQLITE_OK ){
151998       RtreeSearchPoint *pNew;
151999       pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1);
152000       if( pNew==0 ) return SQLITE_NOMEM;
152001       pNew->id = 1;
152002       pNew->iCell = 0;
152003       pNew->eWithin = PARTLY_WITHIN;
152004       assert( pCsr->bPoint==1 );
152005       pCsr->aNode[0] = pRoot;
152006       pRoot = 0;
152007       RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
152008       rc = rtreeStepToLeaf(pCsr);
152009     }
152010   }
152011
152012   nodeRelease(pRtree, pRoot);
152013   rtreeRelease(pRtree);
152014   return rc;
152015 }
152016
152017 /*
152018 ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
152019 ** extension is currently being used by a version of SQLite too old to
152020 ** support estimatedRows. In that case this function is a no-op.
152021 */
152022 static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
152023 #if SQLITE_VERSION_NUMBER>=3008002
152024   if( sqlite3_libversion_number()>=3008002 ){
152025     pIdxInfo->estimatedRows = nRow;
152026   }
152027 #endif
152028 }
152029
152030 /*
152031 ** Rtree virtual table module xBestIndex method. There are three
152032 ** table scan strategies to choose from (in order from most to 
152033 ** least desirable):
152034 **
152035 **   idxNum     idxStr        Strategy
152036 **   ------------------------------------------------
152037 **     1        Unused        Direct lookup by rowid.
152038 **     2        See below     R-tree query or full-table scan.
152039 **   ------------------------------------------------
152040 **
152041 ** If strategy 1 is used, then idxStr is not meaningful. If strategy
152042 ** 2 is used, idxStr is formatted to contain 2 bytes for each 
152043 ** constraint used. The first two bytes of idxStr correspond to 
152044 ** the constraint in sqlite3_index_info.aConstraintUsage[] with
152045 ** (argvIndex==1) etc.
152046 **
152047 ** The first of each pair of bytes in idxStr identifies the constraint
152048 ** operator as follows:
152049 **
152050 **   Operator    Byte Value
152051 **   ----------------------
152052 **      =        0x41 ('A')
152053 **     <=        0x42 ('B')
152054 **      <        0x43 ('C')
152055 **     >=        0x44 ('D')
152056 **      >        0x45 ('E')
152057 **   MATCH       0x46 ('F')
152058 **   ----------------------
152059 **
152060 ** The second of each pair of bytes identifies the coordinate column
152061 ** to which the constraint applies. The leftmost coordinate column
152062 ** is 'a', the second from the left 'b' etc.
152063 */
152064 static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
152065   Rtree *pRtree = (Rtree*)tab;
152066   int rc = SQLITE_OK;
152067   int ii;
152068   i64 nRow;                       /* Estimated rows returned by this scan */
152069
152070   int iIdx = 0;
152071   char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
152072   memset(zIdxStr, 0, sizeof(zIdxStr));
152073
152074   assert( pIdxInfo->idxStr==0 );
152075   for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
152076     struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
152077
152078     if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
152079       /* We have an equality constraint on the rowid. Use strategy 1. */
152080       int jj;
152081       for(jj=0; jj<ii; jj++){
152082         pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
152083         pIdxInfo->aConstraintUsage[jj].omit = 0;
152084       }
152085       pIdxInfo->idxNum = 1;
152086       pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
152087       pIdxInfo->aConstraintUsage[jj].omit = 1;
152088
152089       /* This strategy involves a two rowid lookups on an B-Tree structures
152090       ** and then a linear search of an R-Tree node. This should be 
152091       ** considered almost as quick as a direct rowid lookup (for which 
152092       ** sqlite uses an internal cost of 0.0). It is expected to return
152093       ** a single row.
152094       */ 
152095       pIdxInfo->estimatedCost = 30.0;
152096       setEstimatedRows(pIdxInfo, 1);
152097       return SQLITE_OK;
152098     }
152099
152100     if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
152101       u8 op;
152102       switch( p->op ){
152103         case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
152104         case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
152105         case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
152106         case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
152107         case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
152108         default:
152109           assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
152110           op = RTREE_MATCH; 
152111           break;
152112       }
152113       zIdxStr[iIdx++] = op;
152114       zIdxStr[iIdx++] = p->iColumn - 1 + '0';
152115       pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
152116       pIdxInfo->aConstraintUsage[ii].omit = 1;
152117     }
152118   }
152119
152120   pIdxInfo->idxNum = 2;
152121   pIdxInfo->needToFreeIdxStr = 1;
152122   if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
152123     return SQLITE_NOMEM;
152124   }
152125
152126   nRow = pRtree->nRowEst / (iIdx + 1);
152127   pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
152128   setEstimatedRows(pIdxInfo, nRow);
152129
152130   return rc;
152131 }
152132
152133 /*
152134 ** Return the N-dimensional volumn of the cell stored in *p.
152135 */
152136 static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
152137   RtreeDValue area = (RtreeDValue)1;
152138   int ii;
152139   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
152140     area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
152141   }
152142   return area;
152143 }
152144
152145 /*
152146 ** Return the margin length of cell p. The margin length is the sum
152147 ** of the objects size in each dimension.
152148 */
152149 static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
152150   RtreeDValue margin = (RtreeDValue)0;
152151   int ii;
152152   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
152153     margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
152154   }
152155   return margin;
152156 }
152157
152158 /*
152159 ** Store the union of cells p1 and p2 in p1.
152160 */
152161 static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
152162   int ii;
152163   if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
152164     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
152165       p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
152166       p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
152167     }
152168   }else{
152169     for(ii=0; ii<(pRtree->nDim*2); ii+=2){
152170       p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
152171       p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
152172     }
152173   }
152174 }
152175
152176 /*
152177 ** Return true if the area covered by p2 is a subset of the area covered
152178 ** by p1. False otherwise.
152179 */
152180 static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
152181   int ii;
152182   int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
152183   for(ii=0; ii<(pRtree->nDim*2); ii+=2){
152184     RtreeCoord *a1 = &p1->aCoord[ii];
152185     RtreeCoord *a2 = &p2->aCoord[ii];
152186     if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f)) 
152187      || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i)) 
152188     ){
152189       return 0;
152190     }
152191   }
152192   return 1;
152193 }
152194
152195 /*
152196 ** Return the amount cell p would grow by if it were unioned with pCell.
152197 */
152198 static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
152199   RtreeDValue area;
152200   RtreeCell cell;
152201   memcpy(&cell, p, sizeof(RtreeCell));
152202   area = cellArea(pRtree, &cell);
152203   cellUnion(pRtree, &cell, pCell);
152204   return (cellArea(pRtree, &cell)-area);
152205 }
152206
152207 static RtreeDValue cellOverlap(
152208   Rtree *pRtree, 
152209   RtreeCell *p, 
152210   RtreeCell *aCell, 
152211   int nCell
152212 ){
152213   int ii;
152214   RtreeDValue overlap = RTREE_ZERO;
152215   for(ii=0; ii<nCell; ii++){
152216     int jj;
152217     RtreeDValue o = (RtreeDValue)1;
152218     for(jj=0; jj<(pRtree->nDim*2); jj+=2){
152219       RtreeDValue x1, x2;
152220       x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
152221       x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
152222       if( x2<x1 ){
152223         o = (RtreeDValue)0;
152224         break;
152225       }else{
152226         o = o * (x2-x1);
152227       }
152228     }
152229     overlap += o;
152230   }
152231   return overlap;
152232 }
152233
152234
152235 /*
152236 ** This function implements the ChooseLeaf algorithm from Gutman[84].
152237 ** ChooseSubTree in r*tree terminology.
152238 */
152239 static int ChooseLeaf(
152240   Rtree *pRtree,               /* Rtree table */
152241   RtreeCell *pCell,            /* Cell to insert into rtree */
152242   int iHeight,                 /* Height of sub-tree rooted at pCell */
152243   RtreeNode **ppLeaf           /* OUT: Selected leaf page */
152244 ){
152245   int rc;
152246   int ii;
152247   RtreeNode *pNode;
152248   rc = nodeAcquire(pRtree, 1, 0, &pNode);
152249
152250   for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
152251     int iCell;
152252     sqlite3_int64 iBest = 0;
152253
152254     RtreeDValue fMinGrowth = RTREE_ZERO;
152255     RtreeDValue fMinArea = RTREE_ZERO;
152256
152257     int nCell = NCELL(pNode);
152258     RtreeCell cell;
152259     RtreeNode *pChild;
152260
152261     RtreeCell *aCell = 0;
152262
152263     /* Select the child node which will be enlarged the least if pCell
152264     ** is inserted into it. Resolve ties by choosing the entry with
152265     ** the smallest area.
152266     */
152267     for(iCell=0; iCell<nCell; iCell++){
152268       int bBest = 0;
152269       RtreeDValue growth;
152270       RtreeDValue area;
152271       nodeGetCell(pRtree, pNode, iCell, &cell);
152272       growth = cellGrowth(pRtree, &cell, pCell);
152273       area = cellArea(pRtree, &cell);
152274       if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
152275         bBest = 1;
152276       }
152277       if( bBest ){
152278         fMinGrowth = growth;
152279         fMinArea = area;
152280         iBest = cell.iRowid;
152281       }
152282     }
152283
152284     sqlite3_free(aCell);
152285     rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
152286     nodeRelease(pRtree, pNode);
152287     pNode = pChild;
152288   }
152289
152290   *ppLeaf = pNode;
152291   return rc;
152292 }
152293
152294 /*
152295 ** A cell with the same content as pCell has just been inserted into
152296 ** the node pNode. This function updates the bounding box cells in
152297 ** all ancestor elements.
152298 */
152299 static int AdjustTree(
152300   Rtree *pRtree,                    /* Rtree table */
152301   RtreeNode *pNode,                 /* Adjust ancestry of this node. */
152302   RtreeCell *pCell                  /* This cell was just inserted */
152303 ){
152304   RtreeNode *p = pNode;
152305   while( p->pParent ){
152306     RtreeNode *pParent = p->pParent;
152307     RtreeCell cell;
152308     int iCell;
152309
152310     if( nodeParentIndex(pRtree, p, &iCell) ){
152311       return SQLITE_CORRUPT_VTAB;
152312     }
152313
152314     nodeGetCell(pRtree, pParent, iCell, &cell);
152315     if( !cellContains(pRtree, &cell, pCell) ){
152316       cellUnion(pRtree, &cell, pCell);
152317       nodeOverwriteCell(pRtree, pParent, &cell, iCell);
152318     }
152319  
152320     p = pParent;
152321   }
152322   return SQLITE_OK;
152323 }
152324
152325 /*
152326 ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
152327 */
152328 static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
152329   sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
152330   sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
152331   sqlite3_step(pRtree->pWriteRowid);
152332   return sqlite3_reset(pRtree->pWriteRowid);
152333 }
152334
152335 /*
152336 ** Write mapping (iNode->iPar) to the <rtree>_parent table.
152337 */
152338 static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
152339   sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
152340   sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
152341   sqlite3_step(pRtree->pWriteParent);
152342   return sqlite3_reset(pRtree->pWriteParent);
152343 }
152344
152345 static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
152346
152347
152348 /*
152349 ** Arguments aIdx, aDistance and aSpare all point to arrays of size
152350 ** nIdx. The aIdx array contains the set of integers from 0 to 
152351 ** (nIdx-1) in no particular order. This function sorts the values
152352 ** in aIdx according to the indexed values in aDistance. For
152353 ** example, assuming the inputs:
152354 **
152355 **   aIdx      = { 0,   1,   2,   3 }
152356 **   aDistance = { 5.0, 2.0, 7.0, 6.0 }
152357 **
152358 ** this function sets the aIdx array to contain:
152359 **
152360 **   aIdx      = { 0,   1,   2,   3 }
152361 **
152362 ** The aSpare array is used as temporary working space by the
152363 ** sorting algorithm.
152364 */
152365 static void SortByDistance(
152366   int *aIdx, 
152367   int nIdx, 
152368   RtreeDValue *aDistance, 
152369   int *aSpare
152370 ){
152371   if( nIdx>1 ){
152372     int iLeft = 0;
152373     int iRight = 0;
152374
152375     int nLeft = nIdx/2;
152376     int nRight = nIdx-nLeft;
152377     int *aLeft = aIdx;
152378     int *aRight = &aIdx[nLeft];
152379
152380     SortByDistance(aLeft, nLeft, aDistance, aSpare);
152381     SortByDistance(aRight, nRight, aDistance, aSpare);
152382
152383     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
152384     aLeft = aSpare;
152385
152386     while( iLeft<nLeft || iRight<nRight ){
152387       if( iLeft==nLeft ){
152388         aIdx[iLeft+iRight] = aRight[iRight];
152389         iRight++;
152390       }else if( iRight==nRight ){
152391         aIdx[iLeft+iRight] = aLeft[iLeft];
152392         iLeft++;
152393       }else{
152394         RtreeDValue fLeft = aDistance[aLeft[iLeft]];
152395         RtreeDValue fRight = aDistance[aRight[iRight]];
152396         if( fLeft<fRight ){
152397           aIdx[iLeft+iRight] = aLeft[iLeft];
152398           iLeft++;
152399         }else{
152400           aIdx[iLeft+iRight] = aRight[iRight];
152401           iRight++;
152402         }
152403       }
152404     }
152405
152406 #if 0
152407     /* Check that the sort worked */
152408     {
152409       int jj;
152410       for(jj=1; jj<nIdx; jj++){
152411         RtreeDValue left = aDistance[aIdx[jj-1]];
152412         RtreeDValue right = aDistance[aIdx[jj]];
152413         assert( left<=right );
152414       }
152415     }
152416 #endif
152417   }
152418 }
152419
152420 /*
152421 ** Arguments aIdx, aCell and aSpare all point to arrays of size
152422 ** nIdx. The aIdx array contains the set of integers from 0 to 
152423 ** (nIdx-1) in no particular order. This function sorts the values
152424 ** in aIdx according to dimension iDim of the cells in aCell. The
152425 ** minimum value of dimension iDim is considered first, the
152426 ** maximum used to break ties.
152427 **
152428 ** The aSpare array is used as temporary working space by the
152429 ** sorting algorithm.
152430 */
152431 static void SortByDimension(
152432   Rtree *pRtree,
152433   int *aIdx, 
152434   int nIdx, 
152435   int iDim, 
152436   RtreeCell *aCell, 
152437   int *aSpare
152438 ){
152439   if( nIdx>1 ){
152440
152441     int iLeft = 0;
152442     int iRight = 0;
152443
152444     int nLeft = nIdx/2;
152445     int nRight = nIdx-nLeft;
152446     int *aLeft = aIdx;
152447     int *aRight = &aIdx[nLeft];
152448
152449     SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
152450     SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
152451
152452     memcpy(aSpare, aLeft, sizeof(int)*nLeft);
152453     aLeft = aSpare;
152454     while( iLeft<nLeft || iRight<nRight ){
152455       RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
152456       RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
152457       RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
152458       RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
152459       if( (iLeft!=nLeft) && ((iRight==nRight)
152460        || (xleft1<xright1)
152461        || (xleft1==xright1 && xleft2<xright2)
152462       )){
152463         aIdx[iLeft+iRight] = aLeft[iLeft];
152464         iLeft++;
152465       }else{
152466         aIdx[iLeft+iRight] = aRight[iRight];
152467         iRight++;
152468       }
152469     }
152470
152471 #if 0
152472     /* Check that the sort worked */
152473     {
152474       int jj;
152475       for(jj=1; jj<nIdx; jj++){
152476         RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
152477         RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
152478         RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
152479         RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
152480         assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
152481       }
152482     }
152483 #endif
152484   }
152485 }
152486
152487 /*
152488 ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
152489 */
152490 static int splitNodeStartree(
152491   Rtree *pRtree,
152492   RtreeCell *aCell,
152493   int nCell,
152494   RtreeNode *pLeft,
152495   RtreeNode *pRight,
152496   RtreeCell *pBboxLeft,
152497   RtreeCell *pBboxRight
152498 ){
152499   int **aaSorted;
152500   int *aSpare;
152501   int ii;
152502
152503   int iBestDim = 0;
152504   int iBestSplit = 0;
152505   RtreeDValue fBestMargin = RTREE_ZERO;
152506
152507   int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
152508
152509   aaSorted = (int **)sqlite3_malloc(nByte);
152510   if( !aaSorted ){
152511     return SQLITE_NOMEM;
152512   }
152513
152514   aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
152515   memset(aaSorted, 0, nByte);
152516   for(ii=0; ii<pRtree->nDim; ii++){
152517     int jj;
152518     aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
152519     for(jj=0; jj<nCell; jj++){
152520       aaSorted[ii][jj] = jj;
152521     }
152522     SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
152523   }
152524
152525   for(ii=0; ii<pRtree->nDim; ii++){
152526     RtreeDValue margin = RTREE_ZERO;
152527     RtreeDValue fBestOverlap = RTREE_ZERO;
152528     RtreeDValue fBestArea = RTREE_ZERO;
152529     int iBestLeft = 0;
152530     int nLeft;
152531
152532     for(
152533       nLeft=RTREE_MINCELLS(pRtree); 
152534       nLeft<=(nCell-RTREE_MINCELLS(pRtree)); 
152535       nLeft++
152536     ){
152537       RtreeCell left;
152538       RtreeCell right;
152539       int kk;
152540       RtreeDValue overlap;
152541       RtreeDValue area;
152542
152543       memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
152544       memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
152545       for(kk=1; kk<(nCell-1); kk++){
152546         if( kk<nLeft ){
152547           cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
152548         }else{
152549           cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
152550         }
152551       }
152552       margin += cellMargin(pRtree, &left);
152553       margin += cellMargin(pRtree, &right);
152554       overlap = cellOverlap(pRtree, &left, &right, 1);
152555       area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
152556       if( (nLeft==RTREE_MINCELLS(pRtree))
152557        || (overlap<fBestOverlap)
152558        || (overlap==fBestOverlap && area<fBestArea)
152559       ){
152560         iBestLeft = nLeft;
152561         fBestOverlap = overlap;
152562         fBestArea = area;
152563       }
152564     }
152565
152566     if( ii==0 || margin<fBestMargin ){
152567       iBestDim = ii;
152568       fBestMargin = margin;
152569       iBestSplit = iBestLeft;
152570     }
152571   }
152572
152573   memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
152574   memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
152575   for(ii=0; ii<nCell; ii++){
152576     RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
152577     RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
152578     RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
152579     nodeInsertCell(pRtree, pTarget, pCell);
152580     cellUnion(pRtree, pBbox, pCell);
152581   }
152582
152583   sqlite3_free(aaSorted);
152584   return SQLITE_OK;
152585 }
152586
152587
152588 static int updateMapping(
152589   Rtree *pRtree, 
152590   i64 iRowid, 
152591   RtreeNode *pNode, 
152592   int iHeight
152593 ){
152594   int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
152595   xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
152596   if( iHeight>0 ){
152597     RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
152598     if( pChild ){
152599       nodeRelease(pRtree, pChild->pParent);
152600       nodeReference(pNode);
152601       pChild->pParent = pNode;
152602     }
152603   }
152604   return xSetMapping(pRtree, iRowid, pNode->iNode);
152605 }
152606
152607 static int SplitNode(
152608   Rtree *pRtree,
152609   RtreeNode *pNode,
152610   RtreeCell *pCell,
152611   int iHeight
152612 ){
152613   int i;
152614   int newCellIsRight = 0;
152615
152616   int rc = SQLITE_OK;
152617   int nCell = NCELL(pNode);
152618   RtreeCell *aCell;
152619   int *aiUsed;
152620
152621   RtreeNode *pLeft = 0;
152622   RtreeNode *pRight = 0;
152623
152624   RtreeCell leftbbox;
152625   RtreeCell rightbbox;
152626
152627   /* Allocate an array and populate it with a copy of pCell and 
152628   ** all cells from node pLeft. Then zero the original node.
152629   */
152630   aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
152631   if( !aCell ){
152632     rc = SQLITE_NOMEM;
152633     goto splitnode_out;
152634   }
152635   aiUsed = (int *)&aCell[nCell+1];
152636   memset(aiUsed, 0, sizeof(int)*(nCell+1));
152637   for(i=0; i<nCell; i++){
152638     nodeGetCell(pRtree, pNode, i, &aCell[i]);
152639   }
152640   nodeZero(pRtree, pNode);
152641   memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
152642   nCell++;
152643
152644   if( pNode->iNode==1 ){
152645     pRight = nodeNew(pRtree, pNode);
152646     pLeft = nodeNew(pRtree, pNode);
152647     pRtree->iDepth++;
152648     pNode->isDirty = 1;
152649     writeInt16(pNode->zData, pRtree->iDepth);
152650   }else{
152651     pLeft = pNode;
152652     pRight = nodeNew(pRtree, pLeft->pParent);
152653     nodeReference(pLeft);
152654   }
152655
152656   if( !pLeft || !pRight ){
152657     rc = SQLITE_NOMEM;
152658     goto splitnode_out;
152659   }
152660
152661   memset(pLeft->zData, 0, pRtree->iNodeSize);
152662   memset(pRight->zData, 0, pRtree->iNodeSize);
152663
152664   rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
152665                          &leftbbox, &rightbbox);
152666   if( rc!=SQLITE_OK ){
152667     goto splitnode_out;
152668   }
152669
152670   /* Ensure both child nodes have node numbers assigned to them by calling
152671   ** nodeWrite(). Node pRight always needs a node number, as it was created
152672   ** by nodeNew() above. But node pLeft sometimes already has a node number.
152673   ** In this case avoid the all to nodeWrite().
152674   */
152675   if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
152676    || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
152677   ){
152678     goto splitnode_out;
152679   }
152680
152681   rightbbox.iRowid = pRight->iNode;
152682   leftbbox.iRowid = pLeft->iNode;
152683
152684   if( pNode->iNode==1 ){
152685     rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
152686     if( rc!=SQLITE_OK ){
152687       goto splitnode_out;
152688     }
152689   }else{
152690     RtreeNode *pParent = pLeft->pParent;
152691     int iCell;
152692     rc = nodeParentIndex(pRtree, pLeft, &iCell);
152693     if( rc==SQLITE_OK ){
152694       nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
152695       rc = AdjustTree(pRtree, pParent, &leftbbox);
152696     }
152697     if( rc!=SQLITE_OK ){
152698       goto splitnode_out;
152699     }
152700   }
152701   if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
152702     goto splitnode_out;
152703   }
152704
152705   for(i=0; i<NCELL(pRight); i++){
152706     i64 iRowid = nodeGetRowid(pRtree, pRight, i);
152707     rc = updateMapping(pRtree, iRowid, pRight, iHeight);
152708     if( iRowid==pCell->iRowid ){
152709       newCellIsRight = 1;
152710     }
152711     if( rc!=SQLITE_OK ){
152712       goto splitnode_out;
152713     }
152714   }
152715   if( pNode->iNode==1 ){
152716     for(i=0; i<NCELL(pLeft); i++){
152717       i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
152718       rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
152719       if( rc!=SQLITE_OK ){
152720         goto splitnode_out;
152721       }
152722     }
152723   }else if( newCellIsRight==0 ){
152724     rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
152725   }
152726
152727   if( rc==SQLITE_OK ){
152728     rc = nodeRelease(pRtree, pRight);
152729     pRight = 0;
152730   }
152731   if( rc==SQLITE_OK ){
152732     rc = nodeRelease(pRtree, pLeft);
152733     pLeft = 0;
152734   }
152735
152736 splitnode_out:
152737   nodeRelease(pRtree, pRight);
152738   nodeRelease(pRtree, pLeft);
152739   sqlite3_free(aCell);
152740   return rc;
152741 }
152742
152743 /*
152744 ** If node pLeaf is not the root of the r-tree and its pParent pointer is 
152745 ** still NULL, load all ancestor nodes of pLeaf into memory and populate
152746 ** the pLeaf->pParent chain all the way up to the root node.
152747 **
152748 ** This operation is required when a row is deleted (or updated - an update
152749 ** is implemented as a delete followed by an insert). SQLite provides the
152750 ** rowid of the row to delete, which can be used to find the leaf on which
152751 ** the entry resides (argument pLeaf). Once the leaf is located, this 
152752 ** function is called to determine its ancestry.
152753 */
152754 static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
152755   int rc = SQLITE_OK;
152756   RtreeNode *pChild = pLeaf;
152757   while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
152758     int rc2 = SQLITE_OK;          /* sqlite3_reset() return code */
152759     sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
152760     rc = sqlite3_step(pRtree->pReadParent);
152761     if( rc==SQLITE_ROW ){
152762       RtreeNode *pTest;           /* Used to test for reference loops */
152763       i64 iNode;                  /* Node number of parent node */
152764
152765       /* Before setting pChild->pParent, test that we are not creating a
152766       ** loop of references (as we would if, say, pChild==pParent). We don't
152767       ** want to do this as it leads to a memory leak when trying to delete
152768       ** the referenced counted node structures.
152769       */
152770       iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
152771       for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
152772       if( !pTest ){
152773         rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
152774       }
152775     }
152776     rc = sqlite3_reset(pRtree->pReadParent);
152777     if( rc==SQLITE_OK ) rc = rc2;
152778     if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
152779     pChild = pChild->pParent;
152780   }
152781   return rc;
152782 }
152783
152784 static int deleteCell(Rtree *, RtreeNode *, int, int);
152785
152786 static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
152787   int rc;
152788   int rc2;
152789   RtreeNode *pParent = 0;
152790   int iCell;
152791
152792   assert( pNode->nRef==1 );
152793
152794   /* Remove the entry in the parent cell. */
152795   rc = nodeParentIndex(pRtree, pNode, &iCell);
152796   if( rc==SQLITE_OK ){
152797     pParent = pNode->pParent;
152798     pNode->pParent = 0;
152799     rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
152800   }
152801   rc2 = nodeRelease(pRtree, pParent);
152802   if( rc==SQLITE_OK ){
152803     rc = rc2;
152804   }
152805   if( rc!=SQLITE_OK ){
152806     return rc;
152807   }
152808
152809   /* Remove the xxx_node entry. */
152810   sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
152811   sqlite3_step(pRtree->pDeleteNode);
152812   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
152813     return rc;
152814   }
152815
152816   /* Remove the xxx_parent entry. */
152817   sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
152818   sqlite3_step(pRtree->pDeleteParent);
152819   if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
152820     return rc;
152821   }
152822   
152823   /* Remove the node from the in-memory hash table and link it into
152824   ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
152825   */
152826   nodeHashDelete(pRtree, pNode);
152827   pNode->iNode = iHeight;
152828   pNode->pNext = pRtree->pDeleted;
152829   pNode->nRef++;
152830   pRtree->pDeleted = pNode;
152831
152832   return SQLITE_OK;
152833 }
152834
152835 static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
152836   RtreeNode *pParent = pNode->pParent;
152837   int rc = SQLITE_OK; 
152838   if( pParent ){
152839     int ii; 
152840     int nCell = NCELL(pNode);
152841     RtreeCell box;                            /* Bounding box for pNode */
152842     nodeGetCell(pRtree, pNode, 0, &box);
152843     for(ii=1; ii<nCell; ii++){
152844       RtreeCell cell;
152845       nodeGetCell(pRtree, pNode, ii, &cell);
152846       cellUnion(pRtree, &box, &cell);
152847     }
152848     box.iRowid = pNode->iNode;
152849     rc = nodeParentIndex(pRtree, pNode, &ii);
152850     if( rc==SQLITE_OK ){
152851       nodeOverwriteCell(pRtree, pParent, &box, ii);
152852       rc = fixBoundingBox(pRtree, pParent);
152853     }
152854   }
152855   return rc;
152856 }
152857
152858 /*
152859 ** Delete the cell at index iCell of node pNode. After removing the
152860 ** cell, adjust the r-tree data structure if required.
152861 */
152862 static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
152863   RtreeNode *pParent;
152864   int rc;
152865
152866   if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
152867     return rc;
152868   }
152869
152870   /* Remove the cell from the node. This call just moves bytes around
152871   ** the in-memory node image, so it cannot fail.
152872   */
152873   nodeDeleteCell(pRtree, pNode, iCell);
152874
152875   /* If the node is not the tree root and now has less than the minimum
152876   ** number of cells, remove it from the tree. Otherwise, update the
152877   ** cell in the parent node so that it tightly contains the updated
152878   ** node.
152879   */
152880   pParent = pNode->pParent;
152881   assert( pParent || pNode->iNode==1 );
152882   if( pParent ){
152883     if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
152884       rc = removeNode(pRtree, pNode, iHeight);
152885     }else{
152886       rc = fixBoundingBox(pRtree, pNode);
152887     }
152888   }
152889
152890   return rc;
152891 }
152892
152893 static int Reinsert(
152894   Rtree *pRtree, 
152895   RtreeNode *pNode, 
152896   RtreeCell *pCell, 
152897   int iHeight
152898 ){
152899   int *aOrder;
152900   int *aSpare;
152901   RtreeCell *aCell;
152902   RtreeDValue *aDistance;
152903   int nCell;
152904   RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
152905   int iDim;
152906   int ii;
152907   int rc = SQLITE_OK;
152908   int n;
152909
152910   memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
152911
152912   nCell = NCELL(pNode)+1;
152913   n = (nCell+1)&(~1);
152914
152915   /* Allocate the buffers used by this operation. The allocation is
152916   ** relinquished before this function returns.
152917   */
152918   aCell = (RtreeCell *)sqlite3_malloc(n * (
152919     sizeof(RtreeCell)     +         /* aCell array */
152920     sizeof(int)           +         /* aOrder array */
152921     sizeof(int)           +         /* aSpare array */
152922     sizeof(RtreeDValue)             /* aDistance array */
152923   ));
152924   if( !aCell ){
152925     return SQLITE_NOMEM;
152926   }
152927   aOrder    = (int *)&aCell[n];
152928   aSpare    = (int *)&aOrder[n];
152929   aDistance = (RtreeDValue *)&aSpare[n];
152930
152931   for(ii=0; ii<nCell; ii++){
152932     if( ii==(nCell-1) ){
152933       memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
152934     }else{
152935       nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
152936     }
152937     aOrder[ii] = ii;
152938     for(iDim=0; iDim<pRtree->nDim; iDim++){
152939       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
152940       aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
152941     }
152942   }
152943   for(iDim=0; iDim<pRtree->nDim; iDim++){
152944     aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
152945   }
152946
152947   for(ii=0; ii<nCell; ii++){
152948     aDistance[ii] = RTREE_ZERO;
152949     for(iDim=0; iDim<pRtree->nDim; iDim++){
152950       RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) - 
152951                                DCOORD(aCell[ii].aCoord[iDim*2]));
152952       aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
152953     }
152954   }
152955
152956   SortByDistance(aOrder, nCell, aDistance, aSpare);
152957   nodeZero(pRtree, pNode);
152958
152959   for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
152960     RtreeCell *p = &aCell[aOrder[ii]];
152961     nodeInsertCell(pRtree, pNode, p);
152962     if( p->iRowid==pCell->iRowid ){
152963       if( iHeight==0 ){
152964         rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
152965       }else{
152966         rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
152967       }
152968     }
152969   }
152970   if( rc==SQLITE_OK ){
152971     rc = fixBoundingBox(pRtree, pNode);
152972   }
152973   for(; rc==SQLITE_OK && ii<nCell; ii++){
152974     /* Find a node to store this cell in. pNode->iNode currently contains
152975     ** the height of the sub-tree headed by the cell.
152976     */
152977     RtreeNode *pInsert;
152978     RtreeCell *p = &aCell[aOrder[ii]];
152979     rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
152980     if( rc==SQLITE_OK ){
152981       int rc2;
152982       rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
152983       rc2 = nodeRelease(pRtree, pInsert);
152984       if( rc==SQLITE_OK ){
152985         rc = rc2;
152986       }
152987     }
152988   }
152989
152990   sqlite3_free(aCell);
152991   return rc;
152992 }
152993
152994 /*
152995 ** Insert cell pCell into node pNode. Node pNode is the head of a 
152996 ** subtree iHeight high (leaf nodes have iHeight==0).
152997 */
152998 static int rtreeInsertCell(
152999   Rtree *pRtree,
153000   RtreeNode *pNode,
153001   RtreeCell *pCell,
153002   int iHeight
153003 ){
153004   int rc = SQLITE_OK;
153005   if( iHeight>0 ){
153006     RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
153007     if( pChild ){
153008       nodeRelease(pRtree, pChild->pParent);
153009       nodeReference(pNode);
153010       pChild->pParent = pNode;
153011     }
153012   }
153013   if( nodeInsertCell(pRtree, pNode, pCell) ){
153014     if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
153015       rc = SplitNode(pRtree, pNode, pCell, iHeight);
153016     }else{
153017       pRtree->iReinsertHeight = iHeight;
153018       rc = Reinsert(pRtree, pNode, pCell, iHeight);
153019     }
153020   }else{
153021     rc = AdjustTree(pRtree, pNode, pCell);
153022     if( rc==SQLITE_OK ){
153023       if( iHeight==0 ){
153024         rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
153025       }else{
153026         rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
153027       }
153028     }
153029   }
153030   return rc;
153031 }
153032
153033 static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
153034   int ii;
153035   int rc = SQLITE_OK;
153036   int nCell = NCELL(pNode);
153037
153038   for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
153039     RtreeNode *pInsert;
153040     RtreeCell cell;
153041     nodeGetCell(pRtree, pNode, ii, &cell);
153042
153043     /* Find a node to store this cell in. pNode->iNode currently contains
153044     ** the height of the sub-tree headed by the cell.
153045     */
153046     rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
153047     if( rc==SQLITE_OK ){
153048       int rc2;
153049       rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
153050       rc2 = nodeRelease(pRtree, pInsert);
153051       if( rc==SQLITE_OK ){
153052         rc = rc2;
153053       }
153054     }
153055   }
153056   return rc;
153057 }
153058
153059 /*
153060 ** Select a currently unused rowid for a new r-tree record.
153061 */
153062 static int newRowid(Rtree *pRtree, i64 *piRowid){
153063   int rc;
153064   sqlite3_bind_null(pRtree->pWriteRowid, 1);
153065   sqlite3_bind_null(pRtree->pWriteRowid, 2);
153066   sqlite3_step(pRtree->pWriteRowid);
153067   rc = sqlite3_reset(pRtree->pWriteRowid);
153068   *piRowid = sqlite3_last_insert_rowid(pRtree->db);
153069   return rc;
153070 }
153071
153072 /*
153073 ** Remove the entry with rowid=iDelete from the r-tree structure.
153074 */
153075 static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
153076   int rc;                         /* Return code */
153077   RtreeNode *pLeaf = 0;           /* Leaf node containing record iDelete */
153078   int iCell;                      /* Index of iDelete cell in pLeaf */
153079   RtreeNode *pRoot;               /* Root node of rtree structure */
153080
153081
153082   /* Obtain a reference to the root node to initialize Rtree.iDepth */
153083   rc = nodeAcquire(pRtree, 1, 0, &pRoot);
153084
153085   /* Obtain a reference to the leaf node that contains the entry 
153086   ** about to be deleted. 
153087   */
153088   if( rc==SQLITE_OK ){
153089     rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
153090   }
153091
153092   /* Delete the cell in question from the leaf node. */
153093   if( rc==SQLITE_OK ){
153094     int rc2;
153095     rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
153096     if( rc==SQLITE_OK ){
153097       rc = deleteCell(pRtree, pLeaf, iCell, 0);
153098     }
153099     rc2 = nodeRelease(pRtree, pLeaf);
153100     if( rc==SQLITE_OK ){
153101       rc = rc2;
153102     }
153103   }
153104
153105   /* Delete the corresponding entry in the <rtree>_rowid table. */
153106   if( rc==SQLITE_OK ){
153107     sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
153108     sqlite3_step(pRtree->pDeleteRowid);
153109     rc = sqlite3_reset(pRtree->pDeleteRowid);
153110   }
153111
153112   /* Check if the root node now has exactly one child. If so, remove
153113   ** it, schedule the contents of the child for reinsertion and 
153114   ** reduce the tree height by one.
153115   **
153116   ** This is equivalent to copying the contents of the child into
153117   ** the root node (the operation that Gutman's paper says to perform 
153118   ** in this scenario).
153119   */
153120   if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
153121     int rc2;
153122     RtreeNode *pChild;
153123     i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
153124     rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
153125     if( rc==SQLITE_OK ){
153126       rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
153127     }
153128     rc2 = nodeRelease(pRtree, pChild);
153129     if( rc==SQLITE_OK ) rc = rc2;
153130     if( rc==SQLITE_OK ){
153131       pRtree->iDepth--;
153132       writeInt16(pRoot->zData, pRtree->iDepth);
153133       pRoot->isDirty = 1;
153134     }
153135   }
153136
153137   /* Re-insert the contents of any underfull nodes removed from the tree. */
153138   for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
153139     if( rc==SQLITE_OK ){
153140       rc = reinsertNodeContent(pRtree, pLeaf);
153141     }
153142     pRtree->pDeleted = pLeaf->pNext;
153143     sqlite3_free(pLeaf);
153144   }
153145
153146   /* Release the reference to the root node. */
153147   if( rc==SQLITE_OK ){
153148     rc = nodeRelease(pRtree, pRoot);
153149   }else{
153150     nodeRelease(pRtree, pRoot);
153151   }
153152
153153   return rc;
153154 }
153155
153156 /*
153157 ** Rounding constants for float->double conversion.
153158 */
153159 #define RNDTOWARDS  (1.0 - 1.0/8388608.0)  /* Round towards zero */
153160 #define RNDAWAY     (1.0 + 1.0/8388608.0)  /* Round away from zero */
153161
153162 #if !defined(SQLITE_RTREE_INT_ONLY)
153163 /*
153164 ** Convert an sqlite3_value into an RtreeValue (presumably a float)
153165 ** while taking care to round toward negative or positive, respectively.
153166 */
153167 static RtreeValue rtreeValueDown(sqlite3_value *v){
153168   double d = sqlite3_value_double(v);
153169   float f = (float)d;
153170   if( f>d ){
153171     f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
153172   }
153173   return f;
153174 }
153175 static RtreeValue rtreeValueUp(sqlite3_value *v){
153176   double d = sqlite3_value_double(v);
153177   float f = (float)d;
153178   if( f<d ){
153179     f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
153180   }
153181   return f;
153182 }
153183 #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
153184
153185
153186 /*
153187 ** The xUpdate method for rtree module virtual tables.
153188 */
153189 static int rtreeUpdate(
153190   sqlite3_vtab *pVtab, 
153191   int nData, 
153192   sqlite3_value **azData, 
153193   sqlite_int64 *pRowid
153194 ){
153195   Rtree *pRtree = (Rtree *)pVtab;
153196   int rc = SQLITE_OK;
153197   RtreeCell cell;                 /* New cell to insert if nData>1 */
153198   int bHaveRowid = 0;             /* Set to 1 after new rowid is determined */
153199
153200   rtreeReference(pRtree);
153201   assert(nData>=1);
153202
153203   cell.iRowid = 0;  /* Used only to suppress a compiler warning */
153204
153205   /* Constraint handling. A write operation on an r-tree table may return
153206   ** SQLITE_CONSTRAINT for two reasons:
153207   **
153208   **   1. A duplicate rowid value, or
153209   **   2. The supplied data violates the "x2>=x1" constraint.
153210   **
153211   ** In the first case, if the conflict-handling mode is REPLACE, then
153212   ** the conflicting row can be removed before proceeding. In the second
153213   ** case, SQLITE_CONSTRAINT must be returned regardless of the
153214   ** conflict-handling mode specified by the user.
153215   */
153216   if( nData>1 ){
153217     int ii;
153218
153219     /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
153220     assert( nData==(pRtree->nDim*2 + 3) );
153221 #ifndef SQLITE_RTREE_INT_ONLY
153222     if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
153223       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
153224         cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
153225         cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
153226         if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
153227           rc = SQLITE_CONSTRAINT;
153228           goto constraint;
153229         }
153230       }
153231     }else
153232 #endif
153233     {
153234       for(ii=0; ii<(pRtree->nDim*2); ii+=2){
153235         cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
153236         cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
153237         if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
153238           rc = SQLITE_CONSTRAINT;
153239           goto constraint;
153240         }
153241       }
153242     }
153243
153244     /* If a rowid value was supplied, check if it is already present in 
153245     ** the table. If so, the constraint has failed. */
153246     if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
153247       cell.iRowid = sqlite3_value_int64(azData[2]);
153248       if( sqlite3_value_type(azData[0])==SQLITE_NULL
153249        || sqlite3_value_int64(azData[0])!=cell.iRowid
153250       ){
153251         int steprc;
153252         sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
153253         steprc = sqlite3_step(pRtree->pReadRowid);
153254         rc = sqlite3_reset(pRtree->pReadRowid);
153255         if( SQLITE_ROW==steprc ){
153256           if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
153257             rc = rtreeDeleteRowid(pRtree, cell.iRowid);
153258           }else{
153259             rc = SQLITE_CONSTRAINT;
153260             goto constraint;
153261           }
153262         }
153263       }
153264       bHaveRowid = 1;
153265     }
153266   }
153267
153268   /* If azData[0] is not an SQL NULL value, it is the rowid of a
153269   ** record to delete from the r-tree table. The following block does
153270   ** just that.
153271   */
153272   if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
153273     rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
153274   }
153275
153276   /* If the azData[] array contains more than one element, elements
153277   ** (azData[2]..azData[argc-1]) contain a new record to insert into
153278   ** the r-tree structure.
153279   */
153280   if( rc==SQLITE_OK && nData>1 ){
153281     /* Insert the new record into the r-tree */
153282     RtreeNode *pLeaf = 0;
153283
153284     /* Figure out the rowid of the new row. */
153285     if( bHaveRowid==0 ){
153286       rc = newRowid(pRtree, &cell.iRowid);
153287     }
153288     *pRowid = cell.iRowid;
153289
153290     if( rc==SQLITE_OK ){
153291       rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
153292     }
153293     if( rc==SQLITE_OK ){
153294       int rc2;
153295       pRtree->iReinsertHeight = -1;
153296       rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
153297       rc2 = nodeRelease(pRtree, pLeaf);
153298       if( rc==SQLITE_OK ){
153299         rc = rc2;
153300       }
153301     }
153302   }
153303
153304 constraint:
153305   rtreeRelease(pRtree);
153306   return rc;
153307 }
153308
153309 /*
153310 ** The xRename method for rtree module virtual tables.
153311 */
153312 static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
153313   Rtree *pRtree = (Rtree *)pVtab;
153314   int rc = SQLITE_NOMEM;
153315   char *zSql = sqlite3_mprintf(
153316     "ALTER TABLE %Q.'%q_node'   RENAME TO \"%w_node\";"
153317     "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
153318     "ALTER TABLE %Q.'%q_rowid'  RENAME TO \"%w_rowid\";"
153319     , pRtree->zDb, pRtree->zName, zNewName 
153320     , pRtree->zDb, pRtree->zName, zNewName 
153321     , pRtree->zDb, pRtree->zName, zNewName
153322   );
153323   if( zSql ){
153324     rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
153325     sqlite3_free(zSql);
153326   }
153327   return rc;
153328 }
153329
153330 /*
153331 ** This function populates the pRtree->nRowEst variable with an estimate
153332 ** of the number of rows in the virtual table. If possible, this is based
153333 ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
153334 */
153335 static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
153336   const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
153337   char *zSql;
153338   sqlite3_stmt *p;
153339   int rc;
153340   i64 nRow = 0;
153341
153342   zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
153343   if( zSql==0 ){
153344     rc = SQLITE_NOMEM;
153345   }else{
153346     rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
153347     if( rc==SQLITE_OK ){
153348       if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
153349       rc = sqlite3_finalize(p);
153350     }else if( rc!=SQLITE_NOMEM ){
153351       rc = SQLITE_OK;
153352     }
153353
153354     if( rc==SQLITE_OK ){
153355       if( nRow==0 ){
153356         pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
153357       }else{
153358         pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
153359       }
153360     }
153361     sqlite3_free(zSql);
153362   }
153363
153364   return rc;
153365 }
153366
153367 static sqlite3_module rtreeModule = {
153368   0,                          /* iVersion */
153369   rtreeCreate,                /* xCreate - create a table */
153370   rtreeConnect,               /* xConnect - connect to an existing table */
153371   rtreeBestIndex,             /* xBestIndex - Determine search strategy */
153372   rtreeDisconnect,            /* xDisconnect - Disconnect from a table */
153373   rtreeDestroy,               /* xDestroy - Drop a table */
153374   rtreeOpen,                  /* xOpen - open a cursor */
153375   rtreeClose,                 /* xClose - close a cursor */
153376   rtreeFilter,                /* xFilter - configure scan constraints */
153377   rtreeNext,                  /* xNext - advance a cursor */
153378   rtreeEof,                   /* xEof */
153379   rtreeColumn,                /* xColumn - read data */
153380   rtreeRowid,                 /* xRowid - read data */
153381   rtreeUpdate,                /* xUpdate - write data */
153382   0,                          /* xBegin - begin transaction */
153383   0,                          /* xSync - sync transaction */
153384   0,                          /* xCommit - commit transaction */
153385   0,                          /* xRollback - rollback transaction */
153386   0,                          /* xFindFunction - function overloading */
153387   rtreeRename,                /* xRename - rename the table */
153388   0,                          /* xSavepoint */
153389   0,                          /* xRelease */
153390   0                           /* xRollbackTo */
153391 };
153392
153393 static int rtreeSqlInit(
153394   Rtree *pRtree, 
153395   sqlite3 *db, 
153396   const char *zDb, 
153397   const char *zPrefix, 
153398   int isCreate
153399 ){
153400   int rc = SQLITE_OK;
153401
153402   #define N_STATEMENT 9
153403   static const char *azSql[N_STATEMENT] = {
153404     /* Read and write the xxx_node table */
153405     "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
153406     "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
153407     "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
153408
153409     /* Read and write the xxx_rowid table */
153410     "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
153411     "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
153412     "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
153413
153414     /* Read and write the xxx_parent table */
153415     "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
153416     "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
153417     "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
153418   };
153419   sqlite3_stmt **appStmt[N_STATEMENT];
153420   int i;
153421
153422   pRtree->db = db;
153423
153424   if( isCreate ){
153425     char *zCreate = sqlite3_mprintf(
153426 "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
153427 "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
153428 "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
153429                                   " parentnode INTEGER);"
153430 "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
153431       zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
153432     );
153433     if( !zCreate ){
153434       return SQLITE_NOMEM;
153435     }
153436     rc = sqlite3_exec(db, zCreate, 0, 0, 0);
153437     sqlite3_free(zCreate);
153438     if( rc!=SQLITE_OK ){
153439       return rc;
153440     }
153441   }
153442
153443   appStmt[0] = &pRtree->pReadNode;
153444   appStmt[1] = &pRtree->pWriteNode;
153445   appStmt[2] = &pRtree->pDeleteNode;
153446   appStmt[3] = &pRtree->pReadRowid;
153447   appStmt[4] = &pRtree->pWriteRowid;
153448   appStmt[5] = &pRtree->pDeleteRowid;
153449   appStmt[6] = &pRtree->pReadParent;
153450   appStmt[7] = &pRtree->pWriteParent;
153451   appStmt[8] = &pRtree->pDeleteParent;
153452
153453   rc = rtreeQueryStat1(db, pRtree);
153454   for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
153455     char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
153456     if( zSql ){
153457       rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0); 
153458     }else{
153459       rc = SQLITE_NOMEM;
153460     }
153461     sqlite3_free(zSql);
153462   }
153463
153464   return rc;
153465 }
153466
153467 /*
153468 ** The second argument to this function contains the text of an SQL statement
153469 ** that returns a single integer value. The statement is compiled and executed
153470 ** using database connection db. If successful, the integer value returned
153471 ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
153472 ** code is returned and the value of *piVal after returning is not defined.
153473 */
153474 static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
153475   int rc = SQLITE_NOMEM;
153476   if( zSql ){
153477     sqlite3_stmt *pStmt = 0;
153478     rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
153479     if( rc==SQLITE_OK ){
153480       if( SQLITE_ROW==sqlite3_step(pStmt) ){
153481         *piVal = sqlite3_column_int(pStmt, 0);
153482       }
153483       rc = sqlite3_finalize(pStmt);
153484     }
153485   }
153486   return rc;
153487 }
153488
153489 /*
153490 ** This function is called from within the xConnect() or xCreate() method to
153491 ** determine the node-size used by the rtree table being created or connected
153492 ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
153493 ** Otherwise, an SQLite error code is returned.
153494 **
153495 ** If this function is being called as part of an xConnect(), then the rtree
153496 ** table already exists. In this case the node-size is determined by inspecting
153497 ** the root node of the tree.
153498 **
153499 ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size. 
153500 ** This ensures that each node is stored on a single database page. If the 
153501 ** database page-size is so large that more than RTREE_MAXCELLS entries 
153502 ** would fit in a single node, use a smaller node-size.
153503 */
153504 static int getNodeSize(
153505   sqlite3 *db,                    /* Database handle */
153506   Rtree *pRtree,                  /* Rtree handle */
153507   int isCreate,                   /* True for xCreate, false for xConnect */
153508   char **pzErr                    /* OUT: Error message, if any */
153509 ){
153510   int rc;
153511   char *zSql;
153512   if( isCreate ){
153513     int iPageSize = 0;
153514     zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
153515     rc = getIntFromStmt(db, zSql, &iPageSize);
153516     if( rc==SQLITE_OK ){
153517       pRtree->iNodeSize = iPageSize-64;
153518       if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
153519         pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
153520       }
153521     }else{
153522       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
153523     }
153524   }else{
153525     zSql = sqlite3_mprintf(
153526         "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
153527         pRtree->zDb, pRtree->zName
153528     );
153529     rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
153530     if( rc!=SQLITE_OK ){
153531       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
153532     }
153533   }
153534
153535   sqlite3_free(zSql);
153536   return rc;
153537 }
153538
153539 /* 
153540 ** This function is the implementation of both the xConnect and xCreate
153541 ** methods of the r-tree virtual table.
153542 **
153543 **   argv[0]   -> module name
153544 **   argv[1]   -> database name
153545 **   argv[2]   -> table name
153546 **   argv[...] -> column names...
153547 */
153548 static int rtreeInit(
153549   sqlite3 *db,                        /* Database connection */
153550   void *pAux,                         /* One of the RTREE_COORD_* constants */
153551   int argc, const char *const*argv,   /* Parameters to CREATE TABLE statement */
153552   sqlite3_vtab **ppVtab,              /* OUT: New virtual table */
153553   char **pzErr,                       /* OUT: Error message, if any */
153554   int isCreate                        /* True for xCreate, false for xConnect */
153555 ){
153556   int rc = SQLITE_OK;
153557   Rtree *pRtree;
153558   int nDb;              /* Length of string argv[1] */
153559   int nName;            /* Length of string argv[2] */
153560   int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
153561
153562   const char *aErrMsg[] = {
153563     0,                                                    /* 0 */
153564     "Wrong number of columns for an rtree table",         /* 1 */
153565     "Too few columns for an rtree table",                 /* 2 */
153566     "Too many columns for an rtree table"                 /* 3 */
153567   };
153568
153569   int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
153570   if( aErrMsg[iErr] ){
153571     *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
153572     return SQLITE_ERROR;
153573   }
153574
153575   sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
153576
153577   /* Allocate the sqlite3_vtab structure */
153578   nDb = (int)strlen(argv[1]);
153579   nName = (int)strlen(argv[2]);
153580   pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
153581   if( !pRtree ){
153582     return SQLITE_NOMEM;
153583   }
153584   memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
153585   pRtree->nBusy = 1;
153586   pRtree->base.pModule = &rtreeModule;
153587   pRtree->zDb = (char *)&pRtree[1];
153588   pRtree->zName = &pRtree->zDb[nDb+1];
153589   pRtree->nDim = (argc-4)/2;
153590   pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
153591   pRtree->eCoordType = eCoordType;
153592   memcpy(pRtree->zDb, argv[1], nDb);
153593   memcpy(pRtree->zName, argv[2], nName);
153594
153595   /* Figure out the node size to use. */
153596   rc = getNodeSize(db, pRtree, isCreate, pzErr);
153597
153598   /* Create/Connect to the underlying relational database schema. If
153599   ** that is successful, call sqlite3_declare_vtab() to configure
153600   ** the r-tree table schema.
153601   */
153602   if( rc==SQLITE_OK ){
153603     if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
153604       *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
153605     }else{
153606       char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
153607       char *zTmp;
153608       int ii;
153609       for(ii=4; zSql && ii<argc; ii++){
153610         zTmp = zSql;
153611         zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
153612         sqlite3_free(zTmp);
153613       }
153614       if( zSql ){
153615         zTmp = zSql;
153616         zSql = sqlite3_mprintf("%s);", zTmp);
153617         sqlite3_free(zTmp);
153618       }
153619       if( !zSql ){
153620         rc = SQLITE_NOMEM;
153621       }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
153622         *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
153623       }
153624       sqlite3_free(zSql);
153625     }
153626   }
153627
153628   if( rc==SQLITE_OK ){
153629     *ppVtab = (sqlite3_vtab *)pRtree;
153630   }else{
153631     assert( *ppVtab==0 );
153632     assert( pRtree->nBusy==1 );
153633     rtreeRelease(pRtree);
153634   }
153635   return rc;
153636 }
153637
153638
153639 /*
153640 ** Implementation of a scalar function that decodes r-tree nodes to
153641 ** human readable strings. This can be used for debugging and analysis.
153642 **
153643 ** The scalar function takes two arguments: (1) the number of dimensions
153644 ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
153645 ** an r-tree node.  For a two-dimensional r-tree structure called "rt", to
153646 ** deserialize all nodes, a statement like:
153647 **
153648 **   SELECT rtreenode(2, data) FROM rt_node;
153649 **
153650 ** The human readable string takes the form of a Tcl list with one
153651 ** entry for each cell in the r-tree node. Each entry is itself a
153652 ** list, containing the 8-byte rowid/pageno followed by the 
153653 ** <num-dimension>*2 coordinates.
153654 */
153655 static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
153656   char *zText = 0;
153657   RtreeNode node;
153658   Rtree tree;
153659   int ii;
153660
153661   UNUSED_PARAMETER(nArg);
153662   memset(&node, 0, sizeof(RtreeNode));
153663   memset(&tree, 0, sizeof(Rtree));
153664   tree.nDim = sqlite3_value_int(apArg[0]);
153665   tree.nBytesPerCell = 8 + 8 * tree.nDim;
153666   node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
153667
153668   for(ii=0; ii<NCELL(&node); ii++){
153669     char zCell[512];
153670     int nCell = 0;
153671     RtreeCell cell;
153672     int jj;
153673
153674     nodeGetCell(&tree, &node, ii, &cell);
153675     sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
153676     nCell = (int)strlen(zCell);
153677     for(jj=0; jj<tree.nDim*2; jj++){
153678 #ifndef SQLITE_RTREE_INT_ONLY
153679       sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
153680                        (double)cell.aCoord[jj].f);
153681 #else
153682       sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
153683                        cell.aCoord[jj].i);
153684 #endif
153685       nCell = (int)strlen(zCell);
153686     }
153687
153688     if( zText ){
153689       char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
153690       sqlite3_free(zText);
153691       zText = zTextNew;
153692     }else{
153693       zText = sqlite3_mprintf("{%s}", zCell);
153694     }
153695   }
153696   
153697   sqlite3_result_text(ctx, zText, -1, sqlite3_free);
153698 }
153699
153700 /* This routine implements an SQL function that returns the "depth" parameter
153701 ** from the front of a blob that is an r-tree node.  For example:
153702 **
153703 **     SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
153704 **
153705 ** The depth value is 0 for all nodes other than the root node, and the root
153706 ** node always has nodeno=1, so the example above is the primary use for this
153707 ** routine.  This routine is intended for testing and analysis only.
153708 */
153709 static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
153710   UNUSED_PARAMETER(nArg);
153711   if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB 
153712    || sqlite3_value_bytes(apArg[0])<2
153713   ){
153714     sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1); 
153715   }else{
153716     u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
153717     sqlite3_result_int(ctx, readInt16(zBlob));
153718   }
153719 }
153720
153721 /*
153722 ** Register the r-tree module with database handle db. This creates the
153723 ** virtual table module "rtree" and the debugging/analysis scalar 
153724 ** function "rtreenode".
153725 */
153726 SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
153727   const int utf8 = SQLITE_UTF8;
153728   int rc;
153729
153730   rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
153731   if( rc==SQLITE_OK ){
153732     rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
153733   }
153734   if( rc==SQLITE_OK ){
153735 #ifdef SQLITE_RTREE_INT_ONLY
153736     void *c = (void *)RTREE_COORD_INT32;
153737 #else
153738     void *c = (void *)RTREE_COORD_REAL32;
153739 #endif
153740     rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
153741   }
153742   if( rc==SQLITE_OK ){
153743     void *c = (void *)RTREE_COORD_INT32;
153744     rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
153745   }
153746
153747   return rc;
153748 }
153749
153750 /*
153751 ** This routine deletes the RtreeGeomCallback object that was attached
153752 ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
153753 ** or sqlite3_rtree_query_callback().  In other words, this routine is the
153754 ** destructor for an RtreeGeomCallback objecct.  This routine is called when
153755 ** the corresponding SQL function is deleted.
153756 */
153757 static void rtreeFreeCallback(void *p){
153758   RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
153759   if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
153760   sqlite3_free(p);
153761 }
153762
153763 /*
153764 ** Each call to sqlite3_rtree_geometry_callback() or
153765 ** sqlite3_rtree_query_callback() creates an ordinary SQLite
153766 ** scalar function that is implemented by this routine.
153767 **
153768 ** All this function does is construct an RtreeMatchArg object that
153769 ** contains the geometry-checking callback routines and a list of
153770 ** parameters to this function, then return that RtreeMatchArg object
153771 ** as a BLOB.
153772 **
153773 ** The R-Tree MATCH operator will read the returned BLOB, deserialize
153774 ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
153775 ** out which elements of the R-Tree should be returned by the query.
153776 */
153777 static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
153778   RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
153779   RtreeMatchArg *pBlob;
153780   int nBlob;
153781
153782   nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
153783   pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
153784   if( !pBlob ){
153785     sqlite3_result_error_nomem(ctx);
153786   }else{
153787     int i;
153788     pBlob->magic = RTREE_GEOMETRY_MAGIC;
153789     pBlob->cb = pGeomCtx[0];
153790     pBlob->nParam = nArg;
153791     for(i=0; i<nArg; i++){
153792 #ifdef SQLITE_RTREE_INT_ONLY
153793       pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
153794 #else
153795       pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
153796 #endif
153797     }
153798     sqlite3_result_blob(ctx, pBlob, nBlob, sqlite3_free);
153799   }
153800 }
153801
153802 /*
153803 ** Register a new geometry function for use with the r-tree MATCH operator.
153804 */
153805 SQLITE_API int SQLITE_STDCALL sqlite3_rtree_geometry_callback(
153806   sqlite3 *db,                  /* Register SQL function on this connection */
153807   const char *zGeom,            /* Name of the new SQL function */
153808   int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
153809   void *pContext                /* Extra data associated with the callback */
153810 ){
153811   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
153812
153813   /* Allocate and populate the context object. */
153814   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
153815   if( !pGeomCtx ) return SQLITE_NOMEM;
153816   pGeomCtx->xGeom = xGeom;
153817   pGeomCtx->xQueryFunc = 0;
153818   pGeomCtx->xDestructor = 0;
153819   pGeomCtx->pContext = pContext;
153820   return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY, 
153821       (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
153822   );
153823 }
153824
153825 /*
153826 ** Register a new 2nd-generation geometry function for use with the
153827 ** r-tree MATCH operator.
153828 */
153829 SQLITE_API int SQLITE_STDCALL sqlite3_rtree_query_callback(
153830   sqlite3 *db,                 /* Register SQL function on this connection */
153831   const char *zQueryFunc,      /* Name of new SQL function */
153832   int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
153833   void *pContext,              /* Extra data passed into the callback */
153834   void (*xDestructor)(void*)   /* Destructor for the extra data */
153835 ){
153836   RtreeGeomCallback *pGeomCtx;      /* Context object for new user-function */
153837
153838   /* Allocate and populate the context object. */
153839   pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
153840   if( !pGeomCtx ) return SQLITE_NOMEM;
153841   pGeomCtx->xGeom = 0;
153842   pGeomCtx->xQueryFunc = xQueryFunc;
153843   pGeomCtx->xDestructor = xDestructor;
153844   pGeomCtx->pContext = pContext;
153845   return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY, 
153846       (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
153847   );
153848 }
153849
153850 #if !SQLITE_CORE
153851 #ifdef _WIN32
153852 __declspec(dllexport)
153853 #endif
153854 SQLITE_API int SQLITE_STDCALL sqlite3_rtree_init(
153855   sqlite3 *db,
153856   char **pzErrMsg,
153857   const sqlite3_api_routines *pApi
153858 ){
153859   SQLITE_EXTENSION_INIT2(pApi)
153860   return sqlite3RtreeInit(db);
153861 }
153862 #endif
153863
153864 #endif
153865
153866 /************** End of rtree.c ***********************************************/
153867 /************** Begin file icu.c *********************************************/
153868 /*
153869 ** 2007 May 6
153870 **
153871 ** The author disclaims copyright to this source code.  In place of
153872 ** a legal notice, here is a blessing:
153873 **
153874 **    May you do good and not evil.
153875 **    May you find forgiveness for yourself and forgive others.
153876 **    May you share freely, never taking more than you give.
153877 **
153878 *************************************************************************
153879 ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
153880 **
153881 ** This file implements an integration between the ICU library 
153882 ** ("International Components for Unicode", an open-source library 
153883 ** for handling unicode data) and SQLite. The integration uses 
153884 ** ICU to provide the following to SQLite:
153885 **
153886 **   * An implementation of the SQL regexp() function (and hence REGEXP
153887 **     operator) using the ICU uregex_XX() APIs.
153888 **
153889 **   * Implementations of the SQL scalar upper() and lower() functions
153890 **     for case mapping.
153891 **
153892 **   * Integration of ICU and SQLite collation sequences.
153893 **
153894 **   * An implementation of the LIKE operator that uses ICU to 
153895 **     provide case-independent matching.
153896 */
153897
153898 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
153899
153900 /* Include ICU headers */
153901 #include <unicode/utypes.h>
153902 #include <unicode/uregex.h>
153903 #include <unicode/ustring.h>
153904 #include <unicode/ucol.h>
153905
153906 /* #include <assert.h> */
153907
153908 #ifndef SQLITE_CORE
153909   SQLITE_EXTENSION_INIT1
153910 #else
153911 #endif
153912
153913 /*
153914 ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
153915 ** operator.
153916 */
153917 #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
153918 # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
153919 #endif
153920
153921 /*
153922 ** Version of sqlite3_free() that is always a function, never a macro.
153923 */
153924 static void xFree(void *p){
153925   sqlite3_free(p);
153926 }
153927
153928 /*
153929 ** Compare two UTF-8 strings for equality where the first string is
153930 ** a "LIKE" expression. Return true (1) if they are the same and 
153931 ** false (0) if they are different.
153932 */
153933 static int icuLikeCompare(
153934   const uint8_t *zPattern,   /* LIKE pattern */
153935   const uint8_t *zString,    /* The UTF-8 string to compare against */
153936   const UChar32 uEsc         /* The escape character */
153937 ){
153938   static const int MATCH_ONE = (UChar32)'_';
153939   static const int MATCH_ALL = (UChar32)'%';
153940
153941   int iPattern = 0;       /* Current byte index in zPattern */
153942   int iString = 0;        /* Current byte index in zString */
153943
153944   int prevEscape = 0;     /* True if the previous character was uEsc */
153945
153946   while( zPattern[iPattern]!=0 ){
153947
153948     /* Read (and consume) the next character from the input pattern. */
153949     UChar32 uPattern;
153950     U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
153951     assert(uPattern!=0);
153952
153953     /* There are now 4 possibilities:
153954     **
153955     **     1. uPattern is an unescaped match-all character "%",
153956     **     2. uPattern is an unescaped match-one character "_",
153957     **     3. uPattern is an unescaped escape character, or
153958     **     4. uPattern is to be handled as an ordinary character
153959     */
153960     if( !prevEscape && uPattern==MATCH_ALL ){
153961       /* Case 1. */
153962       uint8_t c;
153963
153964       /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
153965       ** MATCH_ALL. For each MATCH_ONE, skip one character in the 
153966       ** test string.
153967       */
153968       while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
153969         if( c==MATCH_ONE ){
153970           if( zString[iString]==0 ) return 0;
153971           U8_FWD_1_UNSAFE(zString, iString);
153972         }
153973         iPattern++;
153974       }
153975
153976       if( zPattern[iPattern]==0 ) return 1;
153977
153978       while( zString[iString] ){
153979         if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
153980           return 1;
153981         }
153982         U8_FWD_1_UNSAFE(zString, iString);
153983       }
153984       return 0;
153985
153986     }else if( !prevEscape && uPattern==MATCH_ONE ){
153987       /* Case 2. */
153988       if( zString[iString]==0 ) return 0;
153989       U8_FWD_1_UNSAFE(zString, iString);
153990
153991     }else if( !prevEscape && uPattern==uEsc){
153992       /* Case 3. */
153993       prevEscape = 1;
153994
153995     }else{
153996       /* Case 4. */
153997       UChar32 uString;
153998       U8_NEXT_UNSAFE(zString, iString, uString);
153999       uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
154000       uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
154001       if( uString!=uPattern ){
154002         return 0;
154003       }
154004       prevEscape = 0;
154005     }
154006   }
154007
154008   return zString[iString]==0;
154009 }
154010
154011 /*
154012 ** Implementation of the like() SQL function.  This function implements
154013 ** the build-in LIKE operator.  The first argument to the function is the
154014 ** pattern and the second argument is the string.  So, the SQL statements:
154015 **
154016 **       A LIKE B
154017 **
154018 ** is implemented as like(B, A). If there is an escape character E, 
154019 **
154020 **       A LIKE B ESCAPE E
154021 **
154022 ** is mapped to like(B, A, E).
154023 */
154024 static void icuLikeFunc(
154025   sqlite3_context *context, 
154026   int argc, 
154027   sqlite3_value **argv
154028 ){
154029   const unsigned char *zA = sqlite3_value_text(argv[0]);
154030   const unsigned char *zB = sqlite3_value_text(argv[1]);
154031   UChar32 uEsc = 0;
154032
154033   /* Limit the length of the LIKE or GLOB pattern to avoid problems
154034   ** of deep recursion and N*N behavior in patternCompare().
154035   */
154036   if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
154037     sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
154038     return;
154039   }
154040
154041
154042   if( argc==3 ){
154043     /* The escape character string must consist of a single UTF-8 character.
154044     ** Otherwise, return an error.
154045     */
154046     int nE= sqlite3_value_bytes(argv[2]);
154047     const unsigned char *zE = sqlite3_value_text(argv[2]);
154048     int i = 0;
154049     if( zE==0 ) return;
154050     U8_NEXT(zE, i, nE, uEsc);
154051     if( i!=nE){
154052       sqlite3_result_error(context, 
154053           "ESCAPE expression must be a single character", -1);
154054       return;
154055     }
154056   }
154057
154058   if( zA && zB ){
154059     sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
154060   }
154061 }
154062
154063 /*
154064 ** This function is called when an ICU function called from within
154065 ** the implementation of an SQL scalar function returns an error.
154066 **
154067 ** The scalar function context passed as the first argument is 
154068 ** loaded with an error message based on the following two args.
154069 */
154070 static void icuFunctionError(
154071   sqlite3_context *pCtx,       /* SQLite scalar function context */
154072   const char *zName,           /* Name of ICU function that failed */
154073   UErrorCode e                 /* Error code returned by ICU function */
154074 ){
154075   char zBuf[128];
154076   sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
154077   zBuf[127] = '\0';
154078   sqlite3_result_error(pCtx, zBuf, -1);
154079 }
154080
154081 /*
154082 ** Function to delete compiled regexp objects. Registered as
154083 ** a destructor function with sqlite3_set_auxdata().
154084 */
154085 static void icuRegexpDelete(void *p){
154086   URegularExpression *pExpr = (URegularExpression *)p;
154087   uregex_close(pExpr);
154088 }
154089
154090 /*
154091 ** Implementation of SQLite REGEXP operator. This scalar function takes
154092 ** two arguments. The first is a regular expression pattern to compile
154093 ** the second is a string to match against that pattern. If either 
154094 ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
154095 ** is 1 if the string matches the pattern, or 0 otherwise.
154096 **
154097 ** SQLite maps the regexp() function to the regexp() operator such
154098 ** that the following two are equivalent:
154099 **
154100 **     zString REGEXP zPattern
154101 **     regexp(zPattern, zString)
154102 **
154103 ** Uses the following ICU regexp APIs:
154104 **
154105 **     uregex_open()
154106 **     uregex_matches()
154107 **     uregex_close()
154108 */
154109 static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
154110   UErrorCode status = U_ZERO_ERROR;
154111   URegularExpression *pExpr;
154112   UBool res;
154113   const UChar *zString = sqlite3_value_text16(apArg[1]);
154114
154115   (void)nArg;  /* Unused parameter */
154116
154117   /* If the left hand side of the regexp operator is NULL, 
154118   ** then the result is also NULL. 
154119   */
154120   if( !zString ){
154121     return;
154122   }
154123
154124   pExpr = sqlite3_get_auxdata(p, 0);
154125   if( !pExpr ){
154126     const UChar *zPattern = sqlite3_value_text16(apArg[0]);
154127     if( !zPattern ){
154128       return;
154129     }
154130     pExpr = uregex_open(zPattern, -1, 0, 0, &status);
154131
154132     if( U_SUCCESS(status) ){
154133       sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
154134     }else{
154135       assert(!pExpr);
154136       icuFunctionError(p, "uregex_open", status);
154137       return;
154138     }
154139   }
154140
154141   /* Configure the text that the regular expression operates on. */
154142   uregex_setText(pExpr, zString, -1, &status);
154143   if( !U_SUCCESS(status) ){
154144     icuFunctionError(p, "uregex_setText", status);
154145     return;
154146   }
154147
154148   /* Attempt the match */
154149   res = uregex_matches(pExpr, 0, &status);
154150   if( !U_SUCCESS(status) ){
154151     icuFunctionError(p, "uregex_matches", status);
154152     return;
154153   }
154154
154155   /* Set the text that the regular expression operates on to a NULL
154156   ** pointer. This is not really necessary, but it is tidier than 
154157   ** leaving the regular expression object configured with an invalid
154158   ** pointer after this function returns.
154159   */
154160   uregex_setText(pExpr, 0, 0, &status);
154161
154162   /* Return 1 or 0. */
154163   sqlite3_result_int(p, res ? 1 : 0);
154164 }
154165
154166 /*
154167 ** Implementations of scalar functions for case mapping - upper() and 
154168 ** lower(). Function upper() converts its input to upper-case (ABC).
154169 ** Function lower() converts to lower-case (abc).
154170 **
154171 ** ICU provides two types of case mapping, "general" case mapping and
154172 ** "language specific". Refer to ICU documentation for the differences
154173 ** between the two.
154174 **
154175 ** To utilise "general" case mapping, the upper() or lower() scalar 
154176 ** functions are invoked with one argument:
154177 **
154178 **     upper('ABC') -> 'abc'
154179 **     lower('abc') -> 'ABC'
154180 **
154181 ** To access ICU "language specific" case mapping, upper() or lower()
154182 ** should be invoked with two arguments. The second argument is the name
154183 ** of the locale to use. Passing an empty string ("") or SQL NULL value
154184 ** as the second argument is the same as invoking the 1 argument version
154185 ** of upper() or lower().
154186 **
154187 **     lower('I', 'en_us') -> 'i'
154188 **     lower('I', 'tr_tr') -> 'ı' (small dotless i)
154189 **
154190 ** http://www.icu-project.org/userguide/posix.html#case_mappings
154191 */
154192 static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
154193   const UChar *zInput;
154194   UChar *zOutput;
154195   int nInput;
154196   int nOutput;
154197
154198   UErrorCode status = U_ZERO_ERROR;
154199   const char *zLocale = 0;
154200
154201   assert(nArg==1 || nArg==2);
154202   if( nArg==2 ){
154203     zLocale = (const char *)sqlite3_value_text(apArg[1]);
154204   }
154205
154206   zInput = sqlite3_value_text16(apArg[0]);
154207   if( !zInput ){
154208     return;
154209   }
154210   nInput = sqlite3_value_bytes16(apArg[0]);
154211
154212   nOutput = nInput * 2 + 2;
154213   zOutput = sqlite3_malloc(nOutput);
154214   if( !zOutput ){
154215     return;
154216   }
154217
154218   if( sqlite3_user_data(p) ){
154219     u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
154220   }else{
154221     u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
154222   }
154223
154224   if( !U_SUCCESS(status) ){
154225     icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
154226     return;
154227   }
154228
154229   sqlite3_result_text16(p, zOutput, -1, xFree);
154230 }
154231
154232 /*
154233 ** Collation sequence destructor function. The pCtx argument points to
154234 ** a UCollator structure previously allocated using ucol_open().
154235 */
154236 static void icuCollationDel(void *pCtx){
154237   UCollator *p = (UCollator *)pCtx;
154238   ucol_close(p);
154239 }
154240
154241 /*
154242 ** Collation sequence comparison function. The pCtx argument points to
154243 ** a UCollator structure previously allocated using ucol_open().
154244 */
154245 static int icuCollationColl(
154246   void *pCtx,
154247   int nLeft,
154248   const void *zLeft,
154249   int nRight,
154250   const void *zRight
154251 ){
154252   UCollationResult res;
154253   UCollator *p = (UCollator *)pCtx;
154254   res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
154255   switch( res ){
154256     case UCOL_LESS:    return -1;
154257     case UCOL_GREATER: return +1;
154258     case UCOL_EQUAL:   return 0;
154259   }
154260   assert(!"Unexpected return value from ucol_strcoll()");
154261   return 0;
154262 }
154263
154264 /*
154265 ** Implementation of the scalar function icu_load_collation().
154266 **
154267 ** This scalar function is used to add ICU collation based collation 
154268 ** types to an SQLite database connection. It is intended to be called
154269 ** as follows:
154270 **
154271 **     SELECT icu_load_collation(<locale>, <collation-name>);
154272 **
154273 ** Where <locale> is a string containing an ICU locale identifier (i.e.
154274 ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
154275 ** collation sequence to create.
154276 */
154277 static void icuLoadCollation(
154278   sqlite3_context *p, 
154279   int nArg, 
154280   sqlite3_value **apArg
154281 ){
154282   sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
154283   UErrorCode status = U_ZERO_ERROR;
154284   const char *zLocale;      /* Locale identifier - (eg. "jp_JP") */
154285   const char *zName;        /* SQL Collation sequence name (eg. "japanese") */
154286   UCollator *pUCollator;    /* ICU library collation object */
154287   int rc;                   /* Return code from sqlite3_create_collation_x() */
154288
154289   assert(nArg==2);
154290   zLocale = (const char *)sqlite3_value_text(apArg[0]);
154291   zName = (const char *)sqlite3_value_text(apArg[1]);
154292
154293   if( !zLocale || !zName ){
154294     return;
154295   }
154296
154297   pUCollator = ucol_open(zLocale, &status);
154298   if( !U_SUCCESS(status) ){
154299     icuFunctionError(p, "ucol_open", status);
154300     return;
154301   }
154302   assert(p);
154303
154304   rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator, 
154305       icuCollationColl, icuCollationDel
154306   );
154307   if( rc!=SQLITE_OK ){
154308     ucol_close(pUCollator);
154309     sqlite3_result_error(p, "Error registering collation function", -1);
154310   }
154311 }
154312
154313 /*
154314 ** Register the ICU extension functions with database db.
154315 */
154316 SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
154317   struct IcuScalar {
154318     const char *zName;                        /* Function name */
154319     int nArg;                                 /* Number of arguments */
154320     int enc;                                  /* Optimal text encoding */
154321     void *pContext;                           /* sqlite3_user_data() context */
154322     void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
154323   } scalars[] = {
154324     {"regexp", 2, SQLITE_ANY,          0, icuRegexpFunc},
154325
154326     {"lower",  1, SQLITE_UTF16,        0, icuCaseFunc16},
154327     {"lower",  2, SQLITE_UTF16,        0, icuCaseFunc16},
154328     {"upper",  1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
154329     {"upper",  2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
154330
154331     {"lower",  1, SQLITE_UTF8,         0, icuCaseFunc16},
154332     {"lower",  2, SQLITE_UTF8,         0, icuCaseFunc16},
154333     {"upper",  1, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
154334     {"upper",  2, SQLITE_UTF8,  (void*)1, icuCaseFunc16},
154335
154336     {"like",   2, SQLITE_UTF8,         0, icuLikeFunc},
154337     {"like",   3, SQLITE_UTF8,         0, icuLikeFunc},
154338
154339     {"icu_load_collation",  2, SQLITE_UTF8, (void*)db, icuLoadCollation},
154340   };
154341
154342   int rc = SQLITE_OK;
154343   int i;
154344
154345   for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
154346     struct IcuScalar *p = &scalars[i];
154347     rc = sqlite3_create_function(
154348         db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
154349     );
154350   }
154351
154352   return rc;
154353 }
154354
154355 #if !SQLITE_CORE
154356 #ifdef _WIN32
154357 __declspec(dllexport)
154358 #endif
154359 SQLITE_API int SQLITE_STDCALL sqlite3_icu_init(
154360   sqlite3 *db, 
154361   char **pzErrMsg,
154362   const sqlite3_api_routines *pApi
154363 ){
154364   SQLITE_EXTENSION_INIT2(pApi)
154365   return sqlite3IcuInit(db);
154366 }
154367 #endif
154368
154369 #endif
154370
154371 /************** End of icu.c *************************************************/
154372 /************** Begin file fts3_icu.c ****************************************/
154373 /*
154374 ** 2007 June 22
154375 **
154376 ** The author disclaims copyright to this source code.  In place of
154377 ** a legal notice, here is a blessing:
154378 **
154379 **    May you do good and not evil.
154380 **    May you find forgiveness for yourself and forgive others.
154381 **    May you share freely, never taking more than you give.
154382 **
154383 *************************************************************************
154384 ** This file implements a tokenizer for fts3 based on the ICU library.
154385 */
154386 #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
154387 #ifdef SQLITE_ENABLE_ICU
154388
154389 /* #include <assert.h> */
154390 /* #include <string.h> */
154391
154392 #include <unicode/ubrk.h>
154393 /* #include <unicode/ucol.h> */
154394 /* #include <unicode/ustring.h> */
154395 #include <unicode/utf16.h>
154396
154397 typedef struct IcuTokenizer IcuTokenizer;
154398 typedef struct IcuCursor IcuCursor;
154399
154400 struct IcuTokenizer {
154401   sqlite3_tokenizer base;
154402   char *zLocale;
154403 };
154404
154405 struct IcuCursor {
154406   sqlite3_tokenizer_cursor base;
154407
154408   UBreakIterator *pIter;      /* ICU break-iterator object */
154409   int nChar;                  /* Number of UChar elements in pInput */
154410   UChar *aChar;               /* Copy of input using utf-16 encoding */
154411   int *aOffset;               /* Offsets of each character in utf-8 input */
154412
154413   int nBuffer;
154414   char *zBuffer;
154415
154416   int iToken;
154417 };
154418
154419 /*
154420 ** Create a new tokenizer instance.
154421 */
154422 static int icuCreate(
154423   int argc,                            /* Number of entries in argv[] */
154424   const char * const *argv,            /* Tokenizer creation arguments */
154425   sqlite3_tokenizer **ppTokenizer      /* OUT: Created tokenizer */
154426 ){
154427   IcuTokenizer *p;
154428   int n = 0;
154429
154430   if( argc>0 ){
154431     n = strlen(argv[0])+1;
154432   }
154433   p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
154434   if( !p ){
154435     return SQLITE_NOMEM;
154436   }
154437   memset(p, 0, sizeof(IcuTokenizer));
154438
154439   if( n ){
154440     p->zLocale = (char *)&p[1];
154441     memcpy(p->zLocale, argv[0], n);
154442   }
154443
154444   *ppTokenizer = (sqlite3_tokenizer *)p;
154445
154446   return SQLITE_OK;
154447 }
154448
154449 /*
154450 ** Destroy a tokenizer
154451 */
154452 static int icuDestroy(sqlite3_tokenizer *pTokenizer){
154453   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
154454   sqlite3_free(p);
154455   return SQLITE_OK;
154456 }
154457
154458 /*
154459 ** Prepare to begin tokenizing a particular string.  The input
154460 ** string to be tokenized is pInput[0..nBytes-1].  A cursor
154461 ** used to incrementally tokenize this string is returned in 
154462 ** *ppCursor.
154463 */
154464 static int icuOpen(
154465   sqlite3_tokenizer *pTokenizer,         /* The tokenizer */
154466   const char *zInput,                    /* Input string */
154467   int nInput,                            /* Length of zInput in bytes */
154468   sqlite3_tokenizer_cursor **ppCursor    /* OUT: Tokenization cursor */
154469 ){
154470   IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
154471   IcuCursor *pCsr;
154472
154473   const int32_t opt = U_FOLD_CASE_DEFAULT;
154474   UErrorCode status = U_ZERO_ERROR;
154475   int nChar;
154476
154477   UChar32 c;
154478   int iInput = 0;
154479   int iOut = 0;
154480
154481   *ppCursor = 0;
154482
154483   if( zInput==0 ){
154484     nInput = 0;
154485     zInput = "";
154486   }else if( nInput<0 ){
154487     nInput = strlen(zInput);
154488   }
154489   nChar = nInput+1;
154490   pCsr = (IcuCursor *)sqlite3_malloc(
154491       sizeof(IcuCursor) +                /* IcuCursor */
154492       ((nChar+3)&~3) * sizeof(UChar) +   /* IcuCursor.aChar[] */
154493       (nChar+1) * sizeof(int)            /* IcuCursor.aOffset[] */
154494   );
154495   if( !pCsr ){
154496     return SQLITE_NOMEM;
154497   }
154498   memset(pCsr, 0, sizeof(IcuCursor));
154499   pCsr->aChar = (UChar *)&pCsr[1];
154500   pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
154501
154502   pCsr->aOffset[iOut] = iInput;
154503   U8_NEXT(zInput, iInput, nInput, c); 
154504   while( c>0 ){
154505     int isError = 0;
154506     c = u_foldCase(c, opt);
154507     U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
154508     if( isError ){
154509       sqlite3_free(pCsr);
154510       return SQLITE_ERROR;
154511     }
154512     pCsr->aOffset[iOut] = iInput;
154513
154514     if( iInput<nInput ){
154515       U8_NEXT(zInput, iInput, nInput, c);
154516     }else{
154517       c = 0;
154518     }
154519   }
154520
154521   pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
154522   if( !U_SUCCESS(status) ){
154523     sqlite3_free(pCsr);
154524     return SQLITE_ERROR;
154525   }
154526   pCsr->nChar = iOut;
154527
154528   ubrk_first(pCsr->pIter);
154529   *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
154530   return SQLITE_OK;
154531 }
154532
154533 /*
154534 ** Close a tokenization cursor previously opened by a call to icuOpen().
154535 */
154536 static int icuClose(sqlite3_tokenizer_cursor *pCursor){
154537   IcuCursor *pCsr = (IcuCursor *)pCursor;
154538   ubrk_close(pCsr->pIter);
154539   sqlite3_free(pCsr->zBuffer);
154540   sqlite3_free(pCsr);
154541   return SQLITE_OK;
154542 }
154543
154544 /*
154545 ** Extract the next token from a tokenization cursor.
154546 */
154547 static int icuNext(
154548   sqlite3_tokenizer_cursor *pCursor,  /* Cursor returned by simpleOpen */
154549   const char **ppToken,               /* OUT: *ppToken is the token text */
154550   int *pnBytes,                       /* OUT: Number of bytes in token */
154551   int *piStartOffset,                 /* OUT: Starting offset of token */
154552   int *piEndOffset,                   /* OUT: Ending offset of token */
154553   int *piPosition                     /* OUT: Position integer of token */
154554 ){
154555   IcuCursor *pCsr = (IcuCursor *)pCursor;
154556
154557   int iStart = 0;
154558   int iEnd = 0;
154559   int nByte = 0;
154560
154561   while( iStart==iEnd ){
154562     UChar32 c;
154563
154564     iStart = ubrk_current(pCsr->pIter);
154565     iEnd = ubrk_next(pCsr->pIter);
154566     if( iEnd==UBRK_DONE ){
154567       return SQLITE_DONE;
154568     }
154569
154570     while( iStart<iEnd ){
154571       int iWhite = iStart;
154572       U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
154573       if( u_isspace(c) ){
154574         iStart = iWhite;
154575       }else{
154576         break;
154577       }
154578     }
154579     assert(iStart<=iEnd);
154580   }
154581
154582   do {
154583     UErrorCode status = U_ZERO_ERROR;
154584     if( nByte ){
154585       char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
154586       if( !zNew ){
154587         return SQLITE_NOMEM;
154588       }
154589       pCsr->zBuffer = zNew;
154590       pCsr->nBuffer = nByte;
154591     }
154592
154593     u_strToUTF8(
154594         pCsr->zBuffer, pCsr->nBuffer, &nByte,    /* Output vars */
154595         &pCsr->aChar[iStart], iEnd-iStart,       /* Input vars */
154596         &status                                  /* Output success/failure */
154597     );
154598   } while( nByte>pCsr->nBuffer );
154599
154600   *ppToken = pCsr->zBuffer;
154601   *pnBytes = nByte;
154602   *piStartOffset = pCsr->aOffset[iStart];
154603   *piEndOffset = pCsr->aOffset[iEnd];
154604   *piPosition = pCsr->iToken++;
154605
154606   return SQLITE_OK;
154607 }
154608
154609 /*
154610 ** The set of routines that implement the simple tokenizer
154611 */
154612 static const sqlite3_tokenizer_module icuTokenizerModule = {
154613   0,                           /* iVersion */
154614   icuCreate,                   /* xCreate  */
154615   icuDestroy,                  /* xCreate  */
154616   icuOpen,                     /* xOpen    */
154617   icuClose,                    /* xClose   */
154618   icuNext,                     /* xNext    */
154619 };
154620
154621 /*
154622 ** Set *ppModule to point at the implementation of the ICU tokenizer.
154623 */
154624 SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
154625   sqlite3_tokenizer_module const**ppModule
154626 ){
154627   *ppModule = &icuTokenizerModule;
154628 }
154629
154630 #endif /* defined(SQLITE_ENABLE_ICU) */
154631 #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
154632
154633 /************** End of fts3_icu.c ********************************************/